UnicodeEncoding in java - java

I have a string like that "QQBkADEBbgAxAXoA" I am creating a byte array of the string and using this code to convert it to string in c#.
string value = new UnicodeEncoding()).GetString(array)
I need this UnicodeEncoding in java. Is there a class that can perform it in java?

C# class UnicodeEncoding encodes on UTF-16.
String value = new String(bytes, "UTF-16LE");
The code above worked for me, since c# was using little endian representation, and Java UTF-16 is big endian.

The C# class UnicodeEncoding encodes the string using the UTF-16 encoding.
In Java you should be able to convert the bytes back to a string like this:
byte[] bytes = ...;
String value = new String(bytes, "UTF-16");
Or the other way around, convert a Java string to bytes using UTF-16 encoding:
byte[] bytes = value.getBytes("UTF-16");

Related

base32 decode to UTF in java

I want to decode a string to UTF-8 format in java. In the following code, I am able to get the expected decoded value from String decoded.
String s = "SFSFSFSFSF";
Base32 codec = new Base32();
String encoded = codec.encodeAsString(s.toUpperCase().getBytes());
Charset UTF_8 = Charset.forName("UTF-8");
String decoded =new String(codec.decode(encoded),UTF_8); // SFSFSFSFSF
String decoded2 = codec.decode(encoded); // [B#133314b
However, in my implementation specifically, I want to get the decoded val "SFSFSFSFSF" just by saying codec.decode(encoded) which is demonstrated in String decoded2 in the code. I want to know how I can achieve this by changing the way the String is encoded.

How to convert a string UTF-8 to ANSI in java?

I have a string in UTF-8 format. I want to convert it to clean ANSI format. How to do that?
You could use a java function like this one here to convert from UTF-8 to ISO_8859_1 (which seems to be a subset of ANSI):
private static String convertFromUtf8ToIso(String s1) {
if(s1 == null) {
return null;
}
String s = new String(s1.getBytes(StandardCharsets.UTF_8));
byte[] b = s.getBytes(StandardCharsets.ISO_8859_1);
return new String(b, StandardCharsets.ISO_8859_1);
}
Here is a simple test:
String s1 = "your utf8 stringáçﬠ";
String res = convertFromUtf8ToIso(s1);
System.out.println(res);
This prints out:
your utf8 stringáç?
The ﬠ character gets lost because it cannot be represented with ISO_8859_1 (it has 3 bytes when encoded in UTF-8). ISO_8859_1 can represent á and ç.
You can do something like this:
new String("your utf8 string".getBytes(Charset.forName("utf-8")));
in this format 4 bytes of UTF8 converts to 8 bytes of ANSI
Converting UTF-8 to ANSI is not possible generally, because ANSI only has 128 characters (7 bits) and UTF-8 has up to 4 bytes. That's like converting long to int, you lose information in most cases.

byte[] to String {100,25,28,-122,-26,94,-3,-26}

How can I convert this byte[] to String :
byte[] mytest = new byte[] {100,25,28,-122,-26,94,-3,-26};
i get this : "d��^�" when I use :
new String( mytest , "UTF-8" )
Here is code java for creation of key :
m_key = new javax.crypto.spec.SecretKeySpec(new byte[] {100,25,28,-122,-26,94,-3,-26}, "DES");
Thanks.
In order to decode the byte array into something like ASCII, you need to know its original encoding. Otherwise you would need to treat it as binary.
Note: Base64 is intended for transferring binary data across networks.
I would suggest Base64 encoding your byte array. Then in your PHP code decoding the Base64 string back into a UTF-8 string.
In Java, here's how to Base64 encode your byte array and then decode it back to UTF-8:
import org.apache.commons.codec.binary.Base64;
public class MyTest {
public static void main(String[] args) throws Exception {
byte[] byteArray = new byte[] {100,25,28,-122,-26,94,-3,-26};
System.out.println("To UTF-8 string: " + new String(byteArray, "UTF-8"));
byte[] base64 = Base64.encodeBase64(byteArray);
System.out.println("To Base64 string: " + new String(base64, "UTF-8"));
byte[] decoded = Base64.decodeBase64(base64);
System.out.println("Back to UTF-8 string: " + new String(decoded, "UTF-8"));
/* the decoded byte array is the same as the original byte array */
for (int i = 0; i < decoded.length; i++) {
assert byteArray[i] == decoded[i];
}
}
}
The output from the above code is:
To UTF-8 string: d��^�
To Base64 string: ZBkchuZe/eY=
Back to UTF-8 string: d��^�
So if you wanted to use the same binary data in your PHP code, cut and paste the Base64 string into your PHP code and decode it back to UTF-8. Something like this:
<?php
$str = 'ZBkchuZe/eY=';
$key = base64_decode($str);
echo $key;
?>
I don't code in PHP, but you should be able to decode Base64 using this method:
http://php.net/manual/en/function.base64-decode.php
The above code should echo back the original binary data as UTF-8 (albeit with funny characters). The point is that the funny-looking string in the $key variable is representing the same binary data you had in the Java byte array:
d��^�
You should be able to pass the $key variable into your PHP encryption method.
with the way you are doing it makes no sense imo. you are creating a new string with the byte[] as an argument. i dont think that function is suppose to parse. so what you end up with is a lot of junk. but a little bit of googling got me this: http://www.mkyong.com/java/how-do-convert-byte-array-to-string-in-java/
Would m_key.getEncoded() give you the desired result.
Javadocs - SecretKeySpec
If not, you have to identify the Key provider that was used for the encoding (which resulted in the byte array that you have now) and decode.

encrypt and decrypt string

I have a question regarding encrypting and decrypting a string
I have to send a encrypted string over the network.(an android app is the client) this is what i did so far
byte[] input = getByteArray(filePath);//get the message stored in a file as a byte array
by going through some tutorial i managed to get the String message to a byte array and
encrypted it using javax.crypto
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
encrypted msg is retrived as a byte array
byte[] encrypted
i even managed to decrypt it using the reverse method and get the message again
but my problem comes when i try to convert this encrypted byte array to strings (to pass it over the network)
and then reconvert it to a byte array
i tryed this
String encryptedStrn = new String(encrypted); // convert to string
when i convert it to the byte array by
byte[] enc = encryptedStrn.getBytes();
and use this enc array to decrypt but the output does not come correctly.
Have i missed some basic stuff regarding converting. Please help me.
thanks in advance
As CodeInChaos wrote in a comment, you shouldn't use the String(byte[]) constructor to create a string from opaque binary data. The string constructors are intended for text data which has been encoded using an encoding like ASCII, UTF-8 etc. Opaque binary data such as the result of encryption, or an image file, is not encoded text data in the same way, so you end up losing information.
You should use base64 instead, which encodes any binary data into ASCII. There are various 3rd party libraries for this, including a good public domain one. Alternatively, on Android you can just use the Base64 class.
Additionally, even when you are encoding or decoding real text, you shouldn't use String.getBytes() and the String(byte[]) constructor anyway - they use the platform default encoding, which is almost always the wrong choice. Instead, you should use the overloads which explicitly take a CharSet or the name of a character encoding. UTF-8 is typically a good encoding to use if you're able to control both ends - if you're only controlling one end, you need to know which encoding the other end is expecting.
You should base64-encode the cipher text. Don't just convert it to a String. String is not a container for binary data.
public string EncryptUser(string userID)
{
using (var cryptoProvider = new DESCryptoServiceProvider())
using (var memoryStream = new MemoryStream())
using (var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(DESKey, DESInitializationVector), CryptoStreamMode.Write))
using (var writer = new StreamWriter(cryptoStream))
{
writer.Write(userID);
writer.Flush();
cryptoStream.FlushFinalBlock();
writer.Flush();
return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
}
}
public string DecryptUserID(string userID)
{
using (var cryptoProvider = new DESCryptoServiceProvider())
using (var memoryStream = new MemoryStream(Convert.FromBase64String(userID)))
using (var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(DESKey, DESInitializationVector), CryptoStreamMode.Read))
using (var reader = new StreamReader(cryptoStream))
{
return reader.ReadToEnd();
}
}

How do I convert a byte array to Base64 in Java?

Okay, I know how to do it in C#.
It's as simple as:
Convert.ToBase64String(byte[])
and Convert.FromBase64String(string) to get byte[] back.
How can I do this in Java?
Java 8+
Encode or decode byte arrays:
byte[] encoded = Base64.getEncoder().encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = Base64.getDecoder().decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.getEncoder().encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
println(decoded) // Outputs "Hello"
For more info, see Base64.
Java < 8
Base64 is not bundled with Java versions less than 8. I recommend using Apache Commons Codec.
For direct byte arrays:
Base64 codec = new Base64();
byte[] encoded = codec.encode("Hello".getBytes());
println(new String(encoded)); // Outputs "SGVsbG8="
byte[] decoded = codec.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
Base64 codec = new Base64();
String encoded = codec.encodeBase64String("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(codec.decodeBase64(encoded));
println(decoded) // Outputs "Hello"
Spring
If you're working in a Spring project already, you may find their org.springframework.util.Base64Utils class more ergonomic:
For direct byte arrays:
byte[] encoded = Base64Utils.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte[] decoded = Base64Utils.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64Utils.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = Base64Utils.decodeFromString(encoded);
println(new String(decoded)) // Outputs "Hello"
Android (with Java < 8)
If you are using the Android SDK before Java 8 then your best option is to use the bundled android.util.Base64.
For direct byte arrays:
byte[] encoded = Base64.encode("Hello".getBytes());
println(new String(encoded)) // Outputs "SGVsbG8="
byte [] decoded = Base64.decode(encoded);
println(new String(decoded)) // Outputs "Hello"
Or if you just want the strings:
String encoded = Base64.encodeToString("Hello".getBytes());
println(encoded); // Outputs "SGVsbG8="
String decoded = new String(Base64.decode(encoded));
println(decoded) // Outputs "Hello"
Use:
byte[] data = Base64.encode(base64str);
Encoding converts to Base64
You would need to reference commons codec from your project in order for that code to work.
For java8:
import java.util.Base64
Additionally, for our Android friends (API Level 8):
import android.util.Base64
...
Base64.encodeToString(bytes, Base64.DEFAULT);
In case you happen to be using Spring framework along with java, there is an easy way around.
Import the following.
import org.springframework.util.Base64Utils;
Convert like this.
byte[] bytearr ={0,1,2,3,4};
String encodedText = Base64Utils.encodeToString(bytearr);
To decode you can use the decodeToString method of the Base64Utils class.

Categories

Resources