如何在Java中移除小端字节0

huangapple go评论62阅读模式
英文:

How to remove little-endian byte 0 in Java

问题

以下是翻译好的部分:

#C 在加密之前对myValue进行编码
    
    byte[] myBytes = myValue.getBytes(StandardCharsets.UTF_16);
    
    byte[] code = cryptoClient.encrypt(EncryptionAlgorithm.RSA_OAEP, myBytes);
    
    String encryptedmyString = Base64.getEncoder().encodeToString(code);

我需要在Java中解密它

    byte[] code = Base64.getDecoder().decode(encryptedmyString);
    
    DecryptResult decryptionResult = cryptoClient.decrypt(EncryptionAlgorithm.RSA_OAEP, code);
    
    String result = new String(decryptionResult.getPlainText(), StandardCharsets.UTF_8);

在每个字节后面出现了额外的0我找到了关于小端字节序的这篇文章https://stackoverflow.com/questions/32585671/why-encoding-unicode-getbytes-returns-an-additional-0

如何在Java中去掉这些额外的0

**更新**

我不是C#开发者我不能更改他们的代码

如果我在解密后尝试以下操作它会给我错误的结果"搀攀瘀栀最愀瀀瀀猀琀漀爀愀最攀戀氀漀戀"

    new String(decryptionResult.getPlainText(), StandardCharsets.UTF_16);
英文:

#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 https://stackoverflow.com/questions/32585671/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);

答案1

得分: 1

感谢JosefZ在评论中的回答。它有效:

new String(decryptionResult_.getPlainText(), StandardCharsets.UTF_16LE);
英文:

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

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

huangapple
  • 本文由 发表于 2023年2月24日 09:08:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551778.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定