[英]AES Negative bytes
以下是在 Java 中使用 AES 加密的摘录:
encryptedData = encryptCipher.doFinal(strToEncrypt.getBytes());
以下是c#中的摘录
DecryptStringFromBytes_Aes(encrypted, myAes.Key, myAes.IV);
两者都使用一个字节数组来加密另一个来解密,Java 中的加密会产生一些存储在字节数组中的负值。
C# 使用字节数组进行解密,但 C# 中的字节被定义为仅包含 0..255 之间的数字 - Java 将其字节类型定义为 -128 到 127。
因此,我无法将加密数据发送到用 C# 编写的远程应用程序,因为它无法使用从 Java 应用程序发送的字节数组进行解密。
有没有人想出一个解决方案,让我告诉java在加密时不要产生负数?
代码来自 Micrsoft,MemoryStream 需要 byte[] 来为加密代码创建流......无论是否提到,我都用 sbyte 替换了 byte[] 但无济于事,因为 MemoryStream 需要 byte[]
static string DecryptStringFromBytes_Aes(sbyte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("Key");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream((byte)cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
Java 的字节是有符号的,C# 字节是无符号的(C# 中还有一种没有人使用的sbyte
类型,它的工作方式类似于 Java 的字节)。
没关系。 它们在某些方面有所不同,即
int
,C# 的字节将被零扩展,Java 的字节将被符号扩展(这就是为什么在 Java 中使用字节时几乎总是看到& 0xFF
)。这些字节的实际值(即它们的位模式)才是真正重要的,0xAA 的字节将是 0xAA,无论您将其解释为 170(如在 C# 中)还是 -86(如在 Java 中)。 这是同一件事,只是将其打印为字符串的不同方式。
new MemoryStream((byte)cipherText))
绝对不会做正确的事情(或任何事情,它甚至不应该编译)。 相关的new MemoryStream((byte[])cipherText))
也不起作用,您不能在这样的原始数组之间进行转换。 cipherText
应该只是一个byte[]
开始。
您可以将其转换为带有某种编码的字符串,例如:
encryptedData = encryptCipher.doFinal(strToEncrypt.getBytes());
String s = new String(encryptedData, "Base-64");
使用相同的标准化编码,C# 和 Java 都应该能够从该字符串重建彼此的加密数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.