Created
February 12, 2020 01:07
-
-
Save fmonniot/f06e70a21b6bc00c6b66488b62c498a4 to your computer and use it in GitHub Desktop.
A short snippet to remember how to convert base64 encoded keys to their `java.security.PublicKey/PrivateKey` representation, using the i2p crypto library
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
import java.security.{KeyFactory, Security} | |
import java.util.Base64 | |
import net.i2p.crypto.eddsa.EdDSASecurityProvider | |
import net.i2p.crypto.eddsa.spec.{EdDSANamedCurveTable, EdDSAPrivateKeySpec, EdDSAPublicKeySpec} | |
import net.i2p.crypto.eddsa.EdDSAEngine | |
import java.security.MessageDigest | |
import java.nio.charset.StandardCharsets | |
val pubKeyEdDSA = "e1ylCW17UIGCOrKH9zI6cceZxNe93sPsKpM0sm72bEQ=" | |
val privKeyEdDSA = "jbcfwBz1WHFvyXp1lmUHOueiqMzQ1Q/fPgk+ppaHfkZ=" | |
// Should be done in the app, somewhere, before calling `getInstance` | |
Security.insertProviderAt(new EdDSASecurityProvider, 0) | |
// Interesting part | |
val pub = Base64.getDecoder.decode(pubKeyEdDSA) | |
val priv = Base64.getDecoder.decode(privKeyEdDSA) | |
val spec = EdDSANamedCurveTable.ED_25519_CURVE_SPEC | |
val kf = KeyFactory.getInstance("EdDSA") | |
val pu = kf.generatePublic(new EdDSAPublicKeySpec(pub, spec)) | |
val pr = kf.generatePrivate(new EdDSAPrivateKeySpec(priv, spec)) | |
// Here we got the public and private key as java.security.* interface | |
// Quick snippet to generate a signature based on the key above | |
val msg = "hello".getBytes(StandardCharsets.UTF_8) | |
val sgr = new EdDSAEngine(MessageDigest.getInstance(spec.getHashAlgorithm)) | |
sgr.initSign(pr) | |
sgr.update(msg) | |
val jcaSignature = Base64.getUrlEncoder.encodeToString(sgr.sign()).replace("=", "") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment