简体   繁体   中英

Encrypt and Decrypt a String with RSA

I am a new bee to Java Security and Crypto. Below code does not return me the correct decryption.

Also please let me know any recommendation for using an algorithm to make a strong key.

Below code has two methods one is for encryption a String and the other is for decryption.

public class TestSecurityDiscussions {

        public static byte[] encryptData(KeyPair keys){

            String rawData = "Hi how are you>?";
            Cipher cipher = Cipher.getInstance("RSA");
            try {
                cipher.init(Cipher.ENCRYPT_MODE, keys.getPublic());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            byte[] encrypted = cipher.doFinal(rawData.getBytes());

            return encrypted;
        }


        public static String decryptData(byte[] encrypted,KeyPair keys) {
            Cipher cipher = Cipher.getInstance("RSA");
            try {
                cipher.init(Cipher.DECRYPT_MODE, keys.getPrivate());
            } catch (Exception e) {

                e.printStackTrace();
            }
            byte[] deycrypted = cipher.doFinal(encrypted);

            return deycrypted.toString();
        }


        public static void main(String[] args)   {
            KeyPair keys = KeyPairGenerator.getInstance("RSA").generateKeyPair();
            byte[] keydata = encryptData(keys);
            System.out.println("======>"+decryptData(keydata,keys));

        }

    }

I think your problem is this line:

return decrypted.toString();

Byte Strings will give a memory location via the toString() . You should do this:

return new String(decrypted);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM