RC4实现之间的区别

时间:2016-11-04 13:59:58

标签: java node.js cryptography

我必须在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=='

当我用open ssl检查我的实现时,我得到了相同的结果:

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

但是通过我们的合作伙伴实施,结果确实不同。它是用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));
    }
}

运行以上命令:

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

Java中的RC4算法是否可能与其他算法不同,或者Java实现中是否存在错误?

1 个答案:

答案 0 :(得分:2)

区别在于"密码" vs" key。"

例如,对于node和OpenSSL,"密码"表示哈希(using MD5)到生成加密/解密密钥的值。

如果您改为使用"密码"将value作为键(使用空IV),您将匹配从Java接收的值。例如,对于节点,请更改为createCipheriv()函数:

crypto.createCipheriv(CRYPTO.cipherAlgorithm, CRYPTO.password, Buffer.alloc(0));
相关问题