3

How can I decrypt OpenPGP encrypted file in scala? I have public and private keys and

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

works.

Caballero
  • 11,546
  • 22
  • 103
  • 163
  • possible duplicate of [PGP Encryption and Decryption with Java](http://stackoverflow.com/questions/9596298/pgp-encryption-and-decryption-with-java) – oluies Mar 20 '15 at 12:18
  • 1
    @oluies First, that's in java and second - most answers are outdated and none of them were accepted. – Caballero Mar 20 '15 at 12:30
  • Sure, Use https://www.bouncycastle.org/ https://github.com/sbt/sbt-pgp - has the code examples you need – oluies Mar 20 '15 at 12:38
  • @oluies this is an SBT plugin for signing artifacts, there are no examples of using it inside of the application. – Caballero Mar 20 '15 at 13:39
  • its using the councy castle version for signing, have a look at the bc java docs https://github.com/sbt/sbt-pgp/tree/master/gpg-library/src/main/scala/com/jsuereth/pgp – oluies Mar 22 '15 at 18:22

1 Answers1

0

There is encrypt/decrypt file test case code from PR to the https://github.com/sbt/sbt-pgp repository. It provides an example of usage of PGP file encryption/decryption with :

 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

CTiPKA
  • 2,944
  • 1
  • 24
  • 27