0

I've written such code which should take 3 arguments, one is file with public key, second file to encrypt and third is file to save encrypted text. However, it does not work as it should, I added println just to see where it fails:

    public class cipher {
       public static void main (String[] args) throws GeneralSecurityException{
          try {
             FileInputStream keyfis = new FileInputStream(args[0]);
             byte[] encKey = new byte[keyfis.available()];  
             System.out.println(encKey);
             keyfis.read(encKey);
             System.out.println(encKey);
             System.out.println("1");
             X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encKey);
             System.out.println(keySpec);
              KeyFactory kf = KeyFactory.getInstance("RSA");
             System.out.println("2");
             PublicKey pubKey = kf.generatePublic(keySpec);
              System.out.println("3r");
             Cipher cipher = Cipher.getInstance("RSA");
             cipher.init(Cipher.ENCRYPT_MODE,pubKey);   
              System.out.println("4");
               }


         catch(Exception e)
           {}


        }   


}

After invokation of program I have such output :

[B@938b4a
[B@938b4a
1
java.security.spec.X509EncodedKeySpec@182d86
2

Thanks for help!

deer deer
  • 49
  • 5
  • Note that reading from a stream like that is not correct. You should use [`readAllBytes`](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllBytes(java.nio.file.Path)) if you require a short cut. – Maarten Bodewes Oct 15 '14 at 22:55

2 Answers2

0

The first 3 print statements that output something ending with @938b4a only show that the object exists, and that the object does not implement toString(). Byte arrays should be printed out using hexadecimals.

After that you get to generatePublic which fails. This means that your public key - which should be a DER encoded SubjectPublicKeyInfo structure - could not be parsed.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
0

Without knowing what error you're getting, it looks like this might be the answer you're looking for.

It appears as though you're trying to encode the private key with the X509EncodedKeySpec, when you should be using PKCS8EncodedKeySpec.

The public key will then be encoded using the X509EncodedKeySpec.

Community
  • 1
  • 1
sfedak
  • 676
  • 6
  • 20
  • I'm pretty sure that the user requires the public key for encryption. Of course the user could mistake the private key for the public key, but the above certainly does not seem to be the answer. – Maarten Bodewes Oct 15 '14 at 22:57
  • I am using public key, not private. That is why X509EncodedKeySpec is not the problem in this case. – deer deer Oct 16 '14 at 11:20