如何在Java中使用私钥解密消息 – RSA算法

huangapple go评论69阅读模式
英文:

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

问题

以下是您提供的内容的翻译:

由于我正在使用 `.cer` 文件生成加密字符串,但无法进行解密。

要进行解密,我有一个扩展名为 **.key** 的文件,在其中以以下内容开头:

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

算法:`RSA/ECB/PKCS1Padding`

// 使用公钥加密会话密钥
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;
}

但是如何使用 `.key` 文件解密上述字符串。

请帮助我。

我已经搜索了很多解决方案,但没有找到合适的方法。

-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAq+vXWmbEfeQ5543Pco59x4D224g+Bqvr2dN2fkz2TsvZqm5/
nlBb7YkDcQrVIIKGX0VfzJQuFEkPAG3zIXm14cuKVDJ+ubchKPHhGtdld6xQe56K
pGyeUP7aY0iKzbd+JP99T4I9hGJC3ADs+KfLEFGa9VvVigsFnpGECN+euW95c68m
vUj3HLIztMvRbWfvzvS3GOjyBfgIXUodpuzYoUChbWz7E4J43YRJpC5RxqKPkrYi
91DLUGkGA5PMqBJCnJr8ABqwq3qikJfhIPMMUjJhZYVfhrZoIDJwBuFSOyefkcBT
rxn4oY8HjliuDq3ymWZmsslb35N8M+e99ap8cwIDAQABAoIBAH/EMPKVR1gMAeCN
KmuHbACVXmA+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Kc960rjGfYpbhqJVEO662oEL9
25346MPkrRcLth6ioQ5dt8Ebl4p8tSAoLe/EKk2zDUSrFUXmuFd69iH2bi0Yjunm
Ph3GafgFU0loEX+KFPyuEF6PGuSwPwOlgRNn3kXmvIbg2b/DxRyB
-----END RSA PRIVATE KEY-----

请注意,我只提供了翻译部分,没有包括代码部分。如果您还有其他问题或需要进一步的帮助,请随时提问。

英文:

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
91DLUGkGA5PMqBJCnJr8ABqwq3qikJfhIP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
KDGUNmQ9rF3CoXLFr4k0SEEg+F+7Gq/M63s5Dt7PI0YkYu0nRXmgItDs86+F3Tlj
4uYWQQKBgEzystNlExDfGjKGKLQR1wawfXpg43iKc960rjGfYpbhqJVEO662oEL9
25346MPkrRcLth6ioQ5dt8Ebl4p8tSAoLe/EKk2zDUSrFUXmuFd69iH2bi0Yjunm
Ph3GafgFU0loEX+KFPyuEF6PGuSwPwOlgRNn3kXmvIbg2b/DxRyB
-----END RSA PRIVATE KEY-----

答案1

得分: 1

以下是您提供的代码的翻译部分:

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;
    // 逐行读取文件内容
    while ((strLine = br.readLine()) != null) {
        // 在控制台上打印内容
        res.add(strLine);
    }
    // 关闭输入流
    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 = ""; // 加密的字符串
    // ......
    // 将加密字符串加载到 enc 变量中
    // ......
    String dec = decrypt(enc, prvk, xform);
    System.out.println(dec);
}

注意:代码的翻译可能会因为格式的不同而产生微小的变化,但逻辑和功能保持不变。

英文:

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 &lt; len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) &lt;&lt; 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}
public static ArrayList&lt;String&gt; readLines(String path) throws FileNotFoundException, IOException{
ArrayList&lt;String&gt; res = new ArrayList&lt;String&gt;();
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 = &quot;RSA/NONE/PKCS1PADDING&quot;;
PrivateKey prvk = loadKeyPrivateHexStr(&quot;C:\\&quot;,&quot;/mykeyfile.key&quot; ,&quot;RSA&quot;)
String enc = &quot;&quot;; //encrypted string
......
//load encrypeted string into enc
......   
String dec = decrypt(enc, prvk, xform);
System.out.println(dec);
}

huangapple
  • 本文由 发表于 2020年9月22日 17:39:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/64007024.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定