所以必須把 byte array 轉換成字串,傳送出去之後還要能再轉回原本的 byte array 來解密。
根據 Encrypting and decrypting large data using Java and RSA 的建議
要把 byte array 轉成 hexadecimal 的字串,在網路上傳送才不容易有問題。
參考資料:
1、Converting A String To Hexadecimal In Java
2、How to convert Hex String to Bytes and viceversa in Java?
程式碼參考來源為上述的兩個參考資料的連結,程式碼內容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public String byte2Hex( byte [] b) { String result = "" ; for ( int i= 0 ; i<b.length ; i++) result += Integer.toString( ( b[i] & 0xff ) + 0x100 , 16 ).substring( 1 ); return result; } public String string2Hex(String plainText, String charset) throws UnsupportedEncodingException { return String.format( "%040x" , new BigInteger( 1 , plainText.getBytes(charset))); } public byte [] hex2Byte(String hexString) { byte [] bytes = new byte [hexString.length() / 2 ]; for ( int i= 0 ; i<bytes.length ; i++) bytes[i] = ( byte ) Integer.parseInt(hexString.substring( 2 * i, 2 * i + 2 ), 16 ); return bytes; } public String hex2String(String hexString) { StringBuilder str = new StringBuilder(); for ( int i= 0 ; i<hexString.length() ; i+= 2 ) str.append(( char ) Integer.parseInt(hexString.substring(i, i + 2 ), 16 )); return str.toString(); } |
這邊總共有四個方法,分別是將 string/hex 互轉以及 byte array/hex 互轉。
沒有留言:
張貼留言