public static DeviceEntity decrypt(String encryptedString) {
    // Check if encryptedString is null or empty
    if (encryptedString == null || encryptedString.isEmpty()) {
        return null;
    }

    // Check if encryptedString is a valid Base64 encoded string
    if (!Base64.isBase64(encryptedString)) {
        return null;
    }

    IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR.getBytes(StandardCharsets.UTF_8));
    SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");

    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        return null;
    }
    try {
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
    } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
        return null;
    }

    byte[] original = new byte[0];
    try {
        original = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
    } catch (IllegalBlockSizeException | BadPaddingException e) {
        return null;
    }
    String combinedString = new String(original);

    String[] parts = combinedString.split(":");
    // Check if the combinedString has enough parts
    if (parts.length < 3) {
        return null;
    }
    try {
        long id = Long.parseLong(parts[1]);
        String inputString = parts[2];

        DeviceEntity deviceEntity = new DeviceEntity();
        deviceEntity.setDeviceId(id);
        deviceEntity.setQrCode(inputString);
        return deviceEntity;
    } catch (NumberFormatException e) {
        return null;
    }
}

该代码首先检查传入的加密字符串是否为空或空字符串,如果是则返回 null。然后,使用 Base64.isBase64() 方法验证传入的字符串是否为有效的 Base64 编码字符串,如果不是则返回 null。

接下来,代码使用 AES 解密字符串,并将其拆分成三个部分:id、inputString 和其他信息。代码使用 Long.parseLong() 方法将 id 部分转换为长整型,并使用 String 类将 inputString 部分转换为字符串。

最后,代码将解析后的信息封装到 DeviceEntity 对象中,并返回该对象。如果在解析过程中出现任何错误,则返回 null。

该代码包含以下关键步骤:

  • 检查传入的加密字符串是否为空或空字符串。
  • 验证传入的字符串是否为有效的 Base64 编码字符串。
  • 使用 AES 解密字符串。
  • 拆分解密后的字符串。
  • 解析 id 和 inputString 部分。
  • 将解析后的信息封装到 DeviceEntity 对象中。
  • 在出现错误时返回 null。

该代码对错误进行了处理,确保程序的稳定性和可靠性。

AES 解密字符串并解析 DeviceEntity 对象

原文地址: https://www.cveoy.top/t/topic/Kwr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录