Package cn.gmkit.core

Class Bytes

java.lang.Object
cn.gmkit.core.Bytes

public final class Bytes extends Object
字节数组工具。

负责最基础的拷贝、拼接、定长校验和常量时间比较。

  • Method Summary

    Modifier and Type
    Method
    Description
    static byte[]
    clone(byte[] input)
    克隆字节数组
    static byte[]
    concat(byte[]... arrays)
    连接多个字节数组
    static boolean
    constantTimeEquals(byte[] left, byte[] right)
    常量时间比较两个字节数组是否相等,防止时间攻击。
    static byte[]
    copyOfRange(byte[] input, int from, int to)
    复制字节数组的指定范围
    static byte[]
    requireLength(byte[] input, int expectedLength, String label)
    验证字节数组长度是否符合要求
    static byte[]
    requireNonEmpty(byte[] input, String label)
    验证字节数组非空且至少包含一个字节。
    static byte[]
    requireNonNull(byte[] input, String label)
    验证字节数组不为null

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Method Details

    • clone

      public static byte[] clone(byte[] input)
      克隆字节数组
      Parameters:
      input - 待克隆的字节数组
      Returns:
      克隆后的新字节数组,如果输入为null则返回null
    • requireNonNull

      public static byte[] requireNonNull(byte[] input, String label)
      验证字节数组不为null
      Parameters:
      input - 待验证的字节数组
      label - 错误提示标签
      Returns:
      输入的字节数组
      Throws:
      GmkitException - 如果字节数组为null
    • requireNonEmpty

      public static byte[] requireNonEmpty(byte[] input, String label)
      验证字节数组非空且至少包含一个字节。
      Parameters:
      input - 待验证的字节数组
      label - 错误提示标签
      Returns:
      输入的字节数组
      Throws:
      GmkitException - 如果字节数组为 null 或长度为 0
    • requireLength

      public static byte[] requireLength(byte[] input, int expectedLength, String label)
      验证字节数组长度是否符合要求
      Parameters:
      input - 待验证的字节数组
      expectedLength - 期望的长度
      label - 错误提示标签
      Returns:
      输入的字节数组
      Throws:
      GmkitException - 如果字节数组为null或长度不符合要求
    • concat

      public static byte[] concat(byte[]... arrays)
      连接多个字节数组
      Parameters:
      arrays - 待连接的字节数组
      Returns:
      连接后的新字节数组
      Throws:
      GmkitException - 合并后的长度超过 Java 数组上限时抛出
    • constantTimeEquals

      public static boolean constantTimeEquals(byte[] left, byte[] right)
      常量时间比较两个字节数组是否相等,防止时间攻击。

      语义:

      • 任意一侧为 null 返回 false(短路 — null 永远不应是合法 MAC tag)。
      • 长度不同返回 false(长度不是机密 — 通常由消息格式公开)。
      • 两侧均为空数组返回 true(零字节 == 零字节)。
      • 长度相同时,恒定时间扫描全部字节,不因首字节匹配就早返回。
      Parameters:
      left - 第一个字节数组
      right - 第二个字节数组
      Returns:
      如果两个数组内容相同返回 true,否则返回 false
    • copyOfRange

      public static byte[] copyOfRange(byte[] input, int from, int to)
      复制字节数组的指定范围
      Parameters:
      input - 源字节数组
      from - 起始索引(包含)
      to - 结束索引(不包含)
      Returns:
      复制的字节数组