简体   繁体   English

java中如何使用私钥-RSA算法解密消息

[英]How to decrypt the message using private key -RSA algorithm in java

As I'm generating the encrypted string using .cer file but unable to do decryption.当我使用.cer文件生成加密字符串但无法解密时。

for decryption I have a file with .key extension and inside start with:为了解密,我有一个扩展名为.key的文件,里面以:

-----BEGIN RSA PRIVATE KEY-----

Algorithm: RSA/ECB/PKCS1Padding算法: RSA/ECB/PKCS1Padding

  // encrypting session key using public key
         public static String encryptSessionKey_PublicKey(String data) throws  NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, CertificateException, FileNotFoundException {
            FileInputStream fin = new FileInputStream("D:\\cedge_uat\\STAR_cedgenetbanking_in.cer");
            CertificateFactory f = CertificateFactory.getInstance("X.509");
            X509Certificate certificate = (X509Certificate) f.generateCertificate(fin);
            PublicKey publicKey = certificate.getPublicKey();
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] cipherData = cipher.doFinal(data.getBytes());
            String encodedData = Base64.getEncoder().encodeToString(cipherData);
            return encodedData;
        }

But how to decrypt the above string using .keyfile .但是如何使用.keyfile解密上面的字符串。

Please help me.请帮我。

I've searched many solution but unable to get proper one.我搜索了很多解决方案,但无法找到合适的解决方案。

    -----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAq+vXWmbEfeQ5543Pco59x4D224g+Bqvr2dN2fkz2TsvZqm5/
nlBb7YkDcQrVIIKGX0VfzJQuFEkPAG3zIXm14cuKVDJ+ubchKPHhGtdld6xQe56K
pGyeUP7aY0iKzbd+JP99T4I9hGJC3ADs+KfLEFGa9VvVigsFnpGECN+euW95c68m
vUj3HLIztMvRbWfvzvS3GOjyBfgIXUodpuzYoUChbWz7E4J43YRJpC5RxqKPkrYi
91DLUGkGA5PMqBJCnJr8ABqwq3qikJfhIPMMUjJhZYVfhrZoIDJwBuFSOyefkcBT
rxn4oY8HjliuDq3ymWZmssl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RXmgItDs86+F3Tlj
4uYWQQKBgEzystNlExDfGjKGKLQR1wawfXpg43iKc960rjGfYpbhqJVEO662oEL9
25346MPkrRcLth6ioQ5dt8Ebl4p8tSAoLe/EKk2zDUSrFUXmuFd69iH2bi0Yjunm
Ph3GafgFU0loEX+KFPyuEF6PGuSwPwOlgRNn3kXmvIbg2b/DxRyB
-----END RSA PRIVATE KEY-----

I had this lying around - hope it'll do the job for you:我有这个 - 希望它能为你完成工作:

private static byte[] getByteArrayFromHex(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

public static ArrayList<String> readLines(String path) throws FileNotFoundException, IOException{
        ArrayList<String> res = new ArrayList<String>();
        FileInputStream fis = new FileInputStream(path);
        DataInputStream in = new DataInputStream(fis);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {
        // Print the content on the console
        res.add(strLine);
        }
        //Close the input stream
        br.close();
        in.close();
        fis.close();
        return res;
}

public static PrivateKey getPrivateKey(String privateKeyHex, String algorithm) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] encodedPrivateKey = new byte[privateKeyHex.length()];
        encodedPrivateKey = getByteArrayFromHex(privateKeyHex);
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
                encodedPrivateKey);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
        return privateKey;
    }

public static PrivateKey loadKeyPrivateHexStr(String path, String privateKeyFile,String algorithm)
            throws IOException, NoSuchAlgorithmException,
            InvalidKeySpecException {
        String hexPrivateKey = readLines(path + privateKeyFile).get(0); 
        PrivateKey privateKey = getPrivateKey(hexPrivateKey, algorithm);
        return  privateKey;
    }

private static byte[] decrypt(byte[] inpBytes, Key key, String xform) throws Exception {
        Cipher cipher = Cipher.getInstance(xform);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(inpBytes);
    }

private static String decrypt(String inpHexStr, Key key, String xform) throws Exception {
        return new String(decrypt(getByteArrayFromHex(inpHexStr), key, xform));
    }

public static void main(String[] args) throws NoSuchAlgorithmException, Exception { 
    String xform = "RSA/NONE/PKCS1PADDING";
    PrivateKey prvk = loadKeyPrivateHexStr("C:\\","/mykeyfile.key" ,"RSA")
    String enc = ""; //encrypted string
    ......
    //load encrypeted string into enc
    ......   
    String dec = decrypt(enc, prvk, xform);
    System.out.println(dec);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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