Scala解密OpenPGP(GPG)加密文件

3
我如何在Scala中解密OpenPGP加密文件?我有公钥和私钥。
gpg --output file.txt --decrypt file.txt.gpg

工作正常。


可能是Java中使用PGP加密和解密的重复问题。 - oluies
1
@oluies 首先,这是Java编程语言,其次 - 大多数答案都已过时,而且没有一个被采纳。 - Caballero
当然,使用https://www.bouncycastle.org/。https://github.com/sbt/sbt-pgp - 包含您所需的代码示例。 - oluies
@oluies 这是一个用于签署构件的 SBT 插件,但没有在应用程序内使用它的示例。 - Caballero
它使用了Councy Castle版本进行签名,请查看BC Java文档 https://github.com/sbt/sbt-pgp/tree/master/gpg-library/src/main/scala/com/jsuereth/pgp - oluies
1个回答

0

https://github.com/sbt/sbt-pgp存储库中,有来自PR的加密/解密文件测试用例代码。它提供了使用PGP文件加密/解密的示例:

 package com.jsuereth.pgp

 import org.specs2.mutable._
 import sbt.io.IO

 import java.io.{BufferedWriter, File, FileWriter}

 class KeyGenSpec extends Specification {
 PGP.init()
 
 ...
 
 val user = "Test User <test@user.com>"
 val pw: Array[Char] = "test-pw".toCharArray
 val (pub, sec) = PGP.makeNewKeyRings(user, pw)

 "encrypt and decrypt file" in {
  IO withTemporaryDirectory { dir =>
    val fileContent = "Just one string"
    val testFile1 = new File(dir, "test1.txt")
    val testFile2 = new File(dir, "test2.txt")

    // original file
    val bw1 = new BufferedWriter(new FileWriter(testFile1))
    bw1.write(fileContent)
    bw1.close()

    val source1 = scala.io.Source.fromFile(testFile1.getAbsolutePath)
    val lines1 = try source1.mkString finally source1.close()
    //System.out.println(lines1)

    // encrypted -> decrypted file preparation
    val bw2 = new BufferedWriter(new FileWriter(testFile2))
    bw2.write(fileContent)
    bw2.close()

    val testFileEncrypted = new File(dir, "testEncrypted.txt")
    sec.publicKey.encryptFile(testFile2, testFileEncrypted)
    testFile2.delete()
    sec.secretKey.decryptFile(testFileEncrypted, pw)

    val source2 = scala.io.Source.fromFile(testFile2.getAbsolutePath)
    val lines2 = try source2.mkString finally source2.close()
    //System.out.println(lines2)

    lines1 must equalTo(lines2)
  }
 }
...
}

Source: https://github.com/CTiPKA/sbt-pgp/blob/develop/gpg-library/src/test/scala/com/jsuereth/pgp/KeyGenSpec.scala#L34


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接