gpt4 book ai didi

java - 无法在 Android 上使用 AES 密码

转载 作者:行者123 更新时间:2023-12-01 16:54:28 25 4
gpt4 key购买 nike

我无法在 Android 上通过基本 AES 加密/解密往返单元测试。可能是我正在做的事情,但非常感谢您的指导:

public class EncryptionManager {
private static final byte[] keyBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 };
private static final byte[] ivBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };

public byte[] encrypt(byte[] plaintext) throws Exception {
Cipher cipher = getCipher(true);
return cipher.doFinal(plaintext);
}

public byte[] decrypt(byte [] ciphertext) throws Exception {
Cipher cipher = getCipher(false);
return cipher.doFinal(ciphertext);
}

private static Cipher getCipher(boolean encrypt) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
cipher.init(encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE,
secretKeySpec, ivParameterSpec);
return cipher;
}
}

失败的单元测试如下所示:

public class EncryptionManagerTest extends TestCase {
public void testShouldPbeRoundtrip() throws Exception {
String unencryptedStr = "foobargum";
byte[] unencrypted = unencryptedStr.getBytes();
EncryptionManager encryptionManager = new EncryptionManager();
byte[] encrypted = encryptionManager.encrypt(unencrypted);
String encryptedStr = new String(encrypted);
byte[] decrypted = encryptionManager.decrypt(encrypted);
String decryptedStr = new String(encrypted);

// assert
assertFalse("encryption not done",
unencryptedStr.equalsIgnoreCase(encryptedStr));
assertEquals("decryption didn't work", unencryptedStr,
decryptedStr);
}
}

错误:“解密未按预期进行:<[foobargum]>,而是:<[�3��jw� �|*�]>”

最佳答案

String cryptoStr = new String(encrypted); 是一个错误。加密生成的字节序列不太可能是给定字符集的有效字符串,特别是对于 Android 默认的 UTF-8 字符集。在将字节数组加密转换为 String 对象时,无效字节序列将以不可恢复的方式默默地替换为有效字符。

关于java - 无法在 Android 上使用 AES 密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34860527/

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