简体   繁体   English

使用RSA加密和解密字符串

[英]Encrypt and Decrypt a String with RSA

I am a new bee to Java Security and Crypto. 我是Java Security和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() . 字节字符串将通过toString()给出存储位置。 You should do this: 你应该做这个:

return new String(decrypted);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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