Created
September 28, 2018 21:54
-
-
Save giannoug/8c6cc552bea35c3e3b1f58cac0d115b1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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