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

Lee*_*ner 12 java encryption bouncycastle

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

Kev*_*vin 20

您想要执行什么类型的加密?基于密码(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);
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 如果您收到java.security.InvalidKeyException:非法密钥大小参考:http://stackoverflow.com/a/6481658/234110 (2认同)