0

我们使用下面的代码在 Java 中加密

public encrypt(String text) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), SALT, ITERATION_COUNT, KEY_LENGTH); //256 bit
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
    this.ecipher = Cipher.getInstance("AES");
    this.ecipher.init(Cipher.ENCRYPT_MODE, secret);
    byte[] bytes = encrypt.getBytes("UTF-8");
    byte[] encrypted = this.ecipher.doFinal(bytes);
    return Base64.encodeBase64String(encrypted);
}

我们的供应商正在使用 C# 来解密数据 他的代码

string Decrypt(string textToDecrypt, string key)
{
    RijndaelManaged rijndaelCipher = new RijndaelManaged();
    rijndaelCipher.Mode = CipherMode.ECB;
    rijndaelCipher.KeySize = 0x80;
    rijndaelCipher.BlockSize = 0x80;
    byte[] encryptedData = Convert.FromBase64String(textToDecrypt);
    byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
    byte[] keyBytes = new byte[0x10];
    int len = pwdBytes.Length;
    if (len > keyBytes.Length) {
        len = keyBytes.Length;
    }
    Array.Copy(pwdBytes, keyBytes, len);
    rijndaelCipher.Key = keyBytes;
    byte[] plainText = rijndaelCipher.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length);
    return Encoding.UTF8.GetString(plainText); 
}

但他无法解密数据。他得到了一些垃圾数据。知道如何使用 C# 进行 Java 加密部分的解密。

4

1 回答 1

3

首先,不要对您的 java 代码有任何安全性暗示。ECB模式不是一个好的选择。

其次,C# 代码的问题在于它使用密码的原始字节而不是PBKDF2WithHmacSHA1java 代码使用的密钥。C# 中生成密钥的类是Rfc2898DeriveBytes

于 2013-03-08T15:19:01.670 回答