我正在尝试在 C# 中编写一个加密函数,该函数生成一个可以在 Java 应用程序中解密的字符串。我从客户端收到的现有 Java 解密代码:
public static String encryptParameters(byte plainText[], String sKey)
throws RCPCipherException
{
Cipher cipher;
DESedeKeySpec dks = new DESedeKeySpec(_getKeyBytes(sKey));
java.security.Key secretKey = SecretKeyFactory.getInstance("DESede").generateSecret(dks);
cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(1, secretKey);
return Base64.encodeBase64URLSafeString(cipher.doFinal(plainText));
}
到目前为止,我只在 C# 中有这个:
public string Encrypt(string toEncrypt, string encryptionKey, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = Encoding.UTF8.GetBytes(toEncrypt);
if (useHashing)
{
var hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(Encoding.UTF8.GetBytes(encryptionKey));
hashmd5.Clear();
}
else
{
keyArray = Encoding.UTF8.GetBytes(encryptionKey);
}
var tripleDesCryptoServiceProvider = new TripleDESCryptoServiceProvider();
//set the secret key for the tripleDES algorithm
tripleDesCryptoServiceProvider.Key = keyArray;
//mode of operation. there are other 4 modes.
//We choose ECB(Electronic code Book)
tripleDesCryptoServiceProvider.Mode = CipherMode.ECB;
//padding mode(if any extra byte added)
tripleDesCryptoServiceProvider.Padding = PaddingMode.PKCS7;
var cTransform = tripleDesCryptoServiceProvider.CreateEncryptor();
//transform the specified region of bytes array to resultArray
var resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
//Release resources held by TripleDes Encryptor
tripleDesCryptoServiceProvider.Clear();
//Return the encrypted data into unreadable string format
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
可以做些什么来使它们兼容?
Java 函数中的纯文本字节数组参数是通过 String.getBytes("UTF-8") 创建的。