RSA算法:字节到字节数组的字符串

时间:2017-08-30 06:05:19

标签: java arrays encryption rsa

我正在实施以下RSA算法。

http://www.sanfoundry.com/java-program-implement-rsa-algorithm/ 程序从excel文件中获取一个字符串,执行RSA算法并将该字符串(字节串)存储到数据库中。

在解密时,我需要提取该字节串,将其转换为字节数组以执行解密。

 protected String encryptit(String teststring) {
            RSA rsa = new RSA();
            DataInputStream in = new DataInputStream(System.in);
            BigInteger e = rsa.getE();
            //String es=e.toString();
            BigInteger N = rsa.getN();
            BigInteger d=rsa.getD();

            try {
                byte[] encrypted = encrypt(teststring.getBytes(),e,N);
                String encryptString = encrypted.toString();
                return  encryptString;
                }
catch(Exception ex) {
                    System.out.println(ex);
                    return "0";
                }
            }

上述功能执行加密。存储的值之一是[B@37ad7b17

protected String decrypt(String val)
    {
        System.out.println("Value " +val);
        RSA rsa = new RSA();
        BigInteger e = rsa.getE();
        BigInteger N = rsa.getN();
        BigInteger d=rsa.getD();
        try {
            String[] bytesString = val.split(" ");
            byte[] bytes = new byte[bytesString.length];
            for(int i=0;i<bytes.length;i++)
            {
                System.out.println("for loop");
                bytes[i]=Byte.parseByte(bytesString[i]);
            }
            byte[] decrypted= decrypt(bytes,d,N);
            String decryptString = new String(decrypted);
            System.out.println(decryptString);
            return  decryptString;
        }catch(Exception ex) {
            System.out.println(ex);
            return "0";
        }
    }

上述功能执行解密。它给出了java.lang.NumberFormatException: For input string: "[B@37ad7b17"

如何将此字节串转换为字节数组。

1 个答案:

答案 0 :(得分:0)

要编码:

byte[] result = ...;

String str = Base64.encodeBase64String(result);

解码:

byte[] bytes = Base64.decodeBase64(str);

在JDK8中: import java.util.Base64;

String str = Base64.getEncoder().encode(result);
byte[] bytes = Base64.getDecoder().decode(str);