AES - Java编程: 使用AES

本文详细介绍了AES加密算法的基本原理及在Java中的实现方式。探讨了密钥长度、块大小的要求,并展示了如何通过不同填充方式处理非16字节整数倍的数据长度问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AES每次加密的block长度为16字节,密码也是16个字节。JAVA中该算法名为 AES

try
{
    String password = "0123456789abcdef";
    byte[] b = password.getBytes();
    SecretKeySpec sks = new SecretKeySpec(b, "AES");
    
    Cipher c = Cipher.getInstance("AES");
    c.init(Cipher.ENCRYPT_MODE, sks);
    
    String plain = "shaofa0012345678";
    byte [] input = plain.getBytes();
    byte [] output = c.update(plain.getBytes());
    
    System.out.println("haha");
}
catch(Exception e)
{
    e.printStackTrace();
}



加密结果:

-6 51 117 126 30 53 7 76 120 -89 91 -99 -94 -59 52 84

ECB , No Padding, 对于输入数据长度不为16的整数倍时,应填充为整数倍

			String password = "0123456789abcdef";
			byte[] b = password.getBytes("US-ASCII");
			SecretKeySpec sks = new SecretKeySpec(b, "AES");
			
		    Cipher c = Cipher.getInstance("AES/ECB/NoPadding");
		    c.init(Cipher.ENCRYPT_MODE, sks);
			
			String plain = "shaofa0012345678";
			byte [] input = plain.getBytes();
			byte [] output = c.update(plain.getBytes());
			
		    //Cipher c2 = Cipher.getInstance("AES/ECB/NoPadding");
		    c.init(Cipher.DECRYPT_MODE, sks);
		    byte [] pp = c.update(output);
		    

即使用PKCS5Padding,并不能实质性描述长度问题。PKCS5Padding是说,当长度不为整数倍是,以数字N填充。N = 16 - 实际长度。例如:

实际长度为14,,则填充2个0x02

* * * * * * * *     * * * * * * *   02  02

实际长度为1,则填充15个0x0E

*  0E 0E 0E    0E 0E 0E 0E   0E 0E 0E 0E    0E 0E 0E 0E

如果原文刚好末尾有2个02时,就难以区别是填充的值,还是原文的值。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿发你好

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值