Skip to content

Instantly share code, notes, and snippets.

@v6ak
Created March 9, 2014 09:42
Show Gist options
  • Select an option

  • Save v6ak/9445287 to your computer and use it in GitHub Desktop.

Select an option

Save v6ak/9445287 to your computer and use it in GitHub Desktop.
val key: PGPPublicKey = ...
def encrypt(plaintext: String): String = {
val baos = new ByteArrayOutputStream()
val literalDataGenerator = new PGPLiteralDataGenerator()
val comData = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZLIB) // I've also tried other compression algorithms
val bytes = plaintext.getBytes("utf-8")
val BufferSize = 1 << 16
import resource.managed // The "managed" method with for is just a nice replacement of try/catch/finally{x.close()}
for{
edg <- managed(new PGPEncryptedDataGenerator(SymmetricKeyAlgorithmTags.CAST5, new SecureRandom(), "BC"))
_ = edg.addMethod(key)
armoredOut <- managed(new ArmoredOutputStream(baos))
encryptedOut <- managed(edg.open(armoredOut, bytes.length))
compressedOut <- managed(comData.open(encryptedOut))
literalOut <- managed(literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, "x.txt", new Date(), new Array[Byte](BufferSize)))
}{
literalOut.write(bytes)
literalOut.flush();
}
baos.toString
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment