当前位置: 首页 > 面试题库 >

Android:使用iv和密钥通过AES 256位加密对字符串进行加密

端木朝
2023-03-14
问题内容
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块模式时,您不需要IV,这是Java默认设置。确切地说,Java默认为中的"AES/ECB/PKCS5Padding"for
Cipher.getInstance("AES")

因此,您应该可以使用如下代码:

// 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(口令,你可能不需要,虽然)。



 类似资料:
  • 我将AES与salt和IV一起用于加密和解密一个唯一的ID,但它给出了javax。加密。解密时出现BadPaddingException。 每次解密数据时给出的完整错误堆栈跟踪 加密方法- 解密方法 我是JCA的新手。

  • 下面是一个生成IV并将其转换为Base64字符串的示例... 但是,当我将IV的字符串表示形式传递到加密方法中,然后将其转换回字节数组时,下面的代码会失败,说明IV的大小不正确。 在字节数组和字符串表示之间有没有一种标准的转换加密密钥和IV的方法?

  • 我设置了Azure密钥库来检索RSA密钥进行加密。Azure发送给我一个KeyBundle类型的对象。此对象包含一个大小为2048的RSA类型的JsonWebKey。查看我的RSA密钥,它有两个方法,称为和。现在我正在尝试加密和解密一个简单的字符串,如下所示: 在System.Security.Cryptography.RSAImplementation.RSACNG.EncryptorDecry

  • 本文向大家介绍Java对字符串进行加密解密,包括了Java对字符串进行加密解密的使用技巧和注意事项,需要的朋友参考一下 要求:    *  对用户输入的每个字符的值进行加密,将解密后的字符串输出    *  对用户输入的已加密字符串进行解密并输出 实现代码: 运行结果: *加密过程: 请输入一个英文字符串或揭秘字符串: I Love You 加密或者解密之后的结果如下: 乩一乬乏乖久一乹乏乕 *解

  • 这是可能的还是加密必须共享和使用相同的密钥? 主要目的就是这样。 我将有两个客户端可以发送和接收加密数据到彼此。

  • 我想加密应用程序外的密钥并传递给应用程序。在应用程序中,当使用这些密钥时,必须再次使用加密时使用的密钥解密字符串。 在Swift中解密 AES