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

16,823
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;
  }

this is how i turn "String key" into real rsa key(PublicKey publicKey). maybe helps.

Share:
16,823
user3077162
Author by

user3077162

Updated on June 04, 2022

Comments

  • user3077162
    user3077162 almost 2 years

    i have this code :

    // 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);
    

    error:

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

    where is the problem?