开发者

What is wrong with this amateur KeyFactory and Encrypt code

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 fi开发者_高级运维gure 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();
        }
    }
}


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

You probably want new String(cipherData1).


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.


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")

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜