Reputation: 432
I have the bytes of a public key generated in Java with something like this:
package test;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.util.Base64;
public class Test {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
//generator.initialize(dsabits, sr);
KeyPair keyPair = generator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
byte[] encodedBytes = Base64.getEncoder().encode(publicKey.getEncoded());
System.out.println("decodedBytes " + new String(encodedBytes));
}
}
=> decodedBytes MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJQz9HgPKzGi+jT5uZ7CEU8mQyNZXm1IpPBIaMGZ2IW54iv+ptVAI8lG9mRNPTyZf07GZNnDSp5RcAn19lUh6eBxZ6R+Yg78rjw4UFfuGQPe8pKrAsy0ESOxLJrh2iQpa4H1DQ86Jq1kSUGFBMCpk68RyT+yQGwBCO8yomqp+7HQIDAQAB
Now I need to encrypt a string in node using this publick key. I tried with
var crypto = require("crypto");
var pubKeyB64 = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJQz9HgPKzGi+jT5uZ7CEU8mQyNZXm1IpPBIaMGZ2IW54iv+ptVAI8lG9mRNPTyZf07GZNnDSp5RcAn19lUh6eBxZ6R+Yg78rjw4UFfuGQPe8pKrAsy0ESOxLJrh2iQpa4H1DQ86Jq1kSUGFBMCpk68RyT+yQGwBCO8yomqp+7HQIDAQAB';
var pubKey = Buffer.from(pubKeyB64, 'base64');
var toEncrypt = 'ciao';
var buffer = new Buffer(toEncrypt);
var encrypted = crypto.publicEncrypt(pubKey, buffer);
console.log(encrypted.toString("base64"));
but unfortunately I get
Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
I don't have control over the public key generation format, unfortunately I have to use what I got there. Is there a way to use this key in node to encrypt a string somehow?
Upvotes: 1
Views: 936
Reputation: 38990
Assuming you mean https://nodejs.org/api/crypto.html#crypto_crypto_publicencrypt_key_buffer it says it wants as a string
A PEM encoded public or private key.
To create the PEM encoding, instead of converting your base64 to binary, break it into chunks of 64 chars except the last each followed by a newline, put a line -----BEGIN PUBLIC KEY-----
plus newline at the beginning and a line -----END PUBLIC KEY-----
plus newline at the end.
I could code this on the Java side but you say you can't change that, and I don't know enough js to code the nodejs side, so setting CW for anyone else to.
Upvotes: 4