gpt4 book ai didi

java - 在 C# 中解密 AES 加密字符串

转载 作者:太空宇宙 更新时间:2023-11-04 13:04:01 25 4
gpt4 key购买 nike

我正在尝试在 C# 中从 Java 解密 AES 加密字符串。当我解密时,它返回乱码,并且与通过 Java 代码加密的原始纯文本不匹配。请指导我这里出了什么问题。

附上加密的Java代码和解密的C#代码。如果您需要更多详细信息,请告诉我。

我也尝试了 AesCryptoServiceProvider,但也不起作用。您可以在 C# 的注释代码中看到尝试过的代码。

请注意,我只能对 C# 代码进行更改以匹配 Java 代码,而无法对 Java 端进行任何编辑。

加密的Java代码:

/** encrypt cipher */
private static final Cipher ENCRYPT_CIPHER = generateCipher(Cipher.ENCRYPT_MODE);

private static String ENCRYPT_KEY = "key";

/**
* @param val
* @return encrypted value
* @throws Exception
*/
public String encrypt(final String val) throws Exception {
return new String(Base64.encodeBase64(ENCRYPT_CIPHER.doFinal(val.getBytes()), true)).toString();
}

/**
* @param encrypt
* @return cipher
*/
protected static Cipher generateCipher(final int encrypt) {
try {
final Cipher cipher = Cipher.getInstance("AES");
cipher.init(encrypt, SecretKeyFactory.getInstance("AES").generateSecret(new IBMAESKeySpec(Base64.decodeBase64(ENCRYPT_KEY.getBytes()))));
return cipher;
} catch (final Exception e) {
return null;
}
}

解密的C#代码:

private static String ENCRYPT_KEY = "key";
public String decodeString (String encodedStr)
{

/*using (var aesCryptoProvider = new AesCryptoServiceProvider())
{
aesCryptoProvider.BlockSize = 128;
aesCryptoProvider.KeySize = 256;
aesCryptoProvider.Key = Convert.FromBase64String(ENCRYPT_KEY.ToString());
aesCryptoProvider.Padding = PaddingMode.Zeros;
aesCryptoProvider.Mode = CipherMode.ECB;

using (var decryptor = aesCryptoProvider.CreateDecryptor())
using (var memoryStream = new MemoryStream(Convert.FromBase64String(encodedStr)))
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
using (var streamReader = new StreamReader(cryptoStream, Encoding.UTF8))
{
decodedStr = streamReader.ReadToEnd();
}
}
*/
using (AesManaged aesAlg = new AesManaged())
{
aesAlg.Key = Convert.FromBase64String(ENCRYPT_KEY.ToString()); ;
aesAlg.BlockSize = 128;
aesAlg.KeySize = 256;
aesAlg.Mode = CipherMode.ECB;
aesAlg.Padding = PaddingMode.Zeros;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor();

// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encodedStr)))
{
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.
decodedStr = srDecrypt.ReadToEnd();
}
}
}

}
}

最佳答案

这只是一个快速回答。还没有对此进行大量研究,但是您是否检查过字节序是否匹配?看起来 C# (.NET) 是小端字节序,但 JVM 是大端字节序。然而,我不确定它是否将其交换为网络传输(然后它只会匹配硬件)。只是一个想法。如果我发现任何其他内容,我会更新我的答案。

关于java - 在 C# 中解密 AES 加密字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34663554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com