我有一个私钥文件(PEM BASE64编码).我想用它来解密一些其他数据.使用Java我试图读取文件并解码其中的BASE64编码数据...这是我试过的代码片段....
import java.io.*;
import java.nio.ByteBuffer;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import com.ibm.crypto.fips.provider.RSAPrivateKey;
import com.ibm.misc.BASE64Decoder;
public class GetPrivateKey {
public static RSAPrivateKey get() throws Exception {
File privateKeyFile = new File("privatekey.key");
byte[] encodedKey = new byte[(int) privateKeyFile.length()];
new FileInputStream(privateKeyFile).read(encodedKey);
ByteBuffer keyBytes = new BASE64Decoder().decodeBufferToByteBuffer(encodedKey.toString());
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyBytes.array());
KeyFactory kf = KeyFactory.getInstance("RSA", "IBMJCEFIPS");
RSAPrivateKey pk = (RSAPrivateKey) kf.generatePrivate(privateKeySpec);
return pk;
}
public static void main(String[] args) throws Exception {
PrivateKey privKey = FormatMePlease.get();
System.out.println(privKey.toString());
}
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
Exception in thread …Run Code Online (Sandbox Code Playgroud) 是否可以将 PKCS#8 编码的 RSA 私钥转换为 PKCS#1?我知道这可以通过 openssl 轻松完成,但是可以用 Java 完成吗?
我有一个加密的私钥,我知道密码.
我需要使用Java库解密它.
我不想使用BouncyCastle,除非没有其他选择.根据以往的经验,有太多的变化,没有足够的文档.
私钥是这种形式:
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,56F3A98D9CFFA77A
X5h7SUDStF1tL16lRM+AfZb1UBDQ0D1YbQ6vmIlXiK....
.....
/KK5CZmIGw==
-----END RSA PRIVATE KEY-----
Run Code Online (Sandbox Code Playgroud)
我相信关键数据是Base64编码,因为我看到\r\n64个字符后.
我尝试了以下解密密钥:
import java.security.Key;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.crypto.EncryptedPrivateKeyInfo;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public String decrypt(String keyDataStr, String passwordStr){
// This key data start from "X5... to =="
char [] password=passwordStr.toCharArray();
byte [] keyDataBytes=com.sun.jersey.core.util.Base64.decode(keyDataStr);
PBEKeySpec pbeSpec = new PBEKeySpec(password);
EncryptedPrivateKeyInfo pkinfo = new EncryptedPrivateKeyInfo(keyDataBytes);
SecretKeyFactory skf = SecretKeyFactory.getInstance(pkinfo.getAlgName());
Key secret = skf.generateSecret(pbeSpec);
PKCS8EncodedKeySpec keySpec = pkinfo.getKeySpec(secret); …Run Code Online (Sandbox Code Playgroud) 我有一个存储为字符串的 RSA 私钥,我需要将其转换为 PrivateKey 对象以与 API 一起使用。我可以找到人们从私钥文件转换为字符串的例子,但反过来不行。
我设法将它转换为 PrivateKey 对象,但它在 PKCS8 中,当我需要它是 PKCS1 时,我知道 Java 没有 PKCS1EncodedKeySpec
byte[] key64 = Base64.decodeBase64(privateKeyString.getBytes());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
KeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
Run Code Online (Sandbox Code Playgroud) java ×4
pkcs#8 ×3
rsa ×2
certificate ×1
cryptography ×1
encryption ×1
jce ×1
openssl ×1
pkcs#1 ×1
private-key ×1
security ×1
x509 ×1