Search code examples
javac#unicode

How to remove little-endian byte 0 in Java


#C encodes original myValue before encryption.

var myBytes = Encoding.Unicode.GetBytes(myValue);

var encryptedResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, myBytes);

var encryptedmyString = Convert.ToBase64String(encryptedResult.Ciphertext);

I need to decrypt it in Java.

byte[] code = Base64.getDecoder().decode(encryptedmyString);

DecryptResult decryptionResult = cryptoClient.decrypt(EncryptionAlgorithm.RSA_OAEP, code);

String result = new String(decryptionResult.getPlainText(), StandardCharsets.UTF_8);

result has 0 after each byte. I found out this article about little-endian byte Why Encoding.Unicode.GetBytes() returns an additional 0

How to remove those extra 0 in Java?

Updated:

I am not #C developer. I can't change their code.

If I tried this after decryption, it gives me wrong "搀攀瘀栀最愀瀀瀀猀琀漀爀愀最攀戀氀漀戀"

new String(decryptionResult.getPlainText(), StandardCharsets.UTF_16);

Solution

  • Thanks for JosefZ's answer in the comment. It works

       new String(decryptionResult_.getPlainText(), StandardCharsets.UTF_16LE);