Encrypt CryptoJS without special characters - node.js

using nodejs
I am trying to generate an unique URL for user to conform email address. From that URL user will be able to verify the email account by decrypting the ciphertext and comparing ciphertext data with database . I am using CryptoJS to generate the url.
let url = 'http://localhost:4000/newUser/get/'+ciphertext ;
Problem is that in ciphertext, it contains forward slash " / " eg:
http://localhost:4000/newUser/get/U2FsdGVkX189ZNKKQrYgqU90DDwkl/W3hRTSGO1yvUMaDilPJmz9YYI3d1/E3i9C
Router is processing " / " on the URL, thus router is searching for the directory that is actually part of ciphertext. If there is any solution for not including " / " or special characters in ciphertext, please help. Thanks in advance.

You can easily replace the special characters with any of text like:
ciphertext.toString().replace('+','xMl3Jk').replace('/','Por21Ld').replace('=','Ml32');
Do not forget to replace these strings back with special characters
dataString.toString().replace('xMl3Jk', '+' ).replace('Por21Ld', '/').replace('Ml32', '=');
Hope this will help to solve your problem

However, .replace() will only replace first occurrence.
To be more precise, you can use something like this :
// Original Text
var ciphertext = 'asda+dasd+asdas/asdasd/sadasdasd/dadasd=adsasda=dasd=';
// Replaced Text
var dataString = ciphertext.replace(/\+/g,'p1L2u3S').replace(/\//g,'s1L2a3S4h').replace(/=/g,'e1Q2u3A4l');
console.log(dataString);
// Back to Original Text
ciphertext = dataString.replace(/p1L2u3S/g, '+' ).replace(/s1L2a3S4h/g, '/').replace(/e1Q2u3A4l/g, '=');
console.log(ciphertext);

IMHO, for #JaiKumarRajput's answer,
He encoded the string with,
ciphertext.toString().replace('+','xMl3Jk').replace('/','Por21Ld').replace('=','Ml32');
Now, I have no idea how xMl3Jk, Por21Ld, Ml32 works. So, i also don't know if it can mess my string somehow.
Plus, As I have to perform this on decoding as well. So, Why wont I use something like this (What already exists),
encodeURIComponent(ciphertext.toString('base64'))
I know it still introduces % char. But as its getting used in URL. In which its a escape char.
How does it matter more than doing something that can mess my code up ??
NOTE: I used it and had no issue, It doesn't mean I either had found any issue with the top one. That didn't feel neat. Its only my humble opinion, So if u don't like it? Ignore it.

There is no option for excluding / while crypto generate a encryped string.
I had face the same issue and then i found urlencode
const urlencode = require('urlencode');
let xx = {
chatRoomId: 37,
userId: 1,
doctorId: 2
}
xx = JSON.stringify(xx)
//encode
let x = (urlencode(xx, 'gbk')); // '%CB%D5%C7%A7'
// decode gbk
let y = urlencode.decode(x, 'gbk'); // original plain text
console.log(y)

// Original Text
let ciphertext = 'asda+dasd+asdas/asdasd/sadasdasd/dadasd=adsasda=dasd=';
let encodeText = encodeURIComponent(ciphertext);
console.log(encodeText)
let decodeText = decodeURIComponent(encodeText);
console.log(decodeText)
you can use like this.
first encode your ciphertext like above and concatenate that encodeText with ulr
let url = 'http://localhost:4000/newUser/get/'+encodeText ;
and then decode that encodeText from ulr

I have got the same problem, this works out for me:
const aesKey = CryptoJS.enc.Utf8.parse('aeskeyaeskeyaeskeyaeskeyaeskey32');
const aesIv = CryptoJS.enc.Utf8.parse('0123456789abcdef');
const aesOptions = {
iv: aesIv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
};
const plaintext = 'iamtheoriginal';
const ciphertext = CryptoJS.AES.encrypt(plaintext, aesKey, aesOptions).ciphertext.toString(); // 'c3a48990119bdfe40b6c32ec2aca8b93'
const encoded = {ciphertext: CryptoJS.enc.Hex.parse(ciphertext)};
const decodedText = CryptoJS.enc.Utf8.stringify(CryptoJS.AES.decrypt(encoded, aesKey, aesOptions)); // 'iamtheoriginal'
The ciphertext is 'c3a48990119bdfe40b6c32ec2aca8b93', has no special chars, and can be decrypted back to the original text, and it can encrypt all utf8 words like Chinese and even emoji.

Related

How to correctly pass the Cyrillic alphabet in a post request? Groovy

It is not possible to correctly transfer the Cyrillic alphabet to the post request. Letters are replaced with question marks.
Everything works well with numbers and the Latin alphabet.
name = 'иии.docx'
multipartRequestEntity.addPart('filename', new StringBody(name)) // return '???.docx'
name = 'fff.docx'
multipartRequestEntity.addPart('filename', new StringBody(name)) // return 'fff.docx'
How to correctly pass the Cyrillic alphabet in a post request?
Try by create the String with encoding, something like this:
name = new String('иии.docx', 'UTF-8')
Also, verify if the multipartRequestEntity has any method to set the encoding on the output.

How to remove string after and before specific chars

I have this string: https://2352353252142dsbxcs35#github.com/happy.git
I want to get result: https://github.com/happy.git (without random string after second / and after # but without #).
Now I have something like this:
var s = 'https://2352353252142dsbxcs35#github.com/happy.git';
var d = s.substring(s.indexOf('/')+2, s.indexOf('#')+1;
s = s.replace(d, "");
it works, but I know it's an ugly solution.
What is the most efficient and more universal solution?
Try this:
const indexOfAtSign: number = receivedMessage.indexOf('#')+1
const httpsString: string = 'https://'
const trimmedString: string = s.slice(indexOfAtSign)
const requiredURL: string = httpsString.concat(trimmedString)
// Print this value of requiredURL wherever you want.
So here what my code does is, it gets position of # and removes everything before it along with the sign itself. Then using the slice() function, we are left with the remaining part which I named as trimmedString. Now I have pre-defined the `https string, anf we just need to merge them now. Done :-)
I had tried this out in my telegram bot and here's how it works:

I need to read a string while ignoring any spaces or capital letters

I'm trying to read any message sent on a discord server and send a reply if a certain string is within the message ignoring all spaces and capitals. I'm very new to javascript and this is the first code I'm making just for fun.
This is the current main part of the code.
if(msg.content.toLowerCase().includes('string'))
{
msg.channel.send(emoji("480351478930866179"));
}
You can remove whitespace with replace() and shift the string to lowercase using toLowerCase() to achieve the desired result.
const original = 'Hello there.';
const str = original.replace(/\s/g, '').toLowerCase();
if (str.includes('hello')) console.log('Hi.');
You could use the string.replace method or you could use split then join. To ignore case just use toLowerCase();
Thank's, that solved my problem.
const original = 'Hello there.';
const str = original.replace(/\s/g, '').toLowerCase();
if (str.includes('hello')) console.log('Hi.');

Read parameter from URL - plus character converted to space [duplicate]

Say I have a URL
http://example.com/query?q=
and I have a query entered by the user such as:
random word £500 bank $
I want the result to be a properly encoded URL:
http://example.com/query?q=random%20word%20%A3500%20bank%20%24
What's the best way to achieve this? I tried URLEncoder and creating URI/URL objects but none of them come out quite right.
URLEncoder is the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character & nor the parameter name-value separator character =.
String q = "random word £500 bank $";
String url = "https://example.com?q=" + URLEncoder.encode(q, StandardCharsets.UTF_8);
When you're still not on Java 10 or newer, then use StandardCharsets.UTF_8.toString() as charset argument, or when you're still not on Java 7 or newer, then use "UTF-8".
Note that spaces in query parameters are represented by +, not %20, which is legitimately valid. The %20 is usually to be used to represent spaces in URI itself (the part before the URI-query string separator character ?), not in query string (the part after ?).
Also note that there are three encode() methods. One without Charset as second argument and another with String as second argument which throws a checked exception. The one without Charset argument is deprecated. Never use it and always specify the Charset argument. The javadoc even explicitly recommends to use the UTF-8 encoding, as mandated by RFC3986 and W3C.
All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.
See also:
What every web developer must know about URL encoding
I would not use URLEncoder. Besides being incorrectly named (URLEncoder has nothing to do with URLs), inefficient (it uses a StringBuffer instead of Builder and does a couple of other things that are slow) Its also way too easy to screw it up.
Instead I would use URIBuilder or Spring's org.springframework.web.util.UriUtils.encodeQuery or Commons Apache HttpClient.
The reason being you have to escape the query parameters name (ie BalusC's answer q) differently than the parameter value.
The only downside to the above (that I found out painfully) is that URL's are not a true subset of URI's.
Sample code:
import org.apache.http.client.utils.URIBuilder;
URIBuilder ub = new URIBuilder("http://example.com/query");
ub.addParameter("q", "random word £500 bank \$");
String url = ub.toString();
// Result: http://example.com/query?q=random+word+%C2%A3500+bank+%24
You need to first create a URI like:
String urlStr = "http://www.example.com/CEREC® Materials & Accessories/IPS Empress® CAD.pdf"
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
Then convert that URI to an ASCII string:
urlStr = uri.toASCIIString();
Now your URL string is completely encoded. First we did simple URL encoding and then we converted it to an ASCII string to make sure no character outside US-ASCII remained in the string. This is exactly how browsers do it.
Guava 15 has now added a set of straightforward URL escapers.
The code
URL url = new URL("http://example.com/query?q=random word £500 bank $");
URI uri = new URI(url.getProtocol(), url.getUserInfo(), IDN.toASCII(url.getHost()), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
String correctEncodedURL = uri.toASCIIString();
System.out.println(correctEncodedURL);
Prints
http://example.com/query?q=random%20word%20%C2%A3500%20bank%20$
What is happening here?
1. Split URL into structural parts. Use java.net.URL for it.
2. Encode each structural part properly!
3. Use IDN.toASCII(putDomainNameHere) to Punycode encode the hostname!
4. Use java.net.URI.toASCIIString() to percent-encode, NFC encoded Unicode - (better would be NFKC!). For more information, see: How to encode properly this URL
In some cases it is advisable to check if the URL is already encoded. Also replace '+' encoded spaces with '%20' encoded spaces.
Here are some examples that will also work properly
{
"in" : "http://نامه‌ای.com/",
"out" : "http://xn--mgba3gch31f.com/"
},{
"in" : "http://www.example.com/‥/foo",
"out" : "http://www.example.com/%E2%80%A5/foo"
},{
"in" : "http://search.barnesandnoble.com/booksearch/first book.pdf",
"out" : "http://search.barnesandnoble.com/booksearch/first%20book.pdf"
}, {
"in" : "http://example.com/query?q=random word £500 bank $",
"out" : "http://example.com/query?q=random%20word%20%C2%A3500%20bank%20$"
}
The solution passes around 100 of the test cases provided by Web Platform Tests.
Using Spring's UriComponentsBuilder:
UriComponentsBuilder
.fromUriString(url)
.build()
.encode()
.toUri()
The Apache HttpComponents library provides a neat option for building and encoding query parameters.
With HttpComponents 4.x use:
URLEncodedUtils
For HttpClient 3.x use:
EncodingUtil
Here's a method you can use in your code to convert a URL string and map of parameters to a valid encoded URL string containing the query parameters.
String addQueryStringToUrlString(String url, final Map<Object, Object> parameters) throws UnsupportedEncodingException {
if (parameters == null) {
return url;
}
for (Map.Entry<Object, Object> parameter : parameters.entrySet()) {
final String encodedKey = URLEncoder.encode(parameter.getKey().toString(), "UTF-8");
final String encodedValue = URLEncoder.encode(parameter.getValue().toString(), "UTF-8");
if (!url.contains("?")) {
url += "?" + encodedKey + "=" + encodedValue;
} else {
url += "&" + encodedKey + "=" + encodedValue;
}
}
return url;
}
In Android, I would use this code:
Uri myUI = Uri.parse("http://example.com/query").buildUpon().appendQueryParameter("q", "random word A3500 bank 24").build();
Where Uri is a android.net.Uri
In my case I just needed to pass the whole URL and encode only the value of each parameters.
I didn't find common code to do that, so (!!) so I created this small method to do the job:
public static String encodeUrl(String url) throws Exception {
if (url == null || !url.contains("?")) {
return url;
}
List<String> list = new ArrayList<>();
String rootUrl = url.split("\\?")[0] + "?";
String paramsUrl = url.replace(rootUrl, "");
List<String> paramsUrlList = Arrays.asList(paramsUrl.split("&"));
for (String param : paramsUrlList) {
if (param.contains("=")) {
String key = param.split("=")[0];
String value = param.replace(key + "=", "");
list.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}
else {
list.add(param);
}
}
return rootUrl + StringUtils.join(list, "&");
}
public static String decodeUrl(String url) throws Exception {
return URLDecoder.decode(url, "UTF-8");
}
It uses Apache Commons' org.apache.commons.lang3.StringUtils.
Use this:
URLEncoder.encode(query, StandardCharsets.UTF_8.displayName());
or this:
URLEncoder.encode(query, "UTF-8");
You can use the following code.
String encodedUrl1 = UriUtils.encodeQuery(query, "UTF-8"); // No change
String encodedUrl2 = URLEncoder.encode(query, "UTF-8"); // Changed
String encodedUrl3 = URLEncoder.encode(query, StandardCharsets.UTF_8.displayName()); // Changed
System.out.println("url1 " + encodedUrl1 + "\n" + "url2=" + encodedUrl2 + "\n" + "url3=" + encodedUrl3);

How to implement string manipulation in efficienct way?

I have a string ="/show/search/All.aspx?Att=A1". How to get the last value after the 'Att=' in efficient way ?
You could do a split on the '=' character.
Example (in C#):
string line = "/show/search/All.aspx?Att=A1";
string[] parts = line.Split('=');
//parts[1] contains A1;
Hope this helps
If you're only dealing with this one URL then both of the other answers would work fine. I would consider using the HttpUtility.ParseQueryString method and just pull out the item you want by key.
Whatever an
efficient way
is...
Try this:
var str = "/show/search/All.aspx?Att=A1";
var searchString = "Att=";
var answer = str.Substring(str.IndexOf(searchString) + searchString.Length);

Resources