javascriptcharacter-encodingcryptojsrc4-ciphersymmetric-key

Can array of bytes be used as a key with CryptoJS.RC4.encrypt?


I need to use an array of bytes (non-printable characters) as a key for RC4 encryption. The plaintext is a string. It seems that CryptoJS.RC4.encrypt expects only strings for both plaintext and key. Am I correct? If not, how do I call encrypt() with string and array of bytes?


Solution

  • If you want to create a key value from a list of byte values, your best bet is to use the hex encoder function, CryptoJS.enc.Hex.parse:

    CryptoJS.enc.Hex.parse('48656c6c6f2c20576f726c6421');
    

    This will parse your input string as a list of two-character pairs that each described a byte value. In this case, the hex values would be 48, 65, 6c, 6c, 6f, etc. You can pass the result of the parse call directly into the encrypt/decrypt methods as the key parameter. (The result is a CryptoJS type called "WordArray," but you don't need to worry about the mechanics of this type; just pass it in as the key paramemter.)

    If you want to transform an array of numbers to a hex string, you can do this easily with a simple loop and .toString(16):

    var byteArr = [72, 101, 108, 108, 111, 44],
        str = "",
        byteVal;
    for(var i=0; i<byteArr.length; i++) {
        byteVal = byteArr[i];
        if(byteVal < 16) { str += "0"; }
        str += byteVal.toString(16);
    };