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

时间:2014-01-15 20:31:02

标签: java private-key pem

我知道关于这个话题还有其他一些问题,但没有一个问题能帮到我。我也尝试了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

1 个答案:

答案 0 :(得分:1)

我希望这可以帮到你。我复制了getPemPrivatekey的工作副本以及我在main函数中调用它的方式:

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 ...... //在这里实例化课程

 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”是我从包含该函数的类中实例化的对象的名称。 问候。