Java RC4 Encryption |
||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||||||||||||
|
||||||||||||||
The Encode and Decode are performed by the same function.
The file is a working example; you only need the RC4 function in your own pages.
There are a couple of Test Vectors (that don't have nulls in them) in the following Form's code:
Here's the code:function RC4(Key, Data) { KeyBytes=new Array(255); CypherBytes=new Array(255); for(i=0; i<256; ++i) { KeyBytes[i]=Key.charCodeAt(i % Key.length); CypherBytes[i]=i; } Jump=0; for(i=0; i<256; ++i) { Jump=(Jump+CypherBytes[i]+KeyBytes[i]) & 0xFF; Tmp=CypherBytes[i]; // Swap: CypherBytes[i]=CypherBytes[Jump]; CypherBytes[Jump]=Tmp; } i=0; Jump=0; Result=""; for(X=0; X < Data.length; ++X) { i=(i+1) & 0xFF; Tmp=CypherBytes[i]; Jump=(Jump+Tmp) & 0xFF; T=(Tmp+CypherBytes[Jump]) & 0xFF; CypherBytes[i]=CypherBytes[Jump]; // Swap: CypherBytes[Jump]=Tmp; Result+=String.fromCharCode(Data.charCodeAt(X)^CypherBytes[T]); } return Result; }
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.