AES/ECB/NoPadding 全0填充代码

加密算法:

Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
int blockSize = cipher.getBlockSize();

byte[] dataBytes = sSrc.getBytes();
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
    plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
}

byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

SecretKeySpec keyspec = new SecretKeySpec(sKey.getBytes(), "AES");

cipher.init(Cipher.ENCRYPT_MODE, keyspec);
byte[] encrypted = cipher.doFinal(plaintext);

String base64encodedString = new BASE64Encoder().encode(encrypted);

return base64encodedString;

解密算法:

sSrc = sSrc.replaceAll("\\s", ""); //去掉空白字符
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);

Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(sKey.getBytes(), "AES");

cipher.init(Cipher.DECRYPT_MODE, keyspec);

byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;

测试类:

/*
 * 此处使用AES-ECB加密模式。
 */
String cKey = "222fguAJf9bpI4ptUZ";
// 需要加密的字串
String cSrc = "hello";
System.out.println(cSrc);
// 加密
String enString = AESUtils.encrypt(cSrc, cKey);
System.out.println("加密后的字串是:" + enString);

// 解密
String DeString = AESUtils.decrypt(enString, cKey);
System.out.println("解密后的字串是:" + DeString);

问题:1.base64超过76的长度以后,会加\r\n和空格隔开,java默认的base64解析器没有处理这个,这其实是java的问题了 base64的规矩就是会换行的,需要手动过滤一下,把\r\n和空格去掉,data = data.replaceAll("\\s", "");用这个把要解密的东西去掉空白字符,就是\r\n和空格,如果不想手动去空格的话,就不用java.util的base64改用sun.misc下的BASE64Decoder,这是个安全杂项(MISC)包,里面加解密各种工具还蛮全的。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值