在通过URL后,Base64中编码的加密字符串不会被保留?

时间:2014-05-24 08:34:44

标签: java encryption base64 urlencode

“数据”StringBase64(网址安全版)编码,然后加密为byte array。此byte array变为String并发送到REST网络服务。当它到达Web服务端时,String的长度已更改。我不是专家,我做错了什么?

代码:

//CLIENT SIDE
import org.apache.commons.codec.binary.Base64;    

String data = "My message to be encrypted";        
PublicKey pubKey = readPublicKeyFromFile();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] encryptedData = cipher.doFinal(Base64.encodeBase64URLSafe(data.getBytes()));

System.out.println("length of original data string: " + data.length());
System.out.println("length of original data string turned into byte array: " + data.getBytes().length);
System.out.println("length of data string encrypted into byte array: " + encryptedData.length);

String encryptedDataToString = new String(encrypedData,"UTF-8");
System.out.println("length encrypted String into byte array, converted back to String for url: " + encryptedDataToString.length);

httpclient = new DefaultHttpClient();
builder = new URIBuilder();
builder.setScheme("http").setHost(xxx + "webresources/GetData/" + path)
                    .setParameter("data", encryptedDataToString);
            uri = builder.build();



//SERVER SIDE
import org.apache.commons.codec.binary.Base64;

@GET
@Path("path")
@Produces("text/plain")
public String getToken(@QueryParam("data") String data) {

System.out.println("length of data: " + data.length());
System.out.println("length of data to byte array wthout decoding: " + data.getBytes().length);
System.out.println("length of data to byte decoded: " + Base64.decodeBase64(data).length);


//CONSOLE

//CLIENT SIDE
length of original data string: 37
length of original data string turned into byte array: 37
length of data string encrypted into byte array: 256
length encrypted String into byte array, converted back to String for url: 256

//SERVER SIDE
INFO: length of data: 237
INFO: length of data to byte wthout decoding: 444
INFO: length of data to byte decoded: 4

数据String显示在网址客户端中: T%23%EF%BF%BD%0C%EF%BF%BD%EF%BF%BD7%EF%BF%BD%EF%BF%BDK%EF%BF%BDA%EF%BF%BD%10L% EF%BF%BD%EF%BF%BD%EF%BF%BD%14%EF%BF%BD%EF%BF%BD%5E%22%15B%1AE%01%EF%BF%BDgmE%0C% EF%BF%BD%EF%BF%BDN%EF%B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%EF%BF%BDO% EF%BF%BD%EF%BF%BD%11%CB%9C%EF%BF%BD%1DK%EF%BF%BDkL8%EF%BF%BD *%EF%BF%BD%1D%EF%BF %BDL%EF%BF%BD%EF%BF%BD%EF%BF%BD%02%EF%BF%BD

收到的数据String服务器端
T#7kAL ^“BegmEn =܀IMeM5&安培;} NAQ lTVXRi3Uepáb6εy9x|0ˏ}&安培;!A-ލŧ Tezs , ݔ % t Q } F n φR W U xo d-? / [g 2 K ^ M% ^向上{O~kkL8

(不确定这些是实际收到的字符,还是刚刚在控制台上打印错误?)

1 个答案:

答案 0 :(得分:2)

您必须先对其进行加密,然后使用base64对其进行编码并通过网络发送。 否则加密会创建(pseuro)随机数据,其中某些部分可能无法正确编码以通过网络传输,并且不可避免地会被破坏。

如果您想压缩数据,这同样适用。您在加密之前进行压缩,因为在加密之后,算法将难以压缩看似随机的数据。
通常,您发送到Web服务的内容应该是base64编码作为最后一步/更改。