【问题标题】:Encrypt with base64 rsa public key in Node.js在 Node.js 中使用 base64 rsa 公钥加密
【发布时间】:2018-04-01 15:18:38
【问题描述】:

首先,我是一个初级程序员 我在用户端(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));
}

}

【问题讨论】:

    标签: java node.js encryption


    【解决方案1】:

    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;
    

    在 java EncryptDecrypt 类中

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

    而不是

    Cipher.getInstance("RSA");
    

    见: enter link description here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-23
      • 2011-11-07
      • 2011-11-10
      • 2013-05-07
      • 1970-01-01
      • 2015-04-02
      • 2011-08-16
      相关资源
      最近更新 更多