簡體   English   中英

將其轉換為字符串后字節長度發生變化

[英]Length of bytes changes after converting it to String

我想將字節轉換為字符串以進行加密,然后我想檢索相同的字節進行解密。 但問題是,在生成 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。

請不要將隨機生成的字節數組轉換為字符串,因為有很多值無法編碼為字符串 - 只需考慮 x00。

將這樣的字節數組“轉換”為字符串的常用方法是字節數組的Base64 編碼 這會將字符串延長約 1/3,但您可以無損地將字符串重新解碼為字節數組。

請注意,您不應使用Random而應使用SecureRandom作為這些數據的來源。

output:

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));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM