1. 程式人生 > >使用BC進行數字信封操作

使用BC進行數字信封操作

載入BC:

...
Security.addProvider(new BouncyCastleProvider());
...

組數字信封:

public byte[] envelope(byte[] data, String certPath) throws Exception {
	CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509", "BC");

	FileInputStream bais = new FileInputStream(certPath);
	X509Certificate cert = (X509Certificate) certificatefactory.generateCertificate(bais);

	CMSTypedData msg = new CMSProcessableByteArray(data);

	CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
	edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(cert).setProvider("BC"));

	CMSEnvelopedData ed = edGen.generate(msg, new JceCMSContentEncryptorBuilder(PKCSObjectIdentifiers.rc4).setProvider("BC").build());

	byte[] result = ed.getEncoded();

	return result;
}

解數字信封:

public byte[] denvelope(byte[] data, String certPath, String passwd) throws Exception {
	Decoder decoder = Base64.getDecoder();
	CMSEnvelopedData ed = new CMSEnvelopedData(decoder.decode(data));

	RecipientInformationStore recipients = ed.getRecipientInfos();

	Collection<RecipientInformation> c = recipients.getRecipients();
	Iterator<RecipientInformation> it = c.iterator();

	KeyStore ks = KeyStore.getInstance("PKCS12");
	ks.load(new FileInputStream(certPath), passwd.toCharArray());

	String priKeyName = null;
	if (ks.aliases().hasMoreElements()) {
		priKeyName = ks.aliases().nextElement();
	}

	PrivateKey prikey = (PrivateKey) ks.getKey(priKeyName, passwd.toCharArray());

	byte[] result = null;
	if (it.hasNext()) {
		RecipientInformation recipient = (RecipientInformation) it.next();

		result = recipient.getContent(new JceKeyTransEnvelopedRecipient(prikey).setProvider("BC"));
	}

	return result;
}

求指正