我最近遇到了一段在 CBC 模式下使用 BouncyCastle 的 PBE 和 AES 的代码(“PBEWithSHA1And256BitAES-CBC-BC”)。
public static final String ALGORITHM = "PBEWithSHA1And256BitAES-CBC-BC";
public static byte[] encrypt(final byte[] key, final byte[] salt, final byte[] plainText) throws CryptoException {
try {
// Create the encryption key
final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM, "BC");
final PBEKeySpec keySpec = new PBEKeySpec(new String(key).toCharArray());
final SecretKey secretKey = keyFactory.generateSecret(keySpec);
// Encrypt the plain text
final PBEParameterSpec cipherSpec = new PBEParameterSpec(salt, ITERATIONS);
final Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, cipherSpec);
final byte[] encryptedBytes = cipher.doFinal(plainText);
return encryptedBytes;
} catch (final Throwable t) {
throw new CryptoException(t.toString());
}
}
正如您所看到的,此代码没有指定正确的 IV 来执行 AES CBC 加密。
我不知道如何指定盐、迭代次数和要使用的 IV到密码。
我该怎么做呢?
谢谢。
可以使用jasypt(java简单加密)PBEWithSHA1And256BitAES-CBC-BC
示例代码如下所示:
StandardPBEStringEncryptor myFirstEncryptor = new StandardPBEStringEncryptor();
myFirstEncryptor.setProvider(new BouncyCastleProvider());
myFirstEncryptor.setAlgorithm("PBEWITHSHA256AND256BITAES-CBC-BC");
FixedStringSaltGenerator generator = new FixedStringSaltGenerator();
generator.setSalt("justAnotherSaltforGX");
//myFirstEncryptor.setSaltGenerator(new ZeroSaltGenerator());
myFirstEncryptor.setSaltGenerator(generator);
myFirstEncryptor.setKeyObtentionIterations(1);
String myPassword="creditCard";
myFirstEncryptor.setPassword(myPassword);
String myText="Redeem Gacha ";
String myFirstEncryptedText = myFirstEncryptor.encrypt(myText);
System.out.println("myFirstEncryptedText AES encrypt=="+myFirstEncryptedText);
System.out.println("myFirstEncryptedText AES decrypt =="+myFirstEncryptor.decrypt(myFirstEncryptedText));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)