-1

I dont understand what i do wrong, This code is three steps

  • Create public and private keys (save to disk)
  • encrypt the text "hello hello"
  • decrypt the text "hello hello"

but the output from this code is

[B@7455d93d (after encrypt)
[B@3bc0f2e5 (after decrypt)

im doing some really amateur error but cannot figure it out

.

public class KeyPairsGenerator {

    public static void main(String args[]){
        KeyPairsGenerator testClass = new KeyPairsGenerator();
        testClass.GenerateKeyPair();
        testClass.testEncryptDecrypt();
    }

    public void testEncryptDecrypt(){

        ObjectInputStream oinPublic = null;
        ObjectInputStream oinPrivate = null;
        try {

            //****************
            //ENCRYPT
            oinPublic = new ObjectInputStream
            (new BufferedInputStream(new FileInputStream("public.key")));
            BigInteger m = (BigInteger) oinPublic.readObject();
            BigInteger e = (BigInteger) oinPublic.readObject();
            RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
            KeyFactory fact = KeyFactory.getInstance("RSA");
            PublicKey pubKey = fact.generatePublic(keySpec);

            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            byte[] cipherData = cipher.doFinal("hello hello".getBytes());

            System.out.println(cipherData.toString());

            //****************
            //DECRYPT
            oinPrivate = new ObjectInputStream
            (new BufferedInputStream(new FileInputStream("private.key")));
            BigInteger m1 = (BigInteger) oinPrivate.readObject();
            BigInteger e1 = (BigInteger) oinPrivate.readObject();
            RSAPrivateKeySpec keySpecPrivate = new RSAPrivateKeySpec(m1, e1);
            KeyFactory fact1 = KeyFactory.getInstance("RSA");
            PrivateKey privKey = fact1.generatePrivate(keySpecPrivate);

            Cipher cipher1 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher1.init(Cipher.DECRYPT_MODE, privKey);
            byte[] cipherData1 = cipher1.doFinal(cipherData);

            System.out.println(cipherData1.toString()); 

        } catch (Exception e) {
            throw new RuntimeException("Spurious serialization error", e);
        } finally {
            try {
                oinPrivate.close();
                oinPublic.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


    public void GenerateKeyPair()
    {       
        try{
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(2048);
            KeyPair kp = kpg.genKeyPair();

            KeyFactory fact = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec pub = fact.getKeySpec(
                    kp.getPublic(),RSAPublicKeySpec.class);
            RSAPrivateKeySpec priv = fact.getKeySpec
            (kp.getPrivate(),RSAPrivateKeySpec.class);

            saveToFile("public.key", pub.getModulus(),pub.getPublicExponent());
        saveToFile("private.key", priv.getModulus(),priv.getPrivateExponent());
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
    }

    public void saveToFile(String fileName,BigInteger mod, 
            BigInteger exp) throws Exception {

        ObjectOutputStream oout = new ObjectOutputStream
        (new BufferedOutputStream(new FileOutputStream(fileName)));
        try {
            oout.writeObject(mod);
            oout.writeObject(exp);
        } catch (Exception e) {
            throw new Exception("error", e);
        } finally {
            oout.close();
        }
    }
}
2
  • 2
    "hello hello".getBytes() You should specify a character encoding here otherwise the two parties might use something incompatible.
    – Thilo
    Sep 14, 2011 at 10:50
  • good comment yea that would have made problems
    – Erik
    Sep 14, 2011 at 11:22

3 Answers 3

2

cipherData1.toString() doesn't do what you think it does.

You probably want new String(cipherData1).

7
  • except that this is binary data. Maybe something like Base64 first.
    – Thilo
    Sep 14, 2011 at 10:44
  • @Oli that's it.. thanks so much. it's working with the new String(cipherData1). Will try to send some passwords over the Internet now
    – Erik
    Sep 14, 2011 at 10:45
  • @Thilo: The decrypted data ought to be the same as the original. Sep 14, 2011 at 10:46
  • Okay... I was just looking at the variable name, which sounded like it was ciphertext...
    – Thilo
    Sep 14, 2011 at 10:47
  • Binary data gets treated correctly by the new String() command. Sep 14, 2011 at 10:50
1

Use java.util.Arrays.toString(byte[]) to display the byte array. byte[].toString() returns the type of the array ([B) followed by its hashCode.

You could also use Base64 to encode your byte arrays as ASCII strings. Apache commons-codec has a free implementation.

0

Your cipherData and cipherData1 are coming in as a byte array, you need to turn these into a String, the .toString() that is available to the array class is the generic .toString() and it doesn't really return to you the byte Array in a String format, to do this you need to do System.out.println(new String(cipherData)) and System.out.println(new String(chiperData1)) which ends up being better than allocating it to a String in memory prior printing it.

EDIT: On an added note, if you're thinking about doing a cross-platform communication with this, also state the encoding, ie:
- new String(cipherData, "UTF-8")
- new String(cipherData, "ISO-8859-1")

5
  • the private key will be used by any android device world width maybe. yea this is important
    – Erik
    Sep 14, 2011 at 11:23
  • 1
    well if you are going to be doing a Server-client communication then I'd recommend dual encryption, an RSA encryption with the public key on the client side (android devices), which you then use to send the encryption key (for the second encryption method) that is generated by the device, this means you can have the private key pretty much safe on the server side and only the public key is available. For a secondary encryption algorythm I'd recommend TEA or something similar. I did something like this for a project that runs smoothly on old phones, so it should work rather well on Android. Sep 14, 2011 at 11:33
  • Do you mean that both server and client should create key there own key pairs private/public keys. I dont understand fully. Now my server have the RSA private key and my client use the public key to send the login pass/user name to server. How can TEA make this safer?
    – Erik
    Sep 14, 2011 at 16:02
  • if you keep RSA for a "login" connection, and in this primary connection you send the (TEA) key that the client generates each time the app is run, you end up permitting both client and server to decrypt TEA according to a session key. TEA isn't safer than RSA, however if you use it in conjunction with RSA in the method I specified above it ends up making a more safe data transaction between client and server since the RSA private key is only known to the server, and the TEA key gets generated on each session. Sep 14, 2011 at 17:05
  • thanks, i have limited base knowledge to comprehend this. I will start with the RSA and move from there.
    – Erik
    Sep 14, 2011 at 17:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.