2

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?

user3077162
  • 181
  • 2
  • 4
  • 12
  • Where did you get `keyBytes` from? – David Knipe Dec 14 '13 at 17:52
  • from this code: File f = new File("C:/Users/Joe/Desktop/joesaab.txt"); try{ FileInputStream fis = new FileInputStream(f); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int theByte = 0; while ((theByte = fis.read()) != -1) { baos.write(theByte); } fis.close(); byte[] keyBytes = baos.toByteArray(); baos.close(); System.out.println("pub and priv done.. Encoding started!"); – user3077162 Dec 14 '13 at 18:11
  • Does the file exist? Have you spelled its path and name correctly? What's the content of `keyBytes`? Does it look reasonable? Or is it just an empty string or something? Where are you catching exceptions from the `try` block, and is it catching anything interesting? – David Knipe Dec 14 '13 at 18:36
  • file and path are correct and exist, in my code i need to encrypt a text file using RSA.. the problem is in keyspecs i think.. – user3077162 Dec 14 '13 at 18:58
  • What is the file `joesaab.txt`? Is it the text you want to encrypt, or the key? (Java thinks you want to use it as the key.) – David Knipe Dec 15 '13 at 01:31
  • is a text file to be encrypted.. – user3077162 Dec 15 '13 at 15:19
  • That'll be the problem then. You're getting the contents of the file, piping it to a `byte[]`, then trying to read it as a key. You shouldn't get the error if you replace the filename with a file containing a key in X509 format (whatever that is). Or maybe you haven't stored your key on disc, I don't know. And I also don't know what you are supposed to do with the `joesaab.txt` file. – David Knipe Dec 15 '13 at 20:29

1 Answers1

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

mag_zbc
  • 6,801
  • 14
  • 40
  • 62