[英]An example of encrypting an xml file in Java using bouncy castle
任何人都可以向我展示(或提供指向)如何使用充氣城堡在 Java 中加密文件的示例? 我查看了 bouncycastle.org,但找不到他們 API 的任何文檔。 即使只是知道要使用哪些類對我開始使用也會有很大幫助!
您要執行哪種類型的加密? 基於密碼 (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);
}
}
如果你沒有使用BouncyCastle的任何特別的原因,你可以找到關於Java一個很好的教程和背景信息內建有幾個代碼示例加密支持這里。
找到 Bouncy Castle java 代碼示例的最佳位置是通過 bouncy Castle Bouncy Castle 最新版本 java的測試套件中的測試用例
這些測試套件包含可以輕松使用的非棄用代碼
雖然這是對您問題的間接回答,但也許您會發現使用 jasypt 處理加密很有用。
以下是如何使用 jasypt 加密文件的示例: http : //www.jasypt.org/encrypting-configuration.html
而且,這里是如何將充氣城堡配置為 jasypt 的提供者: http : //www.jasypt.org/bouncy-castle.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.