java—字节长度在转换为字符串后发生变化

57hvy0tb  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(336)

我想将字节转换成字符串以进行加密,然后检索相同的字节进行解密。但问题是,在生成16字节的iv之后,我将其转换为字符串,当我尝试从字符串中获取相同的字节时,字节的长度会发生变化。下面是复制问题的示例程序。

package com.prahs.clinical6.mobile.edge.util;

import java.security.SecureRandom;
import java.util.Random;

import javax.crypto.spec.IvParameterSpec;

public class Test {

  public static void main(String[] args) {
    Random rand = new SecureRandom();
    byte[] bytes = new byte[16];
    rand.nextBytes(bytes);
    IvParameterSpec ivSpec = new IvParameterSpec(bytes);
    System.out.println("length of bytes before converting to String: " + ivSpec.getIV().length);
    String ibString = new String(ivSpec.getIV());
    System.out.println("length of bytes after converting to String: " + ibString.getBytes().length);
  }
}

请任何人都能确认为什么会有这样的行为,我需要修改什么才能得到相同长度的字节,即:16在这种情况下。

guz6ccqo

guz6ccqo1#

请不要将随机生成的字节数组转换为字符串,因为有很多值无法编码为字符串—请考虑x00。
将这样的字节数组“转换”为字符串的常用方法是字节数组的base64编码。这将使字符串延长约1/3,但可以无损地将字符串重新编码到字节数组中。
请注意不要使用 Random 但是 SecureRandom 作为这些数据的来源。
输出:

length of bytes before converting to String: 16
ivBase64: +wQtdbbbFdvrorpFb6LRTw==
length of bytes after converting to String: 16
ivSpec equals to ivRedecoded: true

代码:

import javax.crypto.spec.IvParameterSpec;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;

public class Main {
    public static void main(String[] args) {
        //Random rand = new SecureRandom();
        SecureRandom rand = new SecureRandom();
        byte[] bytes = new byte[16];
        rand.nextBytes(bytes);
        IvParameterSpec ivSpec = new IvParameterSpec(bytes);
        System.out.println("length of bytes before converting to String: " + ivSpec.getIV().length);
        //String ibString = new String(ivSpec.getIV());
        String ivBase64 = Base64.getEncoder().encodeToString(ivSpec.getIV());
        System.out.println("ivBase64: " + ivBase64);
        byte[] ivRedecoded = Base64.getDecoder().decode(ivBase64);
        //System.out.println("length of bytes after converting to String: " + ibString.getBytes().length);
        System.out.println("length of bytes after converting to String: " + ivRedecoded.length);
        System.out.println("ivSpec equals to ivRedecoded: " + Arrays.equals(ivSpec.getIV(), ivRedecoded));
    }
}

相关问题