Java生成PGP的公钥和密钥


一、PGP加密是什么?

PGP加密系统是采用公开密钥加密与传统密钥加密相结合的一种加密技术。它使用一对数学上相关的钥匙,其中一个(公钥)用来加密信息,另一个(私钥)用来解密信息。PGP采用的传统加密技术部分所使用的密钥称为“会话密钥”(sek)。

二、使用步骤

1.引入依赖

代码如下(示例):

<dependency>
   <groupId>org.bouncycastle</groupId>
   <artifactId>bcpg-jdk15on</artifactId>
   <version>1.64</version>
</dependency>

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.64</version>
</dependency>

2.生成密钥、公钥方法

代码如下(示例):

private static final String PROVIDER_BC = "BC";
private static final String RSA = "RSA";

static {
    if (Security.getProvider(PROVIDER_BC) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }
}
    
public static void generatePGPKeyPair(String identity, String passPhrase, int keyWidth,
                                          String pubKeyFile, String priKeyFile,String path) throws Exception {
    createDirectory(path);
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA, PROVIDER_BC);
    keyPairGenerator.initialize(keyWidth);
    KeyPair generateKeyPair = keyPairGenerator.generateKeyPair();
    OutputStream priOutputStream;
    OutputStream pubOutputStream;
    try {
        // key format without armored
        priOutputStream = new FileOutputStream(priKeyFile);
        pubOutputStream = new FileOutputStream(pubKeyFile);

        // the pass phrase for open private key
        char[] passPhrase_ = passPhrase.toCharArray();
        // Hash algorithm using SHA1 as certificate
        PGPDigestCalculator sha1Calc = (new JcaPGPDigestCalculatorProviderBuilder()).build().get(HashAlgorithmTags.SHA1);
        // Generate RSA key pair
        JcaPGPKeyPair jcaPGPKeyPair = new JcaPGPKeyPair(PGPPublicKey.RSA_GENERAL, generateKeyPair, new Date());
        PGPSecretKey pgpSecretKey = new PGPSecretKey(
                PGPSignature.DEFAULT_CERTIFICATION,
                jcaPGPKeyPair,
                identity,
                sha1Calc,
                null,
                null,
                new JcaPGPContentSignerBuilder(jcaPGPKeyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1),
                (new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.CAST5, sha1Calc)).setProvider(PROVIDER_BC).build(passPhrase_));
        String privateKeyString = new BASE64Encoder().encode(pgpSecretKey.getEncoded());
        priOutputStream.write(privateKeyString.getBytes());
        PGPPublicKey publicKey = pgpSecretKey.getPublicKey();
        String publicKeyString = new BASE64Encoder().encode(publicKey.getEncoded());
        pubOutputStream.write(publicKeyString.getBytes());
//            pgpSecretKey.encode(priOutputStream);
//            PGPPublicKey pgpPublicKey = pgpSecretKey.getPublicKey();
//            pgpPublicKey.encode(pubOutputStream);
        close(priOutputStream, pubOutputStream);
    } catch (Exception e){

    }
}

其他相关方法:

public static void close(Closeable... closeables) throws IOException {
   if (closeables != null) {
       for (Closeable closeable : closeables) {
           if (closeable != null) {
               closeable.close();
           }
       }
   }
}

public static void createDirectory(String path){
   File file = new File(path);
   if (!file.exists() && !file.isDirectory()) {
       file.mkdirs();
   }
}

调用测试:

public static void main(String[] args) throws Exception {
   String path = "src/main/resources/pgp/";
   System.out.println(path);
   String pubKeyFile = path + "PUBLIC_KEY_2048.asc";
   String priKeyFile = path + "PRIVATE_KEY_2048.asc";
   generatePGPKeyPair("", "", 2048, pubKeyFile,priKeyFile,path);
}

最终生成目录:
在这里插入图片描述


总结

以上demo传入identity和passphrase参数都为"".
加密文件时用public key,解密时用private key.
仅供学习。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值