【问题标题】:Scala decrypt OpenPGP (GPG) encrypted fileScala解密OpenPGP(GPG)加密文件
【发布时间】:2015-03-20 10:49:08
【问题描述】:

如何在 scala 中解密 OpenPGP 加密文件?我有公钥和私钥,并且

gpg --output file.txt --decrypt file.txt.gpg

有效。

【问题讨论】:

标签: scala gnupg openpgp


【解决方案1】:

有从 PR 到 https://github.com/sbt/sbt-pgp 存储库的加密/解密文件测试用例代码。它提供了一个使用 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)
  }
 }
...
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 2018-02-23
    • 2021-07-12
    • 2019-08-10
    • 2018-12-27
    • 2016-06-08
    相关资源
    最近更新 更多