使用充气城堡在Java中加密xml文件的示例

任何人都可以向我展示(或提供一个链接)如何使用充气城堡加密Java文件的示例? 我查看过bouncycastle.org但找不到任何API的文档。 即使只是知道使用哪些课程对我来说也是一个很大的帮助!

您想要执行什么类型的加密? 基于密码(PBE),对称,非对称? 它完全取决于您如何配置密码 。

您不必使用任何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); } } 

您可以在http://bouncycastle.org/docs/docs1.6/index.html上查看java文档

您可以从此页面下载示例: http : //eu.wiley.com/WileyCDA/WileyTitle/productCd-0764596330,descCd-DOWNLOAD.html

如果您没有任何使用BountyCastle的特殊原因,可以在此处找到有关Java内置加密支持的详细教程和背景信息,其中包含几个代码示例。

找到Bouncy Castle java代码示例的最佳位置是在充气城堡Bouncy Castle的测试套件中经历测试用例最新发布的java

这些测试套件包含可以轻松使用的非弃用代码

虽然它是对您的问题的间接答案,但也许您会发现使用jasypt处理加密很有用。

这是一个如何使用jasypt加密文件的示例: http : //www.jasypt.org/encrypting-configuration.html

而且,以下是如何将bouncy castle配置为jasypt的提供者: http : //www.jasypt.org/bouncy-castle.html