AES using Base64 Encryption - java

my target is to encrypt a String with AES
I am using Base64 for encryption, because AES needs a byte array as input.
Moreover i want every possible Char(including chinese and german Symbols) to be stored correctly
byte[] encryptedBytes = Base64.decodeBase64 ("some input");
System.out.println(new Base64().encodeToString(encryptedBytes));
I thought "some input" should be printed. Instead "someinpu" is printed.
It is impossible for me to use sun.misc.* Instead i am using apache.commons.codec
Does someone has a clue what's going wrong?

Yes - "some input" isn't a valid base64 encoded string.
The idea of base64 is that you encode binary data into text. You then decode that text data to a byte array. You can't just decode any arbitrary text as if it were a complete base64 message any more than you can try to decode an mp3 as a jpeg image.
Encrypting a string should be this process:
Encode the string to binary data, e.g. using UTF-8 (text.getBytes("UTF-8"))
Encrypt the binary data using AES
Encode the cyphertext using Base64 to get text
Decryption is then a matter of:
Decode the base64 text to the binary cyphertext
Decrypt the cyphertext to get the binary plaintext
Decode the binary plaintext into a string using the same encoding as the first step above, e.g. new String(bytes, "UTF-8")

You cannot use Base64 to turn arbitrary text into bytes; that's not what it's designed to do.
Instead, you should use UTF8:
byte[] plainTextBytes = inputString.getBytes("UTF8");
String output = new String(plainTextBytes, "UTF8");

Related

How to convert Base64(postgres migrated byte[] to base64) to byte[] in java?

I have converted byte[] to base64 in edb(postgres) using (encode( bytedata::bytea, 'base64')) and stored the base64 value in clob column. On java when I try to convert the base64 to byte[] I'm getting this error
Last unit does not have enough valid bits
Any help welcome.

How to get the same MD5 string in Java as in C#

I have code in C# which produces MD5 encoded byte[] from String and then this byte[] is converted to String. The C# code is
byte[] valueBytes = (new UnicodeEncoding()).GetBytes(value);
byte[] newHash = (new MD5CryptoServiceProvider()).ComputeHash(valueBytes);
I need to get the same result in Java. I'm trying to do this
Charset utf16 = Charset.forName("UTF-16");
return new String(DigestUtils.md5(value.getBytes(utf16)), utf16);
The code is using Apache Commons Codec library for MD5 calculations. I'm using UTF16 charset because I've read in other SO questions that C#'s UnicodeEncoding uses it by default.
So the code snippets look like they do the same thing, but when I'm passing the string byndyusoft2014, C# gives me hV7u6mQYRgBXXF9jOWWYJg== and Java gives me ﹡둛뭶魙ꇥ늺ꢑ. I've tried UTF16LE and UTF16BE as charsets with no luck.
Has anyone idea about what I'm doing wrong?
I think because of the java decode string to byte[] with utf-8,but the C# is not.So the java and C# encode the different byte array,and then get the different result.You can decode the string to byte[] at c# with utf-8,and see the result.Like following code:
UTF8Encoding utf8 = new UTF8Encoding();
byte[] bytes=utf8.GetBytes("byndyusoft2014");
byte[] en=(new MD5CryptoServiceProvider()).ComputeHash(bytes);
Console.WriteLine(Convert.ToBase64String(en));
and the java code:
byte[] en = DigestUtils.md5Digest("byndyusoft2014".getBytes());
byte[] base64 = Base64Utils.encode(en);
System.out.println(new String(base64));
Of course,in your description,the result of C# like be encoded with base64,so the java should encode the byte array with base64.
The result of them is same as swPvmbGDI1GbPKQwL9knjQ==
The DigestUtils and Base64Utils is some implementation of MD5 and BAS64 in spring library
As it turned out, the main difference was not presented in my original code snippet - it was convertation from MD5 encoded byte[] to String. You need to use Base64 to get final result. This is the working code snippet in Java
Charset utf16 = Charset.forName("UTF-16LE");
return new String(Base64.encodeBase64(DigestUtils.md5(value.getBytes(utf16))));
With this code I get the same result as with C#. Thank you all for good hints!

Converting a byte array to a string back to a byte array

I'm currently doing an assignment and I have a byte array that I write onto a file.
I want to be able to get the byte array back out of the file by doing the reverse of what I did but I don't think I'm getting the right value back.
This is the code to write to the text file
PrintWriter fw = new PrintWriter(new BufferedWriter(new FileWriter("tc.txt",true)));
KeyPair keyPair = generateKeyPair();
byte[] publicKey = keyPair.getPublic().getEncoded();
byte[] privateKey = keyPair.getPrivate().getEncoded();
fw.println(email +" " + publicKey + " " + privateKey); //adds the site into the text file whcih contains all the blacklisted sites
fw.flush();
And I try to get information back as a string and use .getBytes() to convert it back to a byte array like this
tempPublicKey = (blScanner.next()).getBytes();
It doesn't seem to be right, does something happen in-between that is wrong?
As you are writing arbitrary byte sequence to a text file, consider encoding your bytes to base64 format upon writing and decoding when you read this text file.
Text files are not suitable to store and retrieve arbitrary byte sequences, because some bytes may be recognized as formatting characters, etc, etc.
Encoding your bytes to base64 and decoding it back will preserve your byte sequence upon writing and reading to/from text file.

Hashing a password in java and trying to convert in string

I actually have a problem with hashing a password and trying to convert in string to put it in a database.
Currently I have this code
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(motsDePasse.getBytes(StandardCharsets.UTF_8));
String fileString = Base64.getEncoder().encodeToString(hash);
The deal is that it does not give me the good hash. Let's say I try to hash "12345". It should give me 5994471abb01112afcc18159f6cc74b4f511b99806da59b3caf5a9c173cacfc5.
But it actually return WZRHGrsBESr8wYFZ9sx0tPURuZgG2lmzyvWpwXPKz8U=
try using a hex encoder
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest("12345".getBytes(StandardCharsets.UTF_8));
String hex = DatatypeConverter.printHexBinary(hash);
System.out.println(hex);
output
5994471ABB01112AFCC18159F6CC74B4F511B99806DA59B3CAF5A9C173CACFC5
You are Base64 encoding it. If you Hex encode it, you will get the output you are looking for.
You're encoding your bytes in base 64. If you want to encode it in hexadecimal, try here: Java code To convert byte to Hexadecimal. If you're putting into a database as a string though, base64 should be fine for your needs.

Java: Is there any encoder which will not include forward slash during data encryption?

I need to pass data in encrypted format with URL like this,
http://localhost:8080/app/{encrypted_data}
So, is there any encoder which will not include forward slash(/) in encoding?
Please Note: I don't want to replace '/' by another character, manually, from the encoded data.
..............................................................................................................
Edited: comment from Oleg Estekhin of using Base64 URL safe Encoding is also working fine, I'm just adding an example over here.
EXAMPLE: Encode:
String str = "subjects?_d=1";
byte[] bytesEncoded = Base64.encodeBase64URLSafe((str.getBytes()));
Decode:
Base64 decoder = new Base64(true);
byte[] decodedBytes = decoder.decode(new String(bytesEncoded));
System.out.println(new String(decodedBytes));
Output:
c3ViamVjdHM_X2Q9MQ
subjects?_d=1
http://en.wikipedia.org/wiki/Base32
example:
Encode string to base32 string in Java

Categories