在Node.js中使用base64 RSA公钥加密

3
首先,我是一名初学者程序员。我在用户端(Android)创建了一对密钥(RSA)。我打算将公钥作为Base64字符串发送到服务器,以备将来使用,并使用公钥对下一个数据进行编码并将其发送给用户。我使用的是Node.js的服务器端。不幸的是,互联网上所有的内容都没有提到如何用Base64公钥加密,或者至少我没有看到。有人可以帮帮我吗?谢谢。
这是我的Java代码:
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;
}

}

以及:

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));
}

}

1个回答

2

已解决。使用 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;

在Java中,加密解密类为EncryptDecrypt。

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

替代

Cipher.getInstance("RSA");

看见:

请参见:enter link description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接