I want using CRC16, but first, i want to convert string to hex. because integer must be 16 bytes. i still confused to encrypt using CRC16. this is my code.
public static void main(String[] args) {
String input = "skn";
byte[] valuesDefault = input.getBytes();
System.out.println("input:" + input);
System.out.println(Arrays.toString(valuesDefault));
}
Try this below
DatatypeConverter.printHexBinary(input.getBytes())
Related
I have generated Base64 encoded value using below Scala code:
println(Base64.getEncoder.encodeToString("E5E9FA1BA31ECD1AE84F75CAAA474F3A".getBytes(StandardCharsets.UTF_8)))
YxRfXk827kPgkmMUX15PNg==
Now I am trying to convert "YxRfXk827kPgkmMUX15PNg==" to Hex. I tried with below Java code but no luck:
public static void main(String[] args) throws DecoderException {
String guid = "RTVFOUZBMUJBMzFFQ0QxQUU4NEY3NUNBQUE0NzRGM0E=";
byte[] hexString = Hex.decodeHex(guid);
System.out.println(hexString);
Exception in thread "main" org.apache.commons.codec.DecoderException: Illegal hexadecimal character R at index 0
When I explored I found below working Java code:
String guid = "YxRfXk827kPgkmMUX15PNg==";
byte[] decoded = Base64.decodeBase64(guid);
String hexString = Hex.encodeHexString(decoded);
System.out.println(hexString);
4535453946413142413331454344314145383446373543414141343734463341
But here Base64 values is getting decoded and then converted to Hex. I am trying to figure out if there is a way we can directly convert Base64 to Hex? Please excuse as it looks like a duplicate question and thanks in advance.
Since it is a String, it already has a way to get the ByteArray.
Don't decode the Base64, simply request the bytes from the String:
public static void main(String[] args) {
String guid = "YxRfXk827kPgkmMUX15PNg==";
String hexString = Hex.encodeHexString(guid.getBytes());
System.out.println(hexString);
}
This basically means you only have to convert your string to a Byte[].
You can see that the business logic code is very simple and that the original text and the hex encoded are the same by trying to decode them in a test:
// actual business logic
public String hexEncoder(String content) {
return Hex.encodeHexString(content.getBytes());
}
// input and assertion
#Test
public void hexEncoder() throws DecoderException {
String guid = "YxRfXk827kPgkmMUX15PNg==";
String hexString = hexEncoder(guid);
String hexDecoded = new String(Hex.decodeHex(hexString));
// no need to decode Base64 but might be useful for `printLn` or debugging
String s = new String(Base64.decodeBase64(guid));
String s1 = new String(Base64.decodeBase64(hexDecoded));
assertEquals(s, s1);
}
I want to convert a string value to the same byte array in C# and Java with following codes:
C#:
string key="EA1302AFBCCF791CB0065BFAD948B092";
byte[] keyByte = Encoding.UTF8.GetBytes(plainKey);
Java:
String key="EA1302AFBCCF791CB0065BFAD948B092";
byte[] keyByte = (key).getBytes("UTF-8");
But the length of the generated array is 32 in C# and 343 in Java. I have to create a byte array in C# same as Java, so please don't suggest changes for my Java code.
I tried:
public static void main(String args[]) throws UnsupportedEncodingException {
String key="EA1302AFBCCF791CB0065BFAD948B092";
byte[] keyByte = key.getBytes("UTF-8");
System.out.println("Length: " + keyByte.length);
}
output is:
Length: 32
I've written this simple Java snippet to SHA-256 a string:
public static void main(String[] args) throws NoSuchAlgorithmException {
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
String input = "00010966776006953D5567439E5E39F86A0D273BEE";
byte[] output = sha256.digest(input.getBytes());
System.out.println(new String(output));
}
Running SHA-256 using this tool gives the output 3CC2243D50E87857A233965AA6B68B37563BFCC52B3C499FBB259B9AA87FFF40, but when I run it myself I get <�$=P�xW�3�Z���7V;��+<I��%����#. It looks like something is going wrong with the byte conversion, but I'm not exactly sure what.
You are correct that something was wrong when you tried to convert byte[] to string. Here is a code that works :)
public static void main(String[] args) throws NoSuchAlgorithmException {
final String input = "Nishit";
final MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(input.getBytes());
final byte[] data = md.digest();
StringBuilder sb = new StringBuilder(data.length * 2);
for (byte b : data) {
sb.append(String.format("%02x", b));
}
System.out.println(sb.toString());
}
What it is really happenning is that the SHA256 returns a 256-bit hash value. So what you're printing is those bytes as if they were characters and their respective character values is all that gibberish.
What the online tool is returning you is the representation of that value in hexadecimal format.
Notice that you're getting, (with the tool) 64 bytes IE 64 characters when 256-bit is equal to 32 bytes (32 charaters you may think).
That is because to represent a whole byte in hexadecimal format 2 characters are needed. 4 most significative bits take one character and the other less significative bits take another one.
scenario:
a std Transaction file (csv) will be there (file1.csv)
other file( file2.csv) assume its a output from other module,
TASK: file1 & file2 should match (headers & data) both should match,
You can check for equality of files using Hashes.
If the hash values of two files match, then the files are exactly same.
Most common hashing techniques are MD5 and SHA1. It would be suitable for most common purposes. (Unless you are using them for cryptographic or security purposes!)
Your JRE comes with the java.security.MessageDigest class that provides hashing.
Here is a sample code that you can use:
public class HashCheck {
public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
byte[] file1Contents = Files.readAllBytes(Paths.get("C:/path/to/file1.csv"));
byte[] file2Contents = Files.readAllBytes(Paths.get("C:/path/to/file2.csv"));
String hashtext1 = computeHash(file1Contents);
String hashtext2 = computeHash(file2Contents);
System.out.println(hashtext1);
System.out.println(hashtext2);
System.out.println(hashtext1.equals(hashtext2));
}
public static String computeHash(String input) throws NoSuchAlgorithmException {
return computeHash(input.getBytes());
}
public static String computeHash(byte[] input) throws NoSuchAlgorithmException {
MessageDigest hasher = java.security.MessageDigest.getInstance("MD5"); //MD5 or SHA1
hasher.reset();
hasher.update(input);
byte[] digest = hasher.digest();
BigInteger bigInt = new BigInteger(1, digest);
String hashtext = bigInt.toString(16); // The hashes are base-16 numbers
// Now we need to zero pad it if you actually want the full 32 chars.
while(hashtext.length() < hasher.getDigestLength() ){
hashtext = "0"+hashtext;
}
return hashtext;
}
}
Hope this helps!
This question already has answers here:
Encoding as Base64 in Java
(19 answers)
Closed 7 years ago.
I want to encode a string into base64 and transfer it through a socket and decode it back.
But after decoding it gives different answer.
Following is my code and result is "77+9x6s="
import javax.xml.bind.DatatypeConverter;
public class f{
public static void main(String a[]){
String str = new String(DatatypeConverter.parseBase64Binary("user:123"));
String res = DatatypeConverter.printBase64Binary(str.getBytes());
System.out.println(res);
}
}
Any idea about how to implement this?
You can use following approach:
import org.apache.commons.codec.binary.Base64;
// Encode data on your side using BASE64
byte[] bytesEncoded = Base64.encodeBase64(str.getBytes());
System.out.println("encoded value is " + new String(bytesEncoded));
// Decode data on other side, by processing encoded data
byte[] valueDecoded = Base64.decodeBase64(bytesEncoded);
System.out.println("Decoded value is " + new String(valueDecoded));
Hope this answers your doubt.
Java 8 now supports BASE64 Encoding and Decoding. You can use the following classes:
java.util.Base64, java.util.Base64.Encoder and java.util.Base64.Decoder.
Example usage:
// encode with padding
String encoded = Base64.getEncoder().encodeToString(someByteArray);
// encode without padding
String encoded = Base64.getEncoder().withoutPadding().encodeToString(someByteArray);
// decode a String
byte [] barr = Base64.getDecoder().decode(encoded);
The accepted answer uses the Apache Commons package but this is how I did it using Java's native libraries
Java 11 and up
import java.util.Base64;
public class Base64Encoding {
public static void main(String[] args) {
Base64.Encoder enc = Base64.getEncoder();
Base64.Decoder dec = Base64.getDecoder();
String str = "77+9x6s=";
// encode data using BASE64
String encoded = enc.encodeToString(str.getBytes());
System.out.println("encoded value is \t" + encoded);
// Decode data
String decoded = new String(dec.decode(encoded));
System.out.println("decoded value is \t" + decoded);
System.out.println("original value is \t" + str);
}
}
Java 6 - 10
import java.io.UnsupportedEncodingException;
import javax.xml.bind.DatatypeConverter;
public class EncodeString64 {
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "77+9x6s=";
// encode data using BASE64
String encoded = DatatypeConverter.printBase64Binary(str.getBytes());
System.out.println("encoded value is \t" + encoded);
// Decode data
String decoded = new String(DatatypeConverter.parseBase64Binary(encoded));
System.out.println("decoded value is \t" + decoded);
System.out.println("original value is \t" + str);
}
}
The better way would be to try/catch the encoding/decoding steps but hopefully you get the idea.
For Spring Users , Spring Security has a Base64 class in the org.springframework.security.crypto.codec package that can also be used for encoding and decoding of Base64.
Ex.
public static String base64Encode(String token) {
byte[] encodedBytes = Base64.encode(token.getBytes());
return new String(encodedBytes, Charset.forName("UTF-8"));
}
public static String base64Decode(String token) {
byte[] decodedBytes = Base64.decode(token.getBytes());
return new String(decodedBytes, Charset.forName("UTF-8"));
}
The following is a good solution -
import android.util.Base64;
String converted = Base64.encodeToString(toConvert.toString().getBytes(), Base64.DEFAULT);
String stringFromBase = new String(Base64.decode(converted, Base64.DEFAULT));
That's it. A single line encoding and decoding.
import javax.xml.bind.DatatypeConverter;
public class f{
public static void main(String a[]){
String str = new String(DatatypeConverter.printBase64Binary(new String("user:123").getBytes()));
String res = DatatypeConverter.parseBase64Binary(str);
System.out.println(res);
}
}