java 将base64编码的字符串转换为java字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/865460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:07:59  来源:igfitidea点击:

Convert base64 encoded string to java byte array

javaarraysbyteunsigned

提问by Chochos

I am writing a decryption class (AES/CBC/PKCS7Padding) where the encrypted data is coming from C#. I want to take the following string (which is base64 encoded):

我正在编写一个解密类 (AES/CBC/PKCS7Padding),其中加密数据来自 C#。我想采用以下字符串(base64 编码):

usiTyri3/gPJJ0F6Kj9qYL0w/zXiUAEcslUH6/zVIjs=

usiTyri3/gPJJ0F6Kj9qYL0w/zXiUAEcslUH6/zVIjs=

and convert it to a byte array in java to pass into the SecretKeySpec as the key. I know there is the issue of C# having unsigned bytes and java only having signed bytes. How then can I pass this sting which has values greater than 127 within it and have java accept the key and initialization vectors?

并将其转换为java中的字节数组作为密钥传递给SecretKeySpec。我知道存在 C# 具有无符号字节而 java 只有有符号字节的问题。那么我如何传递这个值大于 127 的 sting 并让 java 接受键和初始化向量?

回答by Chochos

You don't have to worry about byte signedness because base64 encoded data never uses more than 6 bits in each byte (that's why it's called base 64, because you only use 64 characters which is 6 bits, to represent part of a data byte).

您不必担心字节签名,因为 base64 编码的数据在每个字节中使用的位数永远不会超过 6 位(这就是为什么它被称为 base 64,因为您只使用 64 个字符,即 6 位,来表示数据字节的一部分) .

If your concern is the resulting data (3 data bytes for every 4 base64 characters), don't worry about that, either. An unsigned byte 255 in C# is the same as the signed byte -1 in Java.

如果您关心的是结果数据(每 4 个 base64 字符 3 个数据字节),也不要担心。C# 中的无符号字节 255 与 Java 中的有符号字节 -1 相同。

To encode data, you can bitwise-and each byte with 0xff and store it in an int, then encode the least significant 8 bits. Or just bitwise-or each byte with 0x80 and store it in ant int and decode the least significant 8 bits.

要对数据进行编码,您可以使用 0xff 按位和每个字节并将其存储在一个 int 中,然后对最低有效 8 位进行编码。或者只是按位或每个字节与 0x80 并将其存储在 ant int 中并解码最低有效 8 位。

But I think you would be better off using Bouncy Castle or the standard JCE to deal with all that stuff. The 'S' in PKCS7 means Standard so data encrypted in C# should decrypt fine in Java and vice versa.

但我认为最好使用 Bouncy Castle 或标准 JCE 来处理所有这些问题。PKCS7 中的“S”表示标准,因此在 C# 中加密的数据应该可以在 Java 中解密,反之亦然。