Decoding and encoding in Base64 in java - base64

I am getting a Base64 decoded String from out side network, i ll convert the string to byte and decode it. then it will change to ASCII format. I ll store this ASCII in string send to another server.
In this case when i again encode the ASCII i am not getting the same value what i have received from out side network. But it works fine in unix system, problem is only in windows.
// Base64 Encode
String orig = "mj5ok9qWt2v6fg3kElm8vZGeg9ZV0BqE1u2sYUQDEm8/heIdCH4ZRf7mcEcGkb8y3I24peAUBHdli8GP/MCZR/PG4NAAzd+AU3uEVM3RKTFnYwGslKQTfKgXzg+K+wkMY/0fexPkDrgVHi0vR7VXzcyx200iJYTYjJZLCwahZ7E2Cp7LW14YpCAYg8vFCp0XSZCe1luRNgq+q9xVQ88tDamAB5nGCxYZcx7X4D49HQR5vUEzIkJu2XenGQygXsGWICKv0UrVq72um0nRf0uJUa/jdMVXWtyeAsKTaVw8KTW5u745d+r7H3Fzcsl9UwL0kBfHv4WMQwz1dQ+MommXmA==";
byte [] decodedvalue = Base64.decodeBase64(orig.getBytes());
byte [] encodedvalue = Base64.encodeBase64(decodedvalue);
System.out.println("ORIGINAL VALUE : "+orig);
System.out.println("ENCODED VALUE : "+new String(encodedvalue));
String aa =new String(decodedvalue);
String temp = new String(Base64.encodeBase64(aa.getBytes()));
System.out.println(" String encoded value : " +temp);
ORIGINAL VALUE : mj5ok9qWt2v6fg3kElm8vZGeg9ZV0BqE1u2sYUQDEm8/heIdCH4ZRf7mcEcGkb8y3I24peAUBHdli8GP/MCZR/PG4NAAzd+AU3uEVM3RKTFnYwGslKQTfKgXzg+K+wkMY/0fexPkDrgVHi0vR7VXzcyx200iJYTYjJZLCwahZ7E2Cp7LW14YpCAYg8vFCp0XSZCe1luRNgq+q9xVQ88tDamAB5nGCxYZcx7X4D49HQR5vUEzIkJu2XenGQygXsGWICKv0UrVq72um0nRf0uJUa/jdMVXWtyeAsKTaVw8KTW5u745d+r7H3Fzcsl9UwL0kBfHv4WMQwz1dQ+MommXmA==
ENCODED VALUE : mj5ok9qWt2v6fg3kElm8vZGeg9ZV0BqE1u2sYUQDEm8/heIdCH4ZRf7mcEcGkb8y3I24peAUBHdli8GP/MCZR/PG4NAAzd+AU3uEVM3RKTFnYwGslKQTfKgXzg+K+wkMY/0fexPkDrgVHi0vR7VXzcyx200iJYTYjJZLCwahZ7E2Cp7LW14YpCAYg8vFCp0XSZCe1luRNgq+q9xVQ88tDamAB5nGCxYZcx7X4D49HQR5vUEzIkJu2XenGQygXsGWICKv0UrVq72um0nRf0uJUa/jdMVXWtyeAsKTaVw8KTW5u745d+r7H3Fzcsl9UwL0kBfHv4WMQwz1dQ+MommXmA==
String encoded value : mj5ok9qWt2v6fg3kElm8vZGeg9ZV0BqE1u2sYUQDEm8/heIdCH4ZRf7mcEcGkb8y3D+4peAUBHdli8E//MCZR/PG4NAAzd+AU3uEVM3RKTFnYwGslKQTfKgXzg+K+wkMY/0fexPkDrgVHi0vR7VXzcyx200iJYTYjJZLCwahZ7E2Cp7LW14YpCAYg8vFCj8XST+e1luRNgq+q9xVQ88tDamAB5nGCxYZcx7X4D49HQR5vUEzIkJu2XenGQygXsGWICKv0UrVq72um0nRf0uJUa/jdMVXWtyeAsKTaVw8KTW5u745d+r7H3Fzcsl9UwL0PxfHv4WMQwz1dQ+MommXmA==

Related

Need to convert String to same byteArray

We have used byte[].toStrng() method to convert an encoded string and save it in the DB. But we need to store the string in UTF-8 encoded format. Unfortunatey now we are unable to convert the string back to byte[] as the getBytes is returning different value than the original byte[] and decoding is also getting failed on the new byte array.
Is there any other way to convert the string to original byte array or decode to original string successfully?
public static void main (String[] args) {
String strToEncode = "test sample";
byte[] encbytes = Base64.getEncoder().encode(strToEncode.getBytes());
String str = encbytes.toString();
System.out.println (" Byte Array is " + encbytes);
System.out.println (" String is " + str);
byte[] newbytes = str.getBytes();
System.out.println (" New Byte Array is " + newbytes);
}
Output is as follows:
Byte Array is [B#15db9742
String is [B#15db9742
New Byte Array is [B#6d06d69c
Need encbytes and newbytes Array to be same. Any help is appreciated

How to get the right values when I convert hex to ascii character

I'm trying to convert a hexa file to text, using javascript node js.
function hex_to_ascii(str1){
var hex = str1.toString();
var str = '';
for (var n = 0; n < hex.length; n += 2) {
str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
}
return str;
}
I have a problem concening the extended ASCII charaters, so for example when I try to convert 93 I've get “ instead of ô and when I convert FF I've get ÿ instead of (nbsp) space.
I want to get the same extended charaters as this table: https://www.rapidtables.com/code/text/ascii-table.html
This problem is slightly more complex than it seems at first, since you need to specify an encoding when converting from extended ascii to a string. For example Windows-1252, ISO-8859-1 etc. Since you wish to use the linked table, I'm assuming you wish to use CP437 encoding.
To convert a buffer to string you need a module that will do this for you, converting from a buffer (in a given encoding) to string is not trivial unless the buffer is in a natively supported node.js encoding, e.g. UTF-8, ASCII (7-bit only!), Latin1 etc.
I would suggest using the iconv-lite package, this will convert many types of encoding. Once this is installed the code should look as follows (this takes each character from 0x00 to 0xFF and prints the encoded character):
const iconv = require('iconv-lite');
function hex_to_ascii(hexData, encoding) {
const buffer = Buffer.from(hexData, "hex");
return iconv.decode(buffer, encoding);
}
const testInputs = [...Array(256).keys()];
const encoding = "CP437";
console.log("Decimal\tHex\tCharacter")
for(let input of testInputs) {
console.log([input, input.toString(16), hex_to_ascii(input.toString(16), encoding)].join("\t"));
}

Node - Convert from base64 string to utf-8 byte code array

I'm currently trying to convert images from a base 64 string to a utf-8 byte code array. Below is the code I'm attempting to use with the base 64 string replaced for clarity. I'm getting what looks to be a utf-8 byte array, but have not been able to find a way to verify. Any help with a resource to help verify or if the code is incorrect?
const b64 = '...base64 string';
// convert to utf8 string
const utf8 = (Buffer.from(b64, 'base64')).toString('utf8');
// create a buffer of utf8 string
const buff = Buffer.from(utf8, 'utf8');
//
const arr = [...buff];

How to convert saved text file encoding to UTF8?

recently i saved a text file on my computer but when i open it again i saw some strings like:
"˜ÌÇí ÍÑÝã ÚÌíÈå¿"
now i want to know is it possible to reconvert it to the original text (UTF8)?
i try this codes but it doesn't works
string tempStr="˜ÌÇí ÍÑÝã ÚÌíÈå¿";
Encoding ANSI = Encoding.GetEncoding(1256);
byte[] ansiBytes = ANSI.GetBytes(tempStr);
byte[] utf8Bytes = Encoding.Convert(ANSI, Encoding.UTF8, ansiBytes);
String utf8String = Encoding.UTF8.GetString(utf8Bytes);
You can use something like:
string str = Encoding.GetEncoding(1256).GetString(Encoding.GetEncoding("iso-8859-1").GetBytes(tempStr))
The string wasn't really decoded... Its bytes where simply "enlarged" to char, with something like:
byte[] bytes = ...
char[] chars = new char[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
{
chars[i] = bytes[i];
}
string str = new string(chars);
Now... This transformation is the same that is done by the codepage ISO-8859-1. So I could simply have done the reverse, or I could have used that codepage to do it for me, I selected the second one.
Encoding.GetEncoding("iso-8859-1").GetBytes(tempStr)
this gave me the original byte[]
Then I've done some tests and it seems that the text in the beginning wasn't UTF8, it was in codepage 1256, that is an arabic codepage. So I
string str = Encoding.GetEncoding(1256).GetString(...);
The only thing, the ˜ doesn't seem to be part of the original string.
There is another possibility:
string str = Encoding.GetEncoding(1256).GetString(Encoding.GetEncoding(1252).GetBytes(tempStr));
The codepage 1252 is the codepage used in the USA and in a big part of Europe. If you have a Windows configured to English, there is a good chance it uses the 1252 as the default codepage. The result is slightly different than using the iso-8859-1

Signing a string with HMAC-MD5 with C#

I got the following HMAC key (in hexadecimal format):
52320e181a481f5e19507a75b3cae4d74d5cfbc328f7f2b738e9fb06b2e05b55b632c1c3d331dcf3baacae8d3000594f839d770f2080910b52b7b8beb3458c08
I need to sign this string:
1100002842850CHF91827364
The result should be this (in hexadecimal format):
2ad2f79111afd818c1dc0916d824b0a1
I have the following code:
string key = "52320e181a481f5e19507a75b3cae4d74d5cfbc328f7f2b738e9fb06b2e05b55b632c1c3d331dcf3baacae8d3000594f839d770f2080910b52b7b8beb3458c08";
string payload = "1100002842850CHF91827364";
byte[] keyInBytes = Encoding.UTF8.GetBytes(key);
byte[] payloadInBytes = Encoding.UTF8.GetBytes(payload);
var md5 = new HMACMD5(keyInBytes);
byte[] hash = md5.ComputeHash(payloadInBytes);
var result = BitConverter.ToString(hash).Replace("-", string.Empty);
However, I am not getting the result. What am I doing wrong?
when hashing with key HMAC md5
var data = Encoding.UTF8.GetBytes(plaintext);
// key
var key = Encoding.UTF8.GetBytes(transactionKey);
// Create HMAC-MD5 Algorithm;
var hmac = new HMACMD5(key);
// Compute hash.
var hashBytes = hmac.ComputeHash(data);
// Convert to HEX string.
return System.BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
Instead of doing this:
byte[] keyInBytes = Encoding.UTF8.GetBytes(key);
you need to convert key from a hex string to array of bytes. Here you can find example:
How do you convert Byte Array to Hexadecimal String, and vice versa?

Resources