简体   繁体   English

RC4实现之间的差异

[英]Difference between RC4 implementations

I have to implement a RC4 cipher in NodeJS, here is the code: 我必须在NodeJS中实现RC4密码,这是代码:

function cipher (CRYPTO, str) {
  const cipher = crypto.createCipher(CRYPTO.cipherAlgorithm, CRYPTO.password);

  return Buffer.concat([
    cipher.update(str, 'utf-8'),
    cipher.final()
  ]).toString(CRYPTO.encoding);
}

const CRYPTO = {
  cipherAlgorithm: 'rc4',
  password: 'trololol',
  encoding: 'base64'
};

cipher(CRYPTO, '0612345678');
// returns 'yTXp/PZzn+wYsQ=='

When i check my implementation with open ssl, i've got the same result: 当我用open ssl检查我的实现时,我得到了相同的结果:

echo -ne "0612345678" |  openssl  rc4 -pass "pass:trololol" -e  -nosalt | base64
> yTXp/PZzn+wYsQ==

But with our partner implementation, the result is really different. 但是,通过我们的合作伙伴实施,结果确实不同。 It is written in Java so i tried to do one and i have the same result than him: 它是用Java编写的,所以我尝试做一个,结果与他相同:

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import javax.xml.bind.DatatypeConverter;

public class Encryptor {
    private static String algorithm = "RC4";
    public static String encrypt(String key, String value) {
        try {
            SecretKeySpec rc4Key = new SecretKeySpec(key.getBytes(), algorithm);
            Cipher rc4 = Cipher.getInstance(algorithm);

            rc4.init(Cipher.ENCRYPT_MODE, rc4Key);
            byte [] encrypted = rc4.update(value.getBytes());
            return DatatypeConverter.printBase64Binary(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        String key = "trololol";
        String value = "0612345678";

        System.out.println(encrypt(key, value));
    }
}

Running the above gives: 运行上面的给出:

javac Encryptor.java && java Encryptor  
> LYlbWr0URiz+wA==

Is it possible that the RC4 algorithm in Java differs from the other ones or is there something wrong in the Java implementation? Java中的RC4算法是否有可能与其他算法不同,或者Java实现中存在问题?

The difference is "password" vs "key." 区别在于“密码”与“密钥”。

For example with node and OpenSSL, "password" means some value to hash ( using MD5 ) to generate the key for encryption/decryption. 例如,对于node和OpenSSL,“ password”表示要散列的某些值( 使用MD5 )以生成用于加密/解密的密钥。

If you instead use the "password" value as the key (with an empty IV), you will match the value received from Java. 如果改为使用“ password”值作为键(IV为空),则将匹配从Java接收到的值。 For example with node, change to the createCipheriv() function: 例如,使用node,更改为createCipheriv()函数:

crypto.createCipheriv(CRYPTO.cipherAlgorithm, CRYPTO.password, Buffer.alloc(0));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM