Skip to main content
 首页 » 编程设计

public-key-encryption中java.security.spec.InvalidKeySpecException : java. security.InvalidKeyException:IOException:检测过早的 EOF

2024年11月01日7yxwkf

我有这个代码:

// Turn the encoded key into a real RSA public key. 
// Public keys are encoded in X.509. 
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); 
KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
PublicKey publicKey = keyFactory.generatePublic(keySpec); 

错误:

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: Detect premature EOF

问题出在哪里?

请您参考如下方法:

public static PublicKey getPublicKey(String key) throws Exception { 
      byte[] keyBytes;   
      keyBytes = (new BASE64Decoder()).decodeBuffer(key);  
      X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  
      KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
      PublicKey publicKey = keyFactory.generatePublic(keySpec);  
      return publicKey; 
  } 

这就是我将“字符串 key ”转换为真正的 rsa key (PublicKey publicKey)的方法。 也许有帮助。