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

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

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

  1. package com.prahs.clinical6.mobile.edge.util;
  2. import java.security.SecureRandom;
  3. import java.util.Random;
  4. import javax.crypto.spec.IvParameterSpec;
  5. public class Test {
  6. public static void main(String[] args) {
  7. Random rand = new SecureRandom();
  8. byte[] bytes = new byte[16];
  9. rand.nextBytes(bytes);
  10. IvParameterSpec ivSpec = new IvParameterSpec(bytes);
  11. System.out.println("length of bytes before converting to String: " + ivSpec.getIV().length);
  12. String ibString = new String(ivSpec.getIV());
  13. System.out.println("length of bytes after converting to String: " + ibString.getBytes().length);
  14. }
  15. }

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

guz6ccqo

guz6ccqo1#

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

  1. length of bytes before converting to String: 16
  2. ivBase64: +wQtdbbbFdvrorpFb6LRTw==
  3. length of bytes after converting to String: 16
  4. ivSpec equals to ivRedecoded: true

代码:

  1. import javax.crypto.spec.IvParameterSpec;
  2. import java.security.SecureRandom;
  3. import java.util.Arrays;
  4. import java.util.Base64;
  5. public class Main {
  6. public static void main(String[] args) {
  7. //Random rand = new SecureRandom();
  8. SecureRandom rand = new SecureRandom();
  9. byte[] bytes = new byte[16];
  10. rand.nextBytes(bytes);
  11. IvParameterSpec ivSpec = new IvParameterSpec(bytes);
  12. System.out.println("length of bytes before converting to String: " + ivSpec.getIV().length);
  13. //String ibString = new String(ivSpec.getIV());
  14. String ivBase64 = Base64.getEncoder().encodeToString(ivSpec.getIV());
  15. System.out.println("ivBase64: " + ivBase64);
  16. byte[] ivRedecoded = Base64.getDecoder().decode(ivBase64);
  17. //System.out.println("length of bytes after converting to String: " + ibString.getBytes().length);
  18. System.out.println("length of bytes after converting to String: " + ivRedecoded.length);
  19. System.out.println("ivSpec equals to ivRedecoded: " + Arrays.equals(ivSpec.getIV(), ivRedecoded));
  20. }
  21. }
展开查看全部

相关问题