RSA使用Java加密并使用公共密钥在Java中解密

时间:2019-06-04 11:58:46

标签: javascript java encryption rsa public-key

我想通过RSA使用公开密钥在javascript中将字符串加密,然后使用私有密钥在java中解密。

我使用http://travistidwell.com/jsencrypt/demo/

生成了密钥对

我使用"crypto"这样在javascript中加密字符串:

typedProduceSomething

然后我将此字符串作为加密字符串:

    var crypto = require("crypto");
var publicKey = "-----BEGIN PUBLIC KEY-----\n" +
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCG2s04Qcph89sViJojs8VmIHk/\n" +
"mdoi1nUcflxACgunOeKzHXDRao/hxruSzOEzzPTW9yNbKiog1h0Sm6VWlmhvFgFS\n" +
"i4xC4yZ40wSpZCOYIF4ncNO2YUxFssxtGi+5qsn5+h8jDr93mtqFg9/INIdYHwZ5\n" +
"Mg8NjIanmlXyJdsgWwIDAQAB\n" +
"-----END PUBLIC KEY-----";

var strToEncrypt = "123456789123456789";
var buffer = Buffer.from(strToEncrypt);
var encrypted = crypto.publicEncrypt(publicKey, buffer);
console.log(encrypted.toString("base64"));

然后尝试在Java中将其解密:

RsaUtil.java

O2ywr7v5XPYu1O8r2K6SdouiLJN9L5cU6fIeUkhKG1IvpM7a/iFPpgVdztg/svoqiItBK5gOqyYVI/Du6qnuh7Nox5t+NMoON7gJHHcNMKAIbA8CI4C4rXDRCtLU3EGWjJiKfMKIWHIuXr8EqO3kceERC1dowI17UX7skItZe3s=

主:

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RsaUtil {
    /**
     * Constructs a private key (RSA) from the given string
     *
     * @param key PEM Private Key
     * @return RSA Private Key
     * @throws IOException
     * @throws GeneralSecurityException
     */
    public static RSAPrivateKey getPrivateKeyFromString(String key) throws IOException, GeneralSecurityException {
        String privateKeyPEM = key;

        // Remove the first and last lines
        privateKeyPEM = privateKeyPEM.replace("-----BEGIN RSA PRIVATE KEY-----\n", "");
        privateKeyPEM = privateKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");

        // Base64 decode data
        byte[] encoded = Base64.decodeBase64(privateKeyPEM);

        KeyFactory kf = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
        RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec);
        return privKey;
    }

    /**
     * Decrypts the text with the private key (RSA)
     *
     * @param cipherText Text to be decrypted
     * @param privateKey
     * @return Decrypted text (Base64 encoded)
     * @throws IOException
     * @throws GeneralSecurityException
     */
    public static String decrypt(String cipherText, PrivateKey privateKey) throws IOException, GeneralSecurityException {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return new String(cipher.doFinal(Base64.decodeBase64(cipherText)), "UTF-8");
    }
}

但是我得到这个错误:

public static void main(String[] args) {
        try{
            String privateKeyStr = "-----BEGIN RSA PRIVATE KEY-----\n" +
                    "MIICXAIBAAKBgQCG2s04Qcph89sViJojs8VmIHk/mdoi1nUcflxACgunOeKzHXDR\n" +
                    "ao/hxruSzOEzzPTW9yNbKiog1h0Sm6VWlmhvFgFSi4xC4yZ40wSpZCOYIF4ncNO2\n" +
                    "YUxFssxtGi+5qsn5+h8jDr93mtqFg9/INIdYHwZ5Mg8NjIanmlXyJdsgWwIDAQAB\n" +
                    "AoGAdYfw4B0G5AQCZ2wc2wzs+CtJQVM3uLEsdF70y6N1sJNUr0LzdrDnIaFxDWqe\n" +
                    "w+TXZxsRp3zCJsg1omgg26xO622NoTGUXLNYMAgo2PQhFjvmqsEe/vfQ+LqnvZyU\n" +
                    "wKv7Zbn7RNnyaJETnk2rFMGb1QJrO3rr3fCoViTHtrzR3EECQQDHrAmsq7Q918My\n" +
                    "NoJdWkBeTaIsRAGkM7FXNzzGTciNjxXB1P1/D0nCAUkgt5yTSz6DCWDccUlE4Jp7\n" +
                    "K6C+0tNLAkEArOXFOKuo9MJtYKfaisnn6TuUiMcaPgGRFmyXD7zFm+zsv1E+Dd4L\n" +
                    "iRraupWnUc/d/UOIqQ4gFfXjnSdO6sWtMQJALr7hGPKt5NiRkzzdsltBvJIySGi3\n" +
                    "dajAeOmuqcJmFHYOIu3pVwjOPMQuSaGS34z7GpRkf9dpzt1CbVmebW5QFwJAZqNM\n" +
                    "LfUxqoMVHVDn2oY7puhYp83SVUbm03IJRy1f/c1rSbO369GJ9Y08lZErr9R/Ss7h\n" +
                    "fMJG5+J9iZiBL7vDsQJBAJIZFV+BCqGe3PkwxCBZjLcF0TSScC+qC6wG7wehh4oA\n" +
                    "o9ZBNiJyUJm9VjLwOkpvyeeTXCSCXxtygo/liGCzLF4=\n" +
                    "-----END RSA PRIVATE KEY-----";

            PrivateKey privatekey = RsaUtil.getPrivateKeyFromString(privateKeyStr);
            String cipherText = "O2ywr7v5XPYu1O8r2K6SdouiLJN9L5cU6fIeUkhKG1IvpM7a/iFPpgVdztg/svoqiItBK5gOqyYVI/Du6qnuh7Nox5t+NMoON7gJHHcNMKAIbA8CI4C4rXDRCtLU3EGWjJiKfMKIWHIuXr8EqO3kceERC1dowI17UX7skItZe3s=";
            String decrypted = RsaUtil.decrypt(cipherText, privatekey);
            System.out.println(decrypted);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

有什么主意吗?

注意: 我的私钥以----- BEGIN RSA 私钥开头-----我不知道它是否真的重要

0 个答案:

没有答案