gpt4 book ai didi

java - C# 和 Java 中的 AES 加密文件

转载 作者:行者123 更新时间:2023-12-01 19:34:13 27 4
gpt4 key购买 nike

我用 C# 方法加密了文件:

public byte[] Crypt(byte[] filearray, string sKey)
{
AesManaged DES = new AesManaged();
DES.Key = Encoding.UTF8.GetBytes(sKey);
DES.Mode = CipherMode.ECB;
DES.Padding = PaddingMode.PKCS7;
ICryptoTransform crypt = DES.CreateEncryptor();
byte[] cipher = crypt.TransformFinalBlock(niz, 0, filearray.Length);
String encryptedText = Convert.ToBase64String(cipher);
return cipher.ToArray();
}

现在我尝试用Java解密文件:

private static byte[] transform(string base64Key, final byte[] fileBytes) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchProviderException
{
final byte[] keyBytes = base64Key.getBytes(StandardCharsets.UTF_8);
final byte[] ivBytes = base64Iv.getBytes(StandardCharsets.UTF_8);
final SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
final IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
byte[] transformedBytes = null;
try
{
Security.addProvider(new BouncyCastleProvider());
final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");;
cipher.init(Cipher.DECRYPT_MODE, keySpec);
transformedBytes = cipher.doFinal(fileBytes);
}
catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException |
BadPaddingException e)
{
e.printStackTrace();
}
return transformedBytes;
}

当我尝试执行此函数时,出现异常

javax.crypto.BadPaddingException: pad block corrupted at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher$BufferedGenericBlockCipher.doFinal(Unknown Source) at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(Unknown Source) at javax.crypto.Cipher.doFinal(Cipher.java:2165)

最佳答案

尝试使用不同的填充,例如:

Cipher.getInstance("AES/ECB/NoPadding");

Cipher.getInstance("AES/ECB/PKCS5Padding");

而不是

Cipher.getInstance("AES/ECB/PKCS7Padding");

关于java - C# 和 Java 中的 AES 加密文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59236368/

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