我得到了一个由第三方加密的卡片盘。他们使用 java 使用 48 个字符的密钥对 pan 进行加密。
使用在线工具,我可以获得与他们看到的相同的结果。但在代码中我得到一个“指定的密钥不是这个算法的有效大小。” 错误信息。
你能告诉我如何解决这个问题吗?
下面的代码片段
private void button1_Click(object sender, EventArgs e)
{
byte[] Results;
UTF8Encoding UTF8 = new UTF8Encoding();
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] TDESKey = UTF8Encoding.UTF8.GetBytes(key.Text);
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.IV = new byte[TDESAlgorithm.BlockSize / 8];
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToDecrypt = Convert.FromBase64String(decrypt.Text);
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
}
decryptedText.Text = UTF8.GetString(Results);
}
下面用于加密的代码
public static String encryptData(String toEncrypt, byte[] sharedKeyBytes){
byte[] encrypted = new byte[0];
try {
DESedeKeySpec keySpec = new DESedeKeySpec(sharedKeyBytes);
SecretKey key = SecretKeyFactory.getInstance(ALGORITHM_DESEDE).generateSecret(keySpec);
Cipher encrypter = Cipher.getInstance(TRANSFORMSATION_DESEDE_PADDED);
encrypter.init(Cipher.ENCRYPT_MODE, key);
byte[] input = toEncrypt.getBytes(UTF_8);
encrypted = encrypter.doFinal(input);
} catch (Exception e) {
throw new CryptoException("Exception caught when encrypting", e);
}
return new String(Base64.encodeBase64(encrypted));
}
这是我需要在 c# 中生成的等价物。这段代码在java中工作
public static String decryptTripleDES(String toDecrypt, byte[] customerSharedKeyBytes){
byte[] decrypted = new byte[0];
System.out.println(customerSharedKeyBytes.length);
try {
byte[] decodedValue = Base64.decodeBase64(toDecrypt.getBytes(UTF_8));
DESedeKeySpec keySpec = new DESedeKeySpec(customerSharedKeyBytes);
SecretKey key = SecretKeyFactory.getInstance(ALGORITHM_DESEDE).generateSecret(keySpec);
Cipher decrypter = Cipher.getInstance(TRANSFORMSATION_DESEDE_PADDED);
decrypter.init(Cipher.DECRYPT_MODE, key);
decrypted = decrypter.doFinal(decodedValue);
} catch (Exception e) {
throw new CryptoException("Exception caught when decrypting", e);
}
return new String(decrypted);
}
请就如何最好地解决这个问题提出建议。
谢谢