I am using the below code to encrypt and decrypt the data. Now I want to encrypt the data from Node JS and want to decrypt the data from Go lang. But I am not able to achieve it using GO lang.
var B64XorCipher = {
encode: function(key, data) {
return new Buffer(xorStrings(key, data),'utf8').toString('base64');
},
decode: function(key, data) {
data = new Buffer(data,'base64').toString('utf8');
return xorStrings(key, data);
}
};
function xorStrings(key,input){
var output='';
for(var i=0;i<input.length;i++){
var c = input.charCodeAt(i);
var k = key.charCodeAt(i%key.length);
output += String.fromCharCode(c ^ k);
}
return output;
}
From go I am trying to decode like below I am not able to achieve it.
bytes, err := base64.StdEncoding.DecodeString(actualInput)
encryptedText := string(bytes)
fmt.Println(EncryptDecrypt(encryptedText, "XXXXXX"))
func EncryptDecrypt(input, key string) (output string) {
for i := range input {
output += string(input[i] ^ key[i%len(key)])
}
return output
}
Can someone help me to resolve it.
UTF-16 versus UTF-8?
You should use
DecodeRuneInString
instead of justslice
string to byte.Solution in playground: https://play.golang.org/p/qi_6S1J_dZU
compared to your js result
The test result is the same.
Here is why.
In go, when you range a string, you iterate bytes, but javascript
charCodeAt
is for character,not byte. In utf-8, the character is maybe 2 or 3 bytes long. So that is why you got different output.Test in playground https://play.golang.org/p/XawI9aR_HDh
The output is