gpt4 book ai didi

java - Android:使用 iv 和 key 使用 AES 256 位加密来加密字符串

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

SecureRandom random = new SecureRandom(); // quite heavy, look into a lighter method.

String stringToEncrypt = "mypassword";
byte[] realiv = new byte[16];
random.nextBytes(realiv);
Cipher ecipher = Cipher.getInstance("AES");

SecureRandom random = new SecureRandom(); // quite heavy, look into a lighter method.

byte[] realiv = new byte[16];
random.nextBytes(realiv);

byte[] secret = "somelongsecretkey".getBytes();
SecretKeySpec secretKey = new SecretKeySpec(secret, "AES");
ecipher.init(Cipher.ENCRYPT_MODE, secretKey, random);
byte[] encryptedData = ecipher.doFinal();

但是init()只接受3个参数。我需要一种方法来做类似的事情:

ecipher.init(Cipher.ENCRYPT_MODE, stringToEncrypt, secretKey, random);

最佳答案

一般来说,您不需要为具有确定性行为的算法生成随机数的东西。此外,当您使用 ECB block 模式时,您不需要 IV,这是 Java 默认的模式。准确地说,Java 在 Cipher.getInstance("AES") 中默认使用 "AES/ECB/PKCS5Padding"

所以你应该可以接受这样的代码:

// lets use the actual key value instead of the platform specific character decoding
byte[] secret = Hex.decodeHex("25d6c7fe35b9979a161f2136cd13b0ff".toCharArray());

// that's fine
SecretKeySpec secretKey = new SecretKeySpec(secret, "AES");

// SecureRandom should either be slow or be implemented in hardware
SecureRandom random = new SecureRandom();

// first create the cipher
Cipher eCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

// filled with 00h characters first, use Cipher instance so you can switch algorithms
byte[] realIV = new byte[eCipher.getBlockSize()];

// actually fill with random
random.nextBytes(realIV);

// MISSING: create IvParameterSpec
IvParameterSpec ivSpec = new IvParameterSpec(realIV);

// create the cipher using the IV
eCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);

// NOTE: you should really not encrypt passwords for verification
String stringToEncrypt = "mypassword";

// convert to bytes first, but don't use the platform encoding
byte[] dataToEncrypt = stringToEncrypt.getBytes(Charset.forName("UTF-8"));

// actually do the encryption using the data
byte[] encryptedData = eCipher.doFinal(dataToEncrypt);

现在看起来好多了。我使用 Apache commons 编解码器来解码十六进制字符串。

请注意,您需要将 realIVencryptedData 一起保存,并且您尚未包含完整性保护,例如MAC(对于密码,您可能不需要)。

关于java - Android:使用 iv 和 key 使用 AES 256 位加密来加密字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13205019/

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