2014-01-15 117 views
1

我知道還有其他幾個關於該主題的問題,但他們都沒有幫助我。我也嘗試了BouncyCastle庫。有人可以幫我嗎? PEM文件看起來像:將PEM私鑰文件轉換爲JAVA私鑰對象

-----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

我希望這可以幫助你。我抄getPemPrivatekey的工作副本,我把它的主要功能的方式:

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 =新..... 。//實例化這裏的類

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」是我從包含該函數的類實例化的對象的名稱。 此致敬禮。