gpt4 book ai didi

java - 如何在java中使用私钥(.private)解密数据

转载 作者:行者123 更新时间:2023-11-30 04:40:42 26 4
gpt4 key购买 nike

数据在 PHP 中使用 OpenSSL 加密,我想解密 java,但在 java 中出现错误

PHP 加密代码-

public function getEncryptedString($cardNumber,$key_id){
$encryptedCardNumber = '';
$key_name = "key_{$key_id}";
$pub_key_path =$key_name.".public";
$fp=fopen ($pub_key_path,"r"); //Open the public key (key_8.public)
$pub_key = fread($fp,8192); //Read public key key (key_8.public) into
fclose($fp);
openssl_public_encrypt($cardNumber,$encryptedCardNumber,$pub_key);
if($key_id > 4) return rawurlencode(base64_encode($encryptedCardNumber));
else return addslashes($encryptedCardNumber);

}

JAVA解密代码-

public static String getDecryptedValue(int keyId,String encryptedCCNumber ,String passPhrase){
String result="";

String privateKeyFileName="key_8.private";
String privateKeyLocation= PropertiesUtil.getProperty("PUBLIC_PRIVATE_KEY_LOCATION");
String privateKeyFileNameLocation=privateKeyLocation+privateKeyFileName;
String decryptedValue= getDecryptedMessage(privateKeyFileNameLocation,encryptedCCNumber,passPhrase);
return result;

}


public static String getDecryptedMessage(String privateKeyFileNameLocation, String encryptedCCNumber,String passPhrase)
{
byte[] decodedBytesCCNumber= Base64.decodeBase64(encryptedCCNumber.getBytes());
byte[] decryptedMessage=null;
try {
Cipher cipher = Cipher.getInstance("RSA");

PrivateKey privateKey = getPrivateKey(privateKeyFileNameLocation,passPhrase);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
decryptedMessage = cipher.doFinal(decodedBytesCCNumber);

} catch (Throwable t) {
t.printStackTrace();
}

System.out.println("new String(decryptedMessage)"+new String(decryptedMessage));
return new String(decryptedMessage);

}

private static PrivateKey getPrivateKey(String privateKeyFileNameLocation,String passPhrase) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream(privateKeyFileNameLocation), passPhrase.toCharArray());
String alias = (String) ks.aliases().nextElement();
KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(passPhrase.toCharArray()));
return keyEntry.getPrivateKey();
}

Java 代码出现以下错误。

java.io.IOException: toDerInputStream rejects tag type 45
at sun.security.util.DerValue.toDerInputStream(DerValue.java:847)
at sun.security.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:1221)
at java.security.KeyStore.load(KeyStore.java:1214)

最佳答案

您正在对密文进行 URL 编码 Base64 编码,但您只是解密它的 Base64 解码。要么丢失 URL 编码,要么在接收器处对其进行解码。

关于java - 如何在java中使用私钥(.private)解密数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12388779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com