有人可以向我展示(或提供链接)如何使用充气城堡加密Java文件的示例吗?我查看过bouncycastle.org但找不到任何API的文档。即使只是知道使用哪些课程对我来说也是一个很大的帮助!
答案 0 :(得分:20)
您想要执行哪种加密?基于密码(PBE),对称,非对称?全部是你如何配置Cipher。
您不必使用任何BouncyCastle特定的API,只需使用它提供的算法。以下是使用BouncyCastle PBE密码加密字符串的示例:
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class PBE {
private static final String salt = "A long, but constant phrase that will be used each time as the salt.";
private static final int iterations = 2000;
private static final int keyLength = 256;
private static final SecureRandom random = new SecureRandom();
public static void main(String [] args) throws Exception {
Security.insertProviderAt(new BouncyCastleProvider(), 1);
String passphrase = "The quick brown fox jumped over the lazy brown dog";
String plaintext = "hello world";
byte [] ciphertext = encrypt(passphrase, plaintext);
String recoveredPlaintext = decrypt(passphrase, ciphertext);
System.out.println(recoveredPlaintext);
}
private static byte [] encrypt(String passphrase, String plaintext) throws Exception {
SecretKey key = generateKey(passphrase);
Cipher cipher = Cipher.getInstance("AES/CTR/NOPADDING");
cipher.init(Cipher.ENCRYPT_MODE, key, generateIV(cipher), random);
return cipher.doFinal(plaintext.getBytes());
}
private static String decrypt(String passphrase, byte [] ciphertext) throws Exception {
SecretKey key = generateKey(passphrase);
Cipher cipher = Cipher.getInstance("AES/CTR/NOPADDING");
cipher.init(Cipher.DECRYPT_MODE, key, generateIV(cipher), random);
return new String(cipher.doFinal(ciphertext));
}
private static SecretKey generateKey(String passphrase) throws Exception {
PBEKeySpec keySpec = new PBEKeySpec(passphrase.toCharArray(), salt.getBytes(), iterations, keyLength);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWITHSHA256AND256BITAES-CBC-BC");
return keyFactory.generateSecret(keySpec);
}
private static IvParameterSpec generateIV(Cipher cipher) throws Exception {
byte [] ivBytes = new byte[cipher.getBlockSize()];
random.nextBytes(ivBytes);
return new IvParameterSpec(ivBytes);
}
}
答案 1 :(得分:3)
您可以在http://bouncycastle.org/docs/docs1.6/index.html
查看java文档您可以从此页面下载示例:http://eu.wiley.com/WileyCDA/WileyTitle/productCd-0764596330,descCd-DOWNLOAD.html
答案 2 :(得分:1)
如果您没有使用BountyCastle的任何特殊原因,您可以通过几个代码示例here找到有关Java内置加密支持的良好教程和背景信息。
答案 3 :(得分:1)
找到Bouncy Castle java代码示例的最佳位置是通过充气城堡测试套件中的测试用例 Bouncy Castle latest release java
这些测试套件包含可以随时使用的非弃用代码
答案 4 :(得分:-1)
虽然这是对你的问题的间接答案,但也许你会发现使用jasypt处理加密很有用。
这是一个如何使用jasypt加密文件的示例: http://www.jasypt.org/encrypting-configuration.html
而且,以下是如何将bouncy castle配置为jasypt的提供者: http://www.jasypt.org/bouncy-castle.html