但$ init()只需要3个参数。我需要一种方法来执行以下操作:
but the init() only takes in 3 parameters. I need a way to do something like:
ecipher.init(Cipher.ENCRYPT_MODE, stringToEncrypt, secretKey, random);推荐答案
一般来说,你不需要产生随机的东西具有确定性行为的算法的数字。此外,当您使用ECB块模式时,您不需要IV,这是Java默认的模式。确切地说,Java默认为code $ c中的AES / ECB / PKCS5Padding Cipher.getInstance(AES)
In general you don't need something that generates random numbers for an algorithm that has deterministic behavior. Furthermore, you don't need an IV when you are using ECB block mode, which is what Java defaults to. To be precise, Java defaults to "AES/ECB/PKCS5Padding" for in Cipher.getInstance("AES").
所以你应该是这样的代码:
So you should be OK with code like this:
// 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编解码器解码十六进制字符串。
Now that looks a whole lot better. I've used the Apache commons codec for decoding the hexadecimal string.
请注意,您需要保存 realIV 与 encryptedData ,并且您没有包括完整性保护,例如一个MAC(用于密码,可能不需要)。
Note that you need to save the realIV with the encryptedData, and that you haven't included integrity protection, e.g. a MAC (for passwords, you may not need that though).
更多推荐
Android:使用iv和密钥加密AES 256位加密的字符串
发布评论