我想加密Java和.Net中的字符串。但问题是这两种算法产生不同的结果。我正在使用三重DES加密算法。 它应该产生相同的结果。.Net和Java中三重DES加密的结果不同
我的.NET方法:
Public Function EncryptTripleDES(ByVal sIn As String, ByVal sKey As String) As String
Dim DES As New System.Security.Cryptography.TripleDESCryptoServiceProvider
Dim hashMD5 As New System.Security.Cryptography.MD5CryptoServiceProvider
' scramble the key
' Compute the MD5 hash.
DES.Key = hashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(sKey))
' Set the cipher mode.
DES.Mode = System.Security.Cryptography.CipherMode.ECB
' Create the encryptor.
Dim DESEncrypt As System.Security.Cryptography.ICryptoTransform = DES.CreateEncryptor()
' Get a byte array of the string.
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(sIn)
' Transform and return the string.
Return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length))
End Function
我的Java类:
public class TrippleDESEncryption {
private static final String UNICODE_FORMAT = "UTF8";
public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
private KeySpec keySpec;
private SecretKeyFactory secretKeyFactory;
private Cipher cipher;
byte[] keyAsBytes;
private String encryptionKey;
private String encryptionScheme;
SecretKey key;
public TrippleDESEncryption() throws Exception {
encryptionKey = "234342343423434234342343";
encryptionScheme = DESEDE_ENCRYPTION_SCHEME;
keyAsBytes = encryptionKey.getBytes(UNICODE_FORMAT);
keySpec = new DESedeKeySpec(keyAsBytes);
secretKeyFactory = SecretKeyFactory.getInstance(encryptionScheme);
cipher = Cipher.getInstance(encryptionScheme);
key = secretKeyFactory.generateSecret(keySpec);
}
/**
* Method To Encrypt The String
*/
public String encrypt(String unencryptedString) {
String encryptedString = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
BASE64Encoder base64encoder = new BASE64Encoder();
encryptedString = base64encoder.encode(encryptedText);
} catch (Exception e) {
e.printStackTrace();
}
return encryptedString;
}
}
你已经发布了一个java类与C#方法,所以我们不能告诉你正确的参数传递给C#方法。您使用C#中的ASCII和Java中的UTF-8来获取看起来错误的关键字节。我将首先检查这些GetBytes调用的结果。 –
**现在不要使用三重DES。**即使使用最大的192位密钥,它也只能提供最高112位的安全性。如果使用较短的密钥大小,则它只提供56或57位的安全性。 AES的速度会更快(处理器有一个特殊的AES-NI指令集),而且最低128位的密钥更加安全。 3DES的最大密文大小也有实际的限制。请参阅[3DES和AES的安全性比较](http://security.stackexchange.com/q/26179/45523)。 –
**切勿使用[ECB模式](http://crypto.stackexchange.com/q/14487/13022)**。它是确定性的,因此不具有语义安全性。您至少应该使用[CBC](http://crypto.stackexchange.com/q/22260/13022)或[CTR](http://crypto.stackexchange.com/a/2378/)这样的随机模式。 13022)。最好是对密文进行身份验证,以便像[padding oracle attack](http://crypto.stackexchange.com/q/18185/13022)这样的攻击是不可能的。这可以通过验证模式(如GCM或EAX)或[加密 - 然后MAC](http://crypto.stackexchange.com/q/202/13022)方案完成。 –