【问题标题】:random characters in byte to string conversion java字节到字符串转换java中的随机字符
【发布时间】:2013-10-16 20:29:48
【问题描述】:

我正在将字节 [] 转换为字符串。每次我将字节数组转换为字符串时,它前面都有一个前缀类型的字符。我试过不同的字符,大写等。仍然有前缀。

当我将字节码写入系统输出时,它仍然有字符。

System.out.write(theByteArray);

System.out.println(new String(theByteArray, "UTF-8"));

当我将文本写入文件时,看起来字节数组打印完美,但随后我扫描它并以奇怪的前缀符号结束...

要加密的文本>

"aaaa"

解密后转成字符串时的文本 >

"aaaa"

角色似乎消失了,这是它的图像。

我想将给定的字符串与另一个字符串进行比较,有点像解密密码,并将其与数据库进行比较。如果一个匹配,那么它就可以访问。

生成此字节码的代码。

请记住,我正在查看的字节是 decData,这不是我的代码。

byte[] encData;
        byte[] decData;
        File inFile = new File(fileName+ ".encrypted");

        //Generate the cipher using pass:
        Cipher cipher = FileEncryptor.makeCipher(pass, false);

        //Read in the file:
        FileInputStream inStream = new FileInputStream(inFile);

        encData = new byte[(int)inFile.length()];
        inStream.read(encData);
        inStream.close();
        //Decrypt the file data:
        decData = cipher.doFinal(encData);
        //Figure out how much padding to remove

        int padCount = (int)decData[decData.length - 1];

        //Naive check, will fail if plaintext file actually contained
        //this at the end
        //For robust check, check that padCount bytes at the end have same value
        if( padCount >= 1 && padCount <= 8 ) {
            decData = Arrays.copyOfRange( decData , 0, decData.length - padCount);
        }
        FileOutputStream target = new FileOutputStream(new File(fileName + ".decrypted.txt"));
        target.write(decData);
        target.close();

【问题讨论】:

  • 你说的前缀是什么?
  • 我不确定,它只是消失了,让我来一张图片,对不起。
  • 不要提供链接,使用编辑器上的图片按钮。
  • 这不是你如何比较字符串,你使用.equals()。

标签: java encryption type-conversion bytearray


【解决方案1】:

看起来 encData 包含 BOM 并且我认为 Java 在读取带有 BOM 的流时,只会将 BOM 视为 UTF-8 字符,这会导致“前缀”。您可以尝试此处建议的解决方案:Reading UTF-8 - BOM marker。

另一方面,字节顺序标记是可选的,不推荐用于 UTF-8 编码。所以要问的两个问题是:

  1. 原始数据是否使用 utf-8 编码?
  2. 如果是这样,可能值得花时间找出为什么 BOM 首先会进入原始数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 2011-07-26
    • 1970-01-01
    相关资源
    最近更新 更多