将PEM私钥文件转换为Java PrivateKey对象

问题描述 投票:0回答:1

我知道关于该主题还有其他几个问题,但是它们都没有帮助我。我也尝试了

BouncyCastle
lib。有人可以在这里帮我吗? PEM文件看起来像:

    -----BEGIN RSA PRIVATE KEY-----
    MIIEpAIBAAKCAQEAq2eYtnTsEc/qyqS ...


   ... zY3WG++SA+amcXiO721hJWNC+uTbZ1bzQ==
    -----END RSA PRIVATE KEY-----
我使用此方法

public static PrivateKey getPemPrivateKey(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { File f = new File(PEMFILES_FOLDER+filename); FileInputStream fis = new FileInputStream(f); DataInputStream dis = new DataInputStream(fis); byte[] keyBytes = new byte[(int) f.length()]; dis.readFully(keyBytes); dis.close(); String temp = new String(keyBytes); //TODO care about the linefeeds String privKeyPEM = temp.replace("-----BEGIN RSA PRIVATE KEY-----\n", ""); privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", ""); System.out.println("Private key: \n"+privKeyPEM); Base64 b64 = new Base64(); byte [] decoded = b64.decode(privKeyPEM); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded); KeyFactory kf = KeyFactory.getInstance(RSA); return kf.generatePrivate(spec); }
我正在遇到此错误:

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence

	
我希望这可以帮助您。我复制了GetPemprivateKey的工作副本,以及在主要功能中称呼它的方式:
java private-key pem
1个回答
1
投票
public PrivateKey getPemPrivateKey(String filename, String algorithm) throws Exception { File f = new File(filename); FileInputStream fis = new FileInputStream(f); DataInputStream dis = new DataInputStream(fis); byte[] keyBytes = new byte[(int) f.length()]; dis.readFully(keyBytes); dis.close(); String temp = new String(keyBytes); String privKeyPEM = temp.replace("-----BEGIN PRIVATE KEY-----", ""); privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", ""); //System.out.println("Private key\n"+privKeyPEM); BASE64Decoder b64 = new BASE64Decoder(); byte[] decoded = b64.decodeBuffer(privKeyPEM); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded); KeyFactory kf = KeyFactory.getInstance(algorithm); return kf.generatePrivate(spec); }

主要程序看起来像这样:
...

gcsr = new ...... // instantiate the class here

privateKey = gcsr.getPemPrivateKey("c:\\testdir\\java_private.pem", "RSA");
BASE64Encoder encoder1 = new BASE64Encoder();
String s1 = encoder1.encodeBuffer(gcsr.getPrivateKey().getEncoded());
System.out.println("Private Key in Base64:" + s1 + "\n");

目前正在工作(我的计算机上的Java 8!)。 “ GCSR”是我从包含该函数的类实例化对象的名称。 问候
	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.