在Scala中生成公共和私有PGP密钥

时间:2018-04-02 18:10:39

标签: scala bouncycastle

我在scala项目中使用了充气城堡库,并编写了以下代码

def generateKeyPair(config: PGPKeyInput) : Unit = {
  Security.addProvider(new BouncyCastleProvider())
  val kpg = KeyPairGenerator.getInstance("RSA", "BC")
  kpg.initialize(config.numOfBits)
  val kp = kpg.generateKeyPair()
  val out1 = new FileOutputStream(s"${config.filename}-private.bpg")
  val out2 = new FileOutputStream(s"${config.filename}-public.bpg")
  val sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build().get(HashAlgorithmTags.SHA1)
  val keyPair = new JcaPGPKeyPair(PublicKeyAlgorithmTags.RSA_GENERAL, kp, new Date())
  val publicKey = keyPair.getPublicKey()
  val signerBuilder = new JcaPGPContentSignerBuilder(publicKey.getAlgorithm(), HashAlgorithmTags.SHA1)
  val secretKeyEncryptionBuilder = new JcePBESecretKeyEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5, sha1Calc).setProvider("BC").build(config.passphrase.toArray)
  val secretKey = new PGPSecretKey(PGPSignature.DEFAULT_CERTIFICATION, keyPair, config.username, sha1Calc, null, null, signerBuilder, secretKeyEncryptionBuilder)
  secretKey.encode(out1)
  secretKey.getPublicKey.encode(out2)
  out1.close()
  out2.close()
}

此代码有效,我获得了公钥和私钥文件,但内容都是二进制文件。

我想要创建公钥和私钥文件的方式是它们以

开头
"-----BEGIN PGP PUBLIC KEY BLOCK-----\nComment: GPGTools - https://gpgtools.org\n\nmQINBFp8jgIBEAC02oIv4ohWCy79/ksR4FhagDtV13a60Ca9N2NDgAd7WNRfx5e4\nr6Eqr0m3pinyPzqEyWQc2isa9/LL/Wlb3sBaOIbWtZtmQxlugqa9NaPVYahBkVeg\nT50IfD4wzURodrjYijp2gN5H4Qu1Tcgjxo=\n=hp34\n-----END PGP PUBLIC KEY BLOCK-----"

我应该对代码做出哪些更改,以便获得上面指定格式的密钥。

1 个答案:

答案 0 :(得分:1)

您应该使用ArmoredOutputStream课程。如果需要,您也可以包含可选标题。

它应该像包装out1和out2一样简单:

val out1 = new ArmoredOutputStream(new FileOutputStream(s"${config.filename}-private.bpg"))
val out2 = new ArmoredOutputStream(new FileOutputStream(s"${config.filename}-public.bpg"))