2017-08-30 45 views
-1

我正在实现以下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"; 
       } 
      } 

上述功能执行加密。一个被存储的值是[[email protected]

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: "[[email protected]"

我该怎么做才能将这个字节的字符串转换为一个字节数组。

+0

使用try方法的getBytes()参考的http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#getBytes%28%29 – Akshay

+1

可能的复制[如何将Java字符串转换为字节\ [\]?](https://stackoverflow.com/questions/18571223/how-to-convert-java-string-into-byte) – Flown

+0

@Akshay使用getBytes()给出一个垃圾值 – user3508140

回答

0

为了编码:

byte[] result = ...; 

String str = Base64.encodeBase64String(result); 

为了解码:

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

在JDK8: 进口java.util.Base64;

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