Skip to content

Instantly share code, notes, and snippets.

@giannoug
Created September 28, 2018 21:54
Show Gist options
  • Save giannoug/8c6cc552bea35c3e3b1f58cac0d115b1 to your computer and use it in GitHub Desktop.
Save giannoug/8c6cc552bea35c3e3b1f58cac0d115b1 to your computer and use it in GitHub Desktop.
package lib
import java.io.InputStream
import java.security.KeyFactory
import java.security.interfaces.{RSAPrivateKey, RSAPublicKey}
import java.security.spec.{PKCS8EncodedKeySpec, X509EncodedKeySpec}
import javax.inject.Inject
import play.api.Environment
/**
* https://stackoverflow.com/a/19387517/754565
*/
class PKCS8EncodedKeyReader @Inject()(environment: Environment) {
lazy val kf: KeyFactory = KeyFactory.getInstance("RSA")
def getPrivateKey(path: String): RSAPrivateKey = {
val spec = new PKCS8EncodedKeySpec(readKey(path))
kf.generatePrivate(spec).asInstanceOf[RSAPrivateKey]
}
def getPublicKey(path: String): RSAPublicKey = {
val spec = new X509EncodedKeySpec(readKey(path))
kf.generatePublic(spec).asInstanceOf[RSAPublicKey]
}
private def readKey(path: String) = {
val is: InputStream = environment.resourceAsStream(path)
.getOrElse(throw new RuntimeException(s"Could not read file $path"))
Stream.continually(is.read).takeWhile(_ != -1).map(_.toByte).toArray
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment