使用Node.js中的base64 rsa公钥进行加密

时间:2018-03-31 16:26:05

标签: java node.js encryption

首先,我是初学程序员 我在用户端(android)创建了一对键(rsa)。我打算将公钥作为base64字符串发送到服务器以供将来操作,并使用公钥我将编码下一个数据并将其发送给用户。我使用nodejs的服务器端。不幸的是,互联网上写的所有内容都没有提到使用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 个答案:

答案 0 :(得分:-1)

solve.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;

和java EncryptDecrypt类

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

而不是

Cipher.getInstance("RSA");

请参阅: enter link description here