Preface
I have written an introduction to the configuration center's encryption and decryption of configuration content: "Spring Cloud Build Microservice Architecture: Distributed Configuration Center (Encryption and Decryption)". In this article, there is a problem: when the encrypted content contains some special characters such as = and +, when using the command curl localhost:7001/encrypt -d mentioned in the previous article to encrypt and decrypt, special characters will be found to be lost.
For example, the following situation:
$ curl localhost:7001/encrypt -d eF34+5edo=a34c76c4ddab706fbcae0848639a8e0ed9d612b0035030542c98997e084a7427$ curl localhost:7001/decrypt -d a34c76c4ddab706fbcae0848639a8e0ed9d612b0035030542c98997e084a7427eF34 5edo
It can be seen that after encryption and decryption, some special characters are lost. Since I had a little trick here before, I took the time to write it out and share it. I hope it will be helpful to you if I encounter the same problem.
Causes and solutions to the problem
In fact, the reason for this issue is specifically explained in the official document. I can only blame myself for being too careless. The details are as follows:
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).
Therefore, when using curl, the correct posture should be:
$ 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=
So, how do we play when we write tools to encrypt and decrypt? Here is an example of OkHttp for reference:
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();}Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.