前言
之前寫過一篇關(guān)于配置中心對配置內(nèi)容加密解密的介紹:《spring cloud構(gòu)建微服務(wù)架構(gòu):分布式配置中心(加密解密) 》。在這篇文章中,存在一個(gè)問題:當(dāng)被加密內(nèi)容包含一些諸如=、+這些特殊字符的時(shí)候,使用上篇文章中提到的類似這樣的命令curl localhost:7001/encrypt -d
去加密和解密的時(shí)候,會發(fā)現(xiàn)特殊字符丟失的情況。
比如下面這樣的情況:
1
2
3
4
|
$ curl localhost: 7001 /encrypt -d ef34+5edo= a34c76c4ddab706fbcae0848639a8e0ed9d612b0035030542c98997e084a7427 $ curl localhost: 7001 /decrypt -d a34c76c4ddab706fbcae0848639a8e0ed9d612b0035030542c98997e084a7427 ef34 5edo |
可以看到,經(jīng)過加密解密之后,又一些特殊字符丟失了。由于之前在這里也小坑了一下,所以抽空寫出來分享一下,給遇到同樣問題的朋友,希望對您有幫助。
問題原因與處理方法
其實(shí)關(guān)于這個(gè)問題的原因在官方文檔中是有具體說明的,只能怪自己太過粗心了,具體如下:
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的時(shí)候,正確的姿勢應(yīng)該是:
1
2
3
4
5
|
$ 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= |
那么,如果我們自己寫工具來加密解密的時(shí)候怎么玩呢?下面舉個(gè)okhttp的例子,以供參考:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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(); } |
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對服務(wù)器之家的支持。
原文鏈接:http://blog.didispace.com/spring-cloud-config-sp-char-encrypt/