简体   繁体   中英

Encrypt with base64 rsa public key in Node.js

First of all, I'm a beginner programmer I created a pair of keys(rsa) on the user's side(android). I intend to send the public key to the server for future operations as a base64 string, and with the public key I will encode the next data and send it to the user.I use the server side of the nodejs. Unfortunately, all the content written in The internet did not mention encrypt with the base64 public key or at least I did not see it. Can someone help me? Thank

this my java code:

public class GenKey {
private  String stringPrivateKey;
private  String stringPublicKey;

@RequiresApi(api = Build.VERSION_CODES.O)
public GenKey() throws NoSuchAlgorithmException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(512,new SecureRandom());//1024 or 2048
    KeyPair kp = kpg.generateKeyPair();
    PublicKey publicKey = kp.getPublic();
    PrivateKey privateKey = kp.getPrivate();
    this.stringPublicKey = Base64.encodeToString(publicKey.getEncoded(), DEFAULT);
    this.stringPrivateKey =Base64.encodeToString(privateKey.getEncoded(), DEFAULT);
}
public  String getPublicKey(){
    return stringPublicKey;
}
public  String getPrivateKey(){
    return stringPrivateKey;
}

}

and:

public class EncryptDecrypt {
public static String encrypt(String publicKey, String cleartext) throws Exception {

    X509EncodedKeySpec ks = new X509EncodedKeySpec(Base64.decode(publicKey,DEFAULT));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey pub = kf.generatePublic(ks);
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, pub);
    byte[] encMsgBinary = cipher.doFinal(cleartext.getBytes());
    return Base64.encodeToString(encMsgBinary, DEFAULT);
}
public static String decrypt(String privateKey, String ciphertext) throws Exception {

    PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(Base64.decode(privateKey,DEFAULT));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey pvt = kf.generatePrivate(ks);
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, pvt);
    byte [] encrypted = Base64.decode(ciphertext,DEFAULT);
    return new String(cipher.doFinal(encrypted));
}

}

solved.use node-rsa;

var NodeRSA = require('node-rsa');
var key = new NodeRSA();
var public="-----BEGIN PUBLIC KEY-----\n"+publicKey+"\n"+"-----END PUBLIC KEY-----";
key.importKey(public,"pkcs8-public-pem");
var encrypted = key.encrypt(text, 'base64');
return encrypted;

and in java EncryptDecrypt class

Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");

instead of

Cipher.getInstance("RSA");

see: enter link description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM