· 9 years ago · Nov 24, 2016, 12:48 PM
1package com.helloit.main;
2
3import org.bouncycastle.bcpg.ArmoredOutputStream;
4import org.bouncycastle.bcpg.HashAlgorithmTags;
5import org.bouncycastle.jce.provider.BouncyCastleProvider;
6import org.bouncycastle.openpgp.*;
7import org.bouncycastle.openpgp.operator.PGPDigestCalculator;
8import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder;
9import org.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder;
10import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair;
11import org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyEncryptorBuilder;
12
13import java.io.FileOutputStream;
14import java.io.IOException;
15import java.io.OutputStream;
16import java.security.*;
17import java.util.Date;
18
19/**
20 */
21
22public class KeyGenerator {
23
24 private static void exportKeyPair(OutputStream secretOut, OutputStream publicOut, KeyPair pair,
25 String identity, char[] passPhrase, boolean armor)
26 throws IOException, InvalidKeyException, NoSuchProviderException, SignatureException, PGPException {
27 if (armor) {
28 secretOut = new ArmoredOutputStream(secretOut);
29 }
30
31 PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build().get(HashAlgorithmTags.SHA1);
32 PGPKeyPair keyPair = new JcaPGPKeyPair(PGPPublicKey.RSA_GENERAL, pair, new Date());
33 PGPSecretKey secretKey = new PGPSecretKey(PGPSignature.DEFAULT_CERTIFICATION, keyPair, identity, sha1Calc, null, null,
34 new JcaPGPContentSignerBuilder(keyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1),
35 new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.CAST5, sha1Calc).setProvider("BC").build(passPhrase));
36
37 secretKey.encode(secretOut);
38
39 secretOut.close();
40
41 if (armor) {
42 publicOut = new ArmoredOutputStream(publicOut);
43 }
44
45 PGPPublicKey key = secretKey.getPublicKey();
46
47 key.encode(publicOut);
48
49 publicOut.close();
50 }
51
52 public static void main(String[] args) throws Exception {
53 Security.addProvider(new BouncyCastleProvider());
54
55 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
56
57 kpg.initialize(2048);
58
59 KeyPair kp = kpg.generateKeyPair();
60
61 FileOutputStream out1 = new FileOutputStream("/Users/aronsinoai/Downloads/secret.asc");
62 FileOutputStream out2 = new FileOutputStream("/Users/aronsinoai/Downloads/pub.asc");
63
64 String identity = "webmaster@zzz.com";
65 char[] passPhrase = {'h', 'e', 'l', 'l', 'o'};
66 exportKeyPair(out1, out2, kp, identity, passPhrase, true);
67 }
68
69}