GVKun编程网logo

为什么新的String(bytes,enc).getBytes(enc)不返回原始字节数组?(new string getbytes)

23

这篇文章主要围绕为什么新的String和bytes,enc.getBytes展开,旨在为您提供一份详细的参考资料。我们将全面介绍为什么新的String的优缺点,解答bytes,enc.getBytes

这篇文章主要围绕为什么新的Stringbytes,enc.getBytes展开,旨在为您提供一份详细的参考资料。我们将全面介绍为什么新的String的优缺点,解答bytes,enc.getBytes的相关问题,同时也会为您带来'str = new String(bytes,“ UTF8”)'和'bytes = str.getBytes(“ UTF8”)'中的字节数不相同、(透彻)java String.getBytes()编码问题、byte[]->new String(byte[]) -> getByte()引发的不一致问题、c# – Convert.ToBase64String / Convert.FromBase64String和Encoding.UTF8.GetBytes / Encoding.UTF8.GetString之间的区别的实用方法。

本文目录一览:

为什么新的String(bytes,enc).getBytes(enc)不返回原始字节数组?(new string getbytes)

为什么新的String(bytes,enc).getBytes(enc)不返回原始字节数组?(new string getbytes)

我进行了以下“模拟”:

byte[] b = new byte[256];for (int i = 0; i < 256; i ++) {    b[i] = (byte) (i - 128);}byte[] transformed = new String(b, "cp1251").getBytes("cp1251");for (int i = 0; i < b.length; i ++) {    if (b[i] != transformed[i]) {        System.out.println("Wrong : " + i);    }}

对于cp1251此输出,仅错误的一个字节-在位置25。
对于KOI8-R-一切正常。
对于cp1252-4或5个差异。

这是什么原因,如何克服?

我知道以任何编码形式将字节数组表示为字符串是 错误的 ,但这是付款提供商协议的要求,因此我别无选择。

更新:ISO-8859-1作品中表示出来,我将在byte[]部分和cp1251文本部分使用它,因此问题仅出于好奇

答案1

小编典典

目标集中不支持某些“字节”-它们被替换为?字符。当您转换回去时,?通常会转换为字节值63-这不是以前的值。

'str = new String(bytes,“ UTF8”)'和'bytes = str.getBytes(“ UTF8”)'中的字节数不相同

'str = new String(bytes,“ UTF8”)'和'bytes = str.getBytes(“ UTF8”)'中的字节数不相同

如何解决''str = new String(bytes,“ UTF8”)''和''bytes = str.getBytes(“ UTF8”)''中的字节数不相同?

当您按原样对字符串进行解码时UTF-8,是因为您将字节编码为UTF-8或兼容格式。您不能只取一个byte[]随机字节并将其转换为字符串,因为它是二进制数据而不是文本。

您可以做的是对二进制文件使用Base64编码器,并使用Base64解码器将其转换回原始字节。

这样做的一种怪癖方法是使用ISO-8859-1,但这通常是个坏主意,因为您会混淆二进制数据和文本数据。

解决方法

我可以看到它们与我创建字符串所用的字节不同!我已经使用“ AES / CBC / PKCS5Padding”来获取字符串。

public static void main(String[] args) {

    try {
        int randomNumber = CNStationQueueUtil.randInt(0,99999);
        String key = "AES_KEY_TAKENUMB";
        byte[] bytes = EncryptHelper.encrypt(key,String.format("%%%d%%%d",1001,randomNumber));
        String str = new String(bytes,"UTF8");
        System.out.println("str = " + str);
        System.out.println();
        byte[] utf8Bytes = str.getBytes("UTF8");
        printBytes(utf8Bytes,"utf8Bytes");

    } catch (Exception e) {
        e.printStackTrace();
    }

}



public class EncryptHelper {

    public static byte[] encrypt(String key,String value)
            throws GeneralSecurityException {

        byte[] raw = key.getBytes(Charset.forName("UTF-8"));
        if (raw.length != 16) {
            throw new IllegalArgumentException("Invalid key size.");
        }

        SecretKeySpec skeySpec = new SecretKeySpec(raw,"AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE,skeySpec,new IvParameterSpec(new byte[16]));
        return cipher.doFinal(value.getBytes(Charset.forName("UTF-8")));
    }

    public static String decrypt(String key,byte[] encrypted)
            throws GeneralSecurityException {

        byte[] raw = key.getBytes(Charset.forName("UTF-8"));
        if (raw.length != 16) {
            throw new IllegalArgumentException("Invalid key size.");
        }
        SecretKeySpec skeySpec = new SecretKeySpec(raw,"AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE,new IvParameterSpec(new byte[16]));
        byte[] original = cipher.doFinal(encrypted);

        return new String(original,Charset.forName("UTF-8"));
    }
}

(透彻)java String.getBytes()编码问题

(透彻)java String.getBytes()编码问题

(透彻)java String.getBytes()编码问题 博客分类: java

转载自:

 

 

String.getBytes()的问题

String 的getBytes()方法是得到一个字串的字节数组,这是众所周知的。但特别要注意的是,本方法将返回该操作系统默认的编码格式的字节数组。如果你在使 用这个方法时不考虑到这一点,你会发现在一个平台上运行良好的系统,放到另外一台机器后会产生意想不到的问题。比如下面的程序:
class TestCharset { 
public static void main(String[] args) { 
new TestCharset().execute(); 
private void execute() { 
String s = "Hello!你好!"; 
byte[] bytes = s.getBytes();
System.out.println("bytes lenght is:" + bytes.length); 
}

在一个中文WindowsXP系统下,运行时,结果为:

bytes lenght is:12

但是如果放到了一个英文的UNIX环境下运行:

$ java TestCharset bytes lenght is:9

如果你的程序依赖于该结果,将在后续操作中引起问题。为什么在一个系统中结果为12,而在另外一个却变成了9了呢?上面已经提到了,该方法是和平台(编码)相关的。

在中文操作系统中,getBytes方法返回的是一个GBK或者GB2312的中文编码的字节数组,其中中文字符,各占两个字节。而在英文平台中,一般的默认编码是“ISO-8859-1”,每个字符都只取一个字节(而不管是否非拉丁字符)。

Java中的编码支持

Java是支持多国编码的,在Java中,字符都是以Unicode进行存储的,比如,“你”字的Unicode编码是“4f60”,我们可以通过下面的实验代码来验证:

 

class TestCharset { 
public static void main(String[] args) { 
char c = ''你''; 
int i = c; 
System.out.println(c); 
System.out.println(i); 
}

不管你在任何平台上执行,都会有相同的输出:

 

20320

20320就是Unicode “4f60”的整数值。其实,你可以反编译上面的类,可以发现在生成的.class文件中字符“你”(或者其它任何中文字串)本身就是以Unicode编码进行存储的:

 

char c = ''/u4F60''; ... ...

即使你知道了编码的编码格式,比如:

 

javac -encoding GBK TestCharset.java

编译后生成的.class文件中仍然是以Unicode格式存储中文字符或字符串的。使用String.getBytes(String charset)方法

所以,为了避免这种问题,我建议大家都在编码中使用String.getBytes(String charset)方法。下面我们将从字串分别提取ISO-8859-1和GBK两种编码格式的字节数组,看看会有什么结果:

[java] view plain copy
  1. package org.bruce.file.handle.experiment;  
  2.   
  3. class TestCharset3 {  
  4.     public static void main(String[] args) {  
  5.         new TestCharset3().execute();  
  6.     }  
  7.   
  8.     private void execute() {  
  9.         String s = "Hello!你好!";  
  10.         byte[] bytesISO8859 = null;  
  11.         byte[] bytesGBK = null;  
  12.         try {  
  13.             bytesISO8859 = s.getBytes("iso-8859-1");  
  14.             bytesGBK = s.getBytes("GBK");  
  15.         } catch (java.io.UnsupportedEncodingException e) {  
  16.             e.printStackTrace();  
  17.         }  
  18.         System.out.println("-------------- /n 8859 bytes:");  
  19.         System.out.println("bytes is: " + arrayToString(bytesISO8859));  
  20.         System.out.println("hex format is:" + encodeHex(bytesISO8859));  
  21.         System.out.println();  
  22.         System.out.println("-------------- /n GBK bytes:");  
  23.         System.out.println("bytes is: " + arrayToString(bytesGBK));  
  24.         System.out.println("hex format is:" + encodeHex(bytesGBK));  
  25.     }  
  26.   
  27.     public static final String encodeHex(byte[] bytes) {  
  28.         StringBuffer buff = new StringBuffer(bytes.length * 2);  
  29.         String b;  
  30.         for (int i = 0; i < bytes.length; i++) {  
  31.             b = Integer.toHexString(bytes[i]);  
  32.             // byte是两个字节的, 而上面的Integer.toHexString会把字节扩展为4个字节  
  33.             buff.append(b.length() > 2 ? b.substring(68) : b);  
  34.             buff.append(" ");  
  35.         }  
  36.         return buff.toString();  
  37.     }  
  38.   
  39.     public static final String arrayToString(byte[] bytes) {  
  40.         StringBuffer buff = new StringBuffer();  
  41.         for (int i = 0; i < bytes.length; i++) {  
  42.             buff.append(bytes[i] + " ");  
  43.         }  
  44.         return buff.toString();  
  45.     }  
  46. }  

执行上面程序将打印出:

 

-------------- 8859 bytes: bytes is: 72 101 108 108 111 33 63 63 63 
hex format is:48 65 6c 6c 6f 21 3f 3f 3f 
--------------  GBK bytes: bytes is: 72 101 108 108 111 33 -60 -29 -70 -61 -93 -95 
hex format is:48 65 6c 6c 6f 21 c4 e3 ba c3 a3 a1

可见,在s中提取的8859-1格式的字节数组长度为9,中文字符都变成了“63”,ASCII码为63的是“?”,一些国外的程序在国内中文环境下运行时,经常出现乱码,上面布满了“?”,就是因为编码没有进行正确处理的结果。

而提取的GBK编码的字节数组中正确得到了中文字符的GBK编码。字符“你”“好”“!”的GBK编码分别是:“c4e3”“bac3”“a3a1”。得到了正确的以GBK编码的字节数组,以后需要还原为中文字串时,可以使用下面方法:

 

new String(byte[] bytes, String charset)

 



   mysql 不支持 unicode,所以比较麻烦。
   将 connectionString 设置成 encoding 为 gb2312
   String connectionString
   = "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=gb2312";
  
  测试代码:
   String str = "汉字";
   PreparedStatement pStmt = conn.prepareStatement("INSERT INTO test VALUES (?)");
   pStmt.setString(1,str);
   pStmt.executeUpdate();
  
   数据库表格:
   create table test (
   name char(10)
   )
  
  
  连接  Oracle Database Server
  -------------------------------------------------------------------------------
   在把汉字字符串插入数据库前做如下转换操作:
   String(str.getBytes("ISO8859_1"),"gb2312")
  
  测试代码:
   String str = "汉字";
   PreparedStatement pStmt = conn.prepareStatement("INSERT INTO test VALUES (?)");
   pStmt.setString(1,new String(str.getBytes("ISO8859_1"),"gb2312");
   pStmt.executeUpdate();
  
  
  Servlet
  -------------------------------------------------------------------------------
   在 Servlet 开头加上两句话:
   response.setContentType("text/html;charset=UTF-8");
   request.setCharacterEncoding("UTF-8");
  
  JSP
  -------------------------------------------------------------------------------

 

byte[]->new String(byte[]) -> getByte()引发的不一致问题

byte[]->new String(byte[]) -> getByte()引发的不一致问题

今天接短信接口,短信接口提供了sdk,我们可以直接用sdk发送请求然后发送对应短信。

但是想使用我们平台自定义的httpUtil实现。

 

然而忙了1天半,才解决这个问题,还是我同事帮忙找出问题并解决的。

 

 步骤:

  1、请求信息转json

  2、json走AES加密得到byte[]

  3、将byte[]放入post请求发送,并接受响应。

sdk直接成功,它是自己基于HttpURLConnection封装的一套HttpUtil,直接接受了byte[]作为请求参数,使用post发送响应成功

我们的HttpUtil是基于HttpClient封装而来,post方法只能接受String或Map参数,于是将加密后的byte[] 进行new String()操作后传入,跟进信息,底层将该String采用getByte("UTF-8")进行转换给Request然后请求。一直返回解密失败。

反复调试,将contentType指定为text/plain,编码统一都是UTF-8。但依旧一直该错误。对比两种方式加密后byte[],没有区别。最后发现使用new String(byte[])之后getByte()得到的byte[]容量变大,颠覆我的认知了,byte[]数组经过指定编码new String()然后经过指定编码getByte[]得到的居然不一致。后面定位原因是我系统默认的编码和指定的编码都是UTF-8,但是AES加密产生的byte[]的编码是ISO-8859-1,导致得到的byte[]不是原来的byte[],所以解密失败。

 

 

 

 也就是说我前面解码byte[]得到字符串的时候使用了错误编码,导致后面getByte指定错误编码得到的字符串解密后不是原来的样子。

 

c# – Convert.ToBase64String / Convert.FromBase64String和Encoding.UTF8.GetBytes / Encoding.UTF8.GetString之间的区别

c# – Convert.ToBase64String / Convert.FromBase64String和Encoding.UTF8.GetBytes / Encoding.UTF8.GetString之间的区别

我目前正在学习.NET中的对称加密技术.我写了一个演示如下:
private byte[] key = Encoding.ASCII.GetBytes("abcdefgh");
    private byte[] IV = Encoding.ASCII.GetBytes("hgfedcba");
    private byte[] encrypted;

    public Form1()
    {
        InitializeComponent();

    }

    private void btnEncrypt_Click(object sender,EventArgs e)
    {
        this.textBox2.Text = this.Encrypt(this.textBox1.Text);
    }

    private void btnDecrypt_Click(object sender,EventArgs e)
    {
        this.textBox3.Text = this.Decrypt(this.textBox2.Text);
    }

    private string Encrypt(string plainText)
    {
        try
        {
            using (DESCryptoServiceProvider crypto = new DESCryptoServiceProvider())
            {
                crypto.Key = this.key;
                crypto.IV = this.IV;

                ICryptoTransform transform = crypto.CreateEncryptor(crypto.Key,crypto.IV);

                using (MemoryStream stream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(stream,transform,CryptoStreamMode.Write))
                    {
                        using (StreamWriter writer = new StreamWriter(cryptoStream))
                        {
                            writer.Write(plainText);
                        }

                        encrypted = stream.ToArray();
                    }
                }
            }

            return Convert.ToBase64String(encrypted);
        }
        catch (Exception)
        {

            throw;
        }
    }

    private string Decrypt(string cipherText)
    {
        try
        {
            string plainText = string.Empty;

            using (DESCryptoServiceProvider crypto = new DESCryptoServiceProvider())
            {
                crypto.Key = this.key;
                crypto.IV = this.IV;

                ICryptoTransform transform = crypto.CreateDecryptor(crypto.Key,crypto.IV);

                using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(cipherText)))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(stream,CryptoStreamMode.Read))
                    {
                        using (StreamReader reader = new StreamReader(cryptoStream))
                        {
                            plainText = reader.ReadToEnd();
                        }
                    }
                }
            }

            return plainText;
        }
        catch (Exception)
        {

            throw;
        }
    }

一切都按预期工作.但如果我更换

return Convert.ToBase64String(encrypted);

using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(cipherText)))

return Encoding.UTF8.GetString(encrypted);

using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(cipherText)))

我在CryptoStream System.NotSupportedException中有错误.在诊断代码之后,我发现Encoding.UTF8.GetBytes(cipherText)具有比加密更多的字节

那么使用Convert.From / ToBase64String和Encoding.UTF8.GetBytes / GetString有什么区别呢?

解决方法

UTF-8是一个字符编码.它将Unicode码点(字符)编码成字节.

Base64是二进制到文本编码.它将字节编码为文本.

在这种情况下你需要后者.

Encoding.UTF8.GetString解码一个UTF-8编码的字节数组,如果存在无效的字节序列(这很有可能是像密文一样给它随机字节),那么它是有损的.

我们今天的关于为什么新的Stringbytes,enc.getBytes的分享就到这里,谢谢您的阅读,如果想了解更多关于'str = new String(bytes,“ UTF8”)'和'bytes = str.getBytes(“ UTF8”)'中的字节数不相同、(透彻)java String.getBytes()编码问题、byte[]->new String(byte[]) -> getByte()引发的不一致问题、c# – Convert.ToBase64String / Convert.FromBase64String和Encoding.UTF8.GetBytes / Encoding.UTF8.GetString之间的区别的相关信息,可以在本站进行搜索。

本文标签: