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

小编典典

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

}

}

2020-11-01

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值