Encoding in Java - java

I have an C# function which i want to translate in Java code. I have a problem here:
Encoding enc = Encoding.GetEncoding("Windows-1252");
bytZeichenBenutzer = enc.GetBytes(strBenutzer.Substring(intLoopCount, 1).ToCharArray());
How to do that in Java? I can't find anything similar only stuff that works with UTF-8.

You can use the getBytes(String) or getBytes(Charset) methods:
String myString = getMyStringFromSomeWhere();
byte[] utf8Bytes = myString.getBytes("UTF-8");
// or
Charset myCharset = Charset.forName("Windows-1252");
byte[] windowsBytes = myString.getBytes(myCharset);

String s = "hhh";
try {
s.getBytes("Windows-1252");
} catch(UnsupportedEncodingException e) {
e.printStackTrace();
}

You can do:
byte[] a = "some string".getBytes("Windows-1252");

Related

Convert MD5 - base64 From JAVA to PHP

I have a problem converting this Java code that generate md5-base64 to php.
I'd try more then 5 hours but without success.
This is the java code:
public static void main(String[] args) {
// TODO code application logic here
try {
String string = "customString";
String format = "20190101000000";
StringBuilder sb = new StringBuilder();
sb.append(format);
sb.append(string);
String sb2 = sb.toString();
byte[] bytes = sb2.getBytes();
byte[] bArr = new byte[16];
MessageDigest instance2 = MessageDigest.getInstance("MD5");
instance2.update(bytes, 0, bytes.length);
instance2.digest(bArr, 0, 16);
PrintStream printStream6 = System.out;
String a2 = Base64.getEncoder().encodeToString(bArr);
if (a2.length() >= 20) {
a2 = a2.substring(0, 19).trim();
}
StringBuilder sb8 = new StringBuilder();
sb8.append("MD5 16: ");
sb8.append(a2);
printStream6.println(sb8.toString());
} catch (Exception e) {
System.out.println(e);
}
}
And this is my php
<?php
$string = 'customString';
$format = '20190101000000';
$res = $format . $string;
$md5 = md5($res, true);
echo $md5;
echo '------------------';
$base = base64_encode($md5);
echo $base;
echo '------------------';
$result = substr($base, 0, 19);
echo $result;
echo '------------------';
The Java result is 1B2M2Y8AsgTpgAmY7Ph and php is iSKxA+7Y1mMnHhwf0yb
Check for charset encodings. In Java Strings are usually UTF-8 encoded. But when you transform to byte[] in sb2.getBytes(); it is using platform default charset (e.g. ISO-8859-1).
You have to provide the charset in java to have a determined behavior:
sb2.getBytes(java.nio.charset.Charset.forName("UTF-8");
or, the other way round, if goal isn't simply to make both reproduce same output, but you have to implement a PHP solution compatible with your existing Java solution, convert the PHP UTF-8 string to correct charset before md5(...). Therefore use iconv method.

MD5 encoded parameter in URL

I am using following code to encrypt my email id in Java and sending it as a parameter in url (Using URLEncoder.encode(encrypteInput("email"))):
public static String encrypteInput(String input) {
String output = null;
input = input + ((int) Math.random()) % 1000;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
output = new String(md5.digest(input.getBytes()));
} catch (Exception e) {
output = "";
}
return output;
}
but, when I am getting the same parameter from servlet, it is not giving me the same output as encrypteInput("email").
Whenever you have a byte array that you want to store in a string, you should be Hex- or Base64-encoding the byte array (hex-encoding is probably better in this particular case).
Apache commons-codec has a Hex class you can use for this:
byte[] bytes = ...
char[] encoded = Hex.encodeHex(bytes);
String encodedString = new String(encoded);

Convert Byte String to alpha-numeric char array in java?

My question is, I guess, quite simple :
How to convert a Byte to alpha-numeric char array (String) in java ?
I tried this but it gives me back an error on netbeans :
byte[] b = "test".getBytes("ASCII");
String test = new String(b,"ASCII");
UPDATE :
I am actually using this code :
byte[] b = "test".getBytes("ASCII");
MessageDigest md = MessageDigest.getInstance("SHA-256");
String bla = new String(md.digest(b), "ASCII");
But once I try to use for other stuff which requires String with ASCII, I receive the following errors like "This is not ASCII".
I don't really understand, actually.
When I try to print it I got something weird like "2Q�h/�k�����"
Thank you in advance for your help.
You're close :
public static void main(String[] args) throws java.io.UnsupportedEncodingException { //you should throw or catch this exception
byte[] b = "test".getBytes("ASCII"); // And you must declare a byte array
String test = new String(b,"ASCII");
System.out.println(test); // Will output "test"
}
After your edits I think you want to generate a SHA-256 hash of a given String.
try {
byte[] b = "test".getBytes("ASCII");
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = md.digest(b);
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hashBytes.length; i++) {
hexString.append(Integer.toHexString(0xFF & hashBytes[i]));
}
System.out.println(hexString);
} catch (Exception e) {
e.printStackTrace();
}

Convert UTF-16 unicode characters to UTF-8 in java

When I got JSON then there are \u003c and \u003e instead of < and >. I want to convert them back to utf-8 in java. any help will be highly appreciated. Thanks.
try {
// Convert from Unicode to UTF-8
String string = "\u003c";
byte[] utf8 = string.getBytes("UTF-8");
// Convert from UTF-8 to Unicode
string = new String(utf8, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
refer http://www.exampledepot.com/egs/java.lang/unicodetoutf8.html
You can try converting the string into a byte array
byte[] utfString = str.getBytes("UTF-8") ;
and convert that back to a string object by specifying the UTF-8 encoding like
str = new String(utfString,"UTF-8") ;
You can also try this
String s = "Hello World!";
String convertedInUTF8 = new String(s, StandardCharsets.US_ASCII);

UTF-8 byte[] to String

Let's suppose I have just used a BufferedInputStream to read the bytes of a UTF-8 encoded text file into a byte array. I know that I can use the following routine to convert the bytes to a string, but is there a more efficient/smarter way of doing this than just iterating through the bytes and converting each one?
public String openFileToString(byte[] _bytes)
{
String file_string = "";
for(int i = 0; i < _bytes.length; i++)
{
file_string += (char)_bytes[i];
}
return file_string;
}
Look at the constructor for String
String str = new String(bytes, StandardCharsets.UTF_8);
And if you're feeling lazy, you can use the Apache Commons IO library to convert the InputStream to a String directly:
String str = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
Java String class has a built-in-constructor for converting byte array to string.
byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
String value = new String(byteArray, "UTF-8");
To convert utf-8 data, you can't assume a 1-1 correspondence between bytes and characters.
Try this:
String file_string = new String(bytes, "UTF-8");
(Bah. I see I'm way to slow in hitting the Post Your Answer button.)
To read an entire file as a String, do something like this:
public String openFileToString(String fileName) throws IOException
{
InputStream is = new BufferedInputStream(new FileInputStream(fileName));
try {
InputStreamReader rdr = new InputStreamReader(is, "UTF-8");
StringBuilder contents = new StringBuilder();
char[] buff = new char[4096];
int len = rdr.read(buff);
while (len >= 0) {
contents.append(buff, 0, len);
}
return buff.toString();
} finally {
try {
is.close();
} catch (Exception e) {
// log error in closing the file
}
}
}
You can use the String(byte[] bytes) constructor for that. See this link for details.
EDIT You also have to consider your plateform's default charset as per the java doc:
Constructs a new String by decoding the specified array of bytes using
the platform's default charset. The length of the new String is a
function of the charset, and hence may not be equal to the length of
the byte array. The behavior of this constructor when the given bytes
are not valid in the default charset is unspecified. The
CharsetDecoder class should be used when more control over the
decoding process is required.
You could use the methods described in this question (especially since you start off with an InputStream): Read/convert an InputStream to a String
In particular, if you don't want to rely on external libraries, you can try this answer, which reads the InputStream via an InputStreamReader into a char[] buffer and appends it into a StringBuilder.
Knowing that you are dealing with a UTF-8 byte array, you'll definitely want to use the String constructor that accepts a charset name. Otherwise you may leave yourself open to some charset encoding based security vulnerabilities. Note that it throws UnsupportedEncodingException which you'll have to handle. Something like this:
public String openFileToString(String fileName) {
String file_string;
try {
file_string = new String(_bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
// this should never happen because "UTF-8" is hard-coded.
throw new IllegalStateException(e);
}
return file_string;
}
Here's a simplified function that will read in bytes and create a string. It assumes you probably already know what encoding the file is in (and otherwise defaults).
static final int BUFF_SIZE = 2048;
static final String DEFAULT_ENCODING = "utf-8";
public static String readFileToString(String filePath, String encoding) throws IOException {
if (encoding == null || encoding.length() == 0)
encoding = DEFAULT_ENCODING;
StringBuffer content = new StringBuffer();
FileInputStream fis = new FileInputStream(new File(filePath));
byte[] buffer = new byte[BUFF_SIZE];
int bytesRead = 0;
while ((bytesRead = fis.read(buffer)) != -1)
content.append(new String(buffer, 0, bytesRead, encoding));
fis.close();
return content.toString();
}
String has a constructor that takes byte[] and charsetname as parameters :)
This also involves iterating, but this is much better than concatenating strings as they are very very costly.
public String openFileToString(String fileName)
{
StringBuilder s = new StringBuilder(_bytes.length);
for(int i = 0; i < _bytes.length; i++)
{
s.append((char)_bytes[i]);
}
return s.toString();
}
Why not get what you are looking for from the get go and read a string from the file instead of an array of bytes? Something like:
BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream( "foo.txt"), Charset.forName( "UTF-8"));
then readLine from in until it's done.
I use this way
String strIn = new String(_bytes, 0, numBytes);

Categories