import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
Security.addProvider(new BouncyCastleProvider());
这样就成功配置了BouncyCastle库。如果需要使用BouncyCastle的加密算法,则可使用以下代码:
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.PBEParametersGenerator;
import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Base64;
public class BouncyCastleEncryptionUtils {
static BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new org.bouncycastle.crypto.engines.AESEngine());
public static void main(String args[]){
String message = "This is a secret!";
String password = "mysecretpassword";
String salt = "somesalt";
String cipherText = encrypt(message,password, salt);
System.out.println(cipherText);
String plainText = decrypt(cipherText,password, salt);
System.out.println(plainText);
}
public static String encrypt(String message, String password, String salt) {
PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator();
generator.init(password.getBytes(), salt.getBytes(), 1000);
byte[] keyBytes = ((KeyParameter) generator.generateDerivedParameters(256)).getKey();
byte[] ivBytes = new byte[16];