Post

Replies

Boosts

Views

Activity

Reply to Convert PEM format Curve25519 ECDH Keys with long length base64 string?
Thank you Quinn, After generating public and private keys need to generate PEM format like, -----BEGIN PUBLIC KEY----- // base64String -----END PUBLIC KEY----- -----BEGIN PRIVATE KEY----- // base64String -----END PRIVATE KEY----- This is the java code for generating keys and convert pem format , required same for this: @Log@Servicepublic class ECCService { @Value("${forwardsecrecy.ecc.curve:Curve25519}") String curve; @Value("${forwardsecrecy.ecc.algorithm:EC}") String algorithm; @Value("${forwardsecrecy.ecc.keyDerivationAlgorithm:ECDH}") String keyDerivationAlgorithm; @Value("${forwardsecrecy.ecc.provider:BC}") String provider; @Value("${forwardsecrecy.ecc.keyExpiryHrs:24}") int keyExpiry; private KeyPair generateKey() throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { KeyPairGenerator kpg; kpg = KeyPairGenerator.getInstance(algorithm, provider); X9ECParameters ecP = CustomNamedCurves.getByName(curve); ECParameterSpec ecSpec = EC5Util.convertToSpec(ecP); kpg.initialize(ecSpec); final KeyPair kp = kpg.genKeyPair(); log.info("Key pair generated " + kp.getPublic().getAlgorithm()); return kp; } public SerializedKeyPair getKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { final KeyPair kp = this.generateKey(); final String privateKey = this.getPEMEncodedStream(kp.getPrivate(),true); final String publicKey = this.getPEMEncodedStream(kp.getPublic(), false); Date date = new Date(); Calendar cl = Calendar. getInstance(); cl.setTime(date); cl.add(Calendar.HOUR, keyExpiry); TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // Quoted "Z" to indicate UTC, no timezone offset df.setTimeZone(tz); String expiryAsISO = df.format(cl.getTime()); final DHPublicKey dhPublicKey = new DHPublicKey(expiryAsISO,"",publicKey); final KeyMaterial keyMaterial = new KeyMaterial(keyDerivationAlgorithm,curve,"",dhPublicKey); final SerializedKeyPair serializedKeyPair = new SerializedKeyPair(privateKey, keyMaterial); return serializedKeyPair; } private String getPEMEncodedStream(final Key key, boolean privateKey) { final PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key.getEncoded()); final StringBuilder sb = new StringBuilder(); final String keyType = privateKey ? "PRIVATE" : "PUBLIC"; sb.append("-----BEGIN " + keyType + " KEY-----"); sb.append(new String(Base64.getEncoder().encode(pkcs8KeySpec.getEncoded()))); sb.append("-----END " + keyType + " KEY-----"); return sb.toString(); } }
Jan ’22