Spring Cloud Config對特殊字符加密的處理
之前寫過一篇關(guān)于配置中心對配置內(nèi)容加密解密的介紹:《Spring Cloud構(gòu)建微服務(wù)架構(gòu):分布式配置中心(加密解密)》。在這篇文章中,存在一個問題:當(dāng)被加密內(nèi)容包含一些諸如=、+這些特殊字符的時候,使用上篇文章中提到的類似這樣的命令curl localhost:7001/encrypt -d去加密和解密的時候,會發(fā)現(xiàn)特殊字符丟失的情況。
比如下面這樣的情況:
- $ curl localhost:7001/encrypt -d eF34+5edo=
- a34c76c4ddab706fbcae0848639a8e0ed9d612b0035030542c98997e084a7427
- $ curl localhost:7001/decrypt -d a34c76c4ddab706fbcae0848639a8e0ed9d612b0035030542c98997e084a7427
- eF34 5edo
可以看到,經(jīng)過加密解密之后,又一些特殊字符丟失了。由于之前在這里也小坑了一下,所以抽空寫出來分享一下,給遇到同樣問題的朋友,希望對您有幫助。
問題原因與處理方法
其實關(guān)于這個問題的原因在官方文檔中是有具體說明的,只能怪自己太過粗心了,具體如下:
If you are testing like this with curl, then use --data-urlencode (instead of -d) or set an explicit Content-Type: text/plain to make sure curl encodes the data correctly when there are special characters (‘+’ is particularly tricky).
所以,在使用curl的時候,正確的姿勢應(yīng)該是:
- $ curl localhost:7001/encrypt -H 'Content-Type:text/plain' --data-urlencode "eF34+5edo="
- 335e618a02a0ff3dc1377321885f484fb2c19a499423ee7776755b875997b033
- $ curl localhost:7001/decrypt -H 'Content-Type:text/plain' --data-urlencode "335e618a02a0ff3dc1377321885f484fb2c19a499423ee7776755b875997b033"
- eF34+5edo=
那么,如果我們自己寫工具來加密解密的時候怎么玩呢?下面舉個OkHttp的例子,以供參考:
- private String encrypt(String value) {
- String url = "http://localhost:7001/encrypt";
- Request request = new Request.Builder()
- .url(url)
- .post(RequestBody.create(MediaType.parse("text/plain"), value.getBytes()))
- .build();
- Call call = okHttpClient.newCall(request);
- Response response = call.execute();
- ResponseBody responseBody = response.body();
- return responseBody.string();
- }
- private String decrypt(String value) {
- String url = "http://localhost:7001/decrypt";
- Request request = new Request.Builder()
- .url(url)
- .post(RequestBody.create(MediaType.parse("text/plain"), value.getBytes()))
- .build();
- Call call = okHttpClient.newCall(request);
- Response response = call.execute();
- ResponseBody responseBody = response.body();
- return responseBody.string();
- }
【本文為51CTO專欄作者“翟永超”的原創(chuàng)稿件,轉(zhuǎn)載請通過51CTO聯(lián)系作者獲取授權(quán)】