我最近发现了一段代码,它在 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));
关于java - Bouncy CaSTLe 在 CBC 模式下使用 AES 进行基于密码的加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7916617/