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

风格不统一 提交于 2020-12-15 06:53:41

问题


As I'm generating the encrypted string using .cer file but unable to do decryption.

for decryption I have a file with .key extension and inside start with:

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

Algorithm: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.

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
rxn4oY8HjliuDq3ymWZmsslb35N8M+e99ap8cwIDAQABAoIBAH/EMPKVR1gMAeCN
KmuHbACVXmA+e2I36Hqkxf4NMkvTAXvAzQUZ0YfReIZNN6EGf9hT1WNTiH844HZA
QB1Tt5EL1EzIjhd0+qbU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iH2bi0Yjunm
Ph3GafgFU0loEX+KFPyuEF6PGuSwPwOlgRNn3kXmvIbg2b/DxRyB
-----END RSA PRIVATE KEY-----

回答1:


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


来源:https://stackoverflow.com/questions/64007024/how-to-decrypt-the-message-using-private-key-rsa-algorithm-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!