开发者

Input Sanitizing to not break JSON syntax

开发者 https://www.devze.com 2023-03-17 06:03 出处:网络
So, in a nutshell I\'m trying to create a regex that I can use in a java program that is about to submit a JSON object to my php server.

So, in a nutshell I'm trying to create a regex that I can use in a java program that is about to submit a JSON object to my php server.

myString.replaceAll(myRegexString,"");

My question is that I am absolutely no good with regex and to add onto that I need to escape the characters properly as its stored in a string, and then also escape the characters properly inside the regex. good lordy.

What I came up with was this:

String myRegexString = "[\"',{}[]:;]"

The first backslash was to escape outer quotes to get a " in there. And then it struck me that {} and [] are also regex commands. Would I escape those as well? Like:

String myRegexString = "[\"',\{\}\[\]:;]"

Thanks in advance. In case it wasnt clear from examp开发者_如何学Cles above the only characters I really care about at this moment in time is: " { } [ ] , and also ; : ' for general sqlinj protection.

UPDATE:

This is the final regex: [\\Q\"',{}[\]:;\\E] for anyone else curious. Thanks Amit!


Why don't you use an actual JSON encoding API/framework? What you're doing is not sanitizing. What you're doing is corrupting the data. If my name is O'Reilly, I want it to be spelled O'Reilly, not OReilly. If I send a message containing [ or {, I want these to be in the messages. Use a framework or API that escapes those characters when needed rather than removing them blindly.

Googling for JSON Java will lead you to many APIs and frameworks.


Try something like

String myRegexString = "[\\Q\"',{}[]:;\\E]";

now the characters between \Q and \E are now treated as normal characters.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号