You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已实现字符串AES加密,如何在Java中支持整数值加密?

Java中整数值的AES加密/解密实现修改方案

AES加密的核心是对字节数组进行操作,要支持整数值加密,只需把整数转换成字节数组后走加密流程;解密时反向操作即可:将解密得到的字节数组转回整数。

加密逻辑修改(整数→加密字符串)

通过ByteBuffer把整数转换成标准字节数组,再传入AES加密流程:

import java.nio.ByteBuffer;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;

// 整数加密方法
public String encryptInteger(int plainInt, String secret) throws Exception {
    Cipher cipher = Cipher.getInstance(AES_ENCRYPTION_SCHEME);
    cipher.init(Cipher.ENCRYPT_MODE, getSecretKeyAES(secret));
    
    // 将int转换为4字节数组(默认使用JVM大端字节序)
    byte[] intBytes = ByteBuffer.allocate(4).putInt(plainInt).array();
    
    // 加密后转Base64字符串返回
    byte[] encryptedBytes = cipher.doFinal(intBytes);
    return Base64.encodeBase64String(encryptedBytes);
}

解密逻辑修改(加密字符串→整数)

解密得到字节数组后,再通过ByteBuffer转回整数:

// 整数解密方法
public int decryptInteger(String ciphertext, String secret) throws Exception {
    Cipher cipher = Cipher.getInstance(AES_ENCRYPTION_SCHEME);
    cipher.init(Cipher.DECRYPT_MODE, getSecretKeyAES(secret));
    
    // Base64解码得到加密字节数组
    byte[] encryptedBytes = Base64.decodeBase64(ciphertext);
    
    // 解密得到原始整数字节数组
    byte[] intBytes = cipher.doFinal(encryptedBytes);
    
    // 将字节数组转回int
    return ByteBuffer.wrap(intBytes).getInt();
}

关键注意事项

  • 字节序一致性:加密和解密必须使用相同的字节序(上述代码用JVM默认大端序,如需指定小端可调用ByteBuffer.order(ByteOrder.LITTLE_ENDIAN))
  • 类型适配:如果是long类型,只需把putInt/getInt替换为putLong/getLong,并将字节数组长度调整为8

内容的提问来源于stack exchange,提问作者tech-engg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:00:17