java aes加密长度_关于Java下的AES加密明文长度的问题

本文介绍了Java中AES加密的相关知识,包括如何生成密钥、加密和解密过程。通过一个具体的示例展示了如何使用AES对指定数据进行加解密操作,强调了AES加密时明文长度的要求。
摘要由CSDN通过智能技术生成

[Java] 纯文本查看 复制代码package com.example.AESTest;

import java.security.SecureRandom;

import java.util.Arrays;

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

public class MyClass {

private static final String ALGORITHM = "AES";

/**

* 生成一个密钥

* @param password用于当做密钥生成种子

* [url=home.php?mod=space&uid=155549]@Return[/url] secretKey生成的密钥

* @throws Exception

*/

private static SecretKey geneKey(String password) throws Exception {

KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);

SecureRandom random = new SecureRandom();

random.setSeed(password.getBytes());

keyGenerator.init(256);

keyGenerator.init(random);

SecretKey secretKey = keyGenerator.generateKey();

return secretKey;

}

/**

* 加密

* @param password秘钥

* @param data明文

* @return result密文

* @throws Exception

*/

public static byte[] testEncrypt(byte[] data,String password) throws Exception {

Cipher cipher = Cipher.getInstance(ALGORITHM);

SecretKey secretKey = geneKey(password);

cipher.init(Cipher.ENCRYPT_MODE, secretKey);

cipher.update(data);

byte[] result = cipher.doFinal();

return result;

}

/**

* 解密

* @param password秘钥

* @param data密文

* @return result明文

* @throws Exception

*/

public static byte[] testDecrpyt(byte[] data,String password) throws Exception {

Cipher cipher = Cipher.getInstance(ALGORITHM);

SecretKey secretKey = geneKey(password);

cipher.init(Cipher.DECRYPT_MODE, secretKey);

byte[] encodedBytes = data;

byte[] result = cipher.doFinal(encodedBytes);

return result;

}

public static void main(String[] args) throws Exception {

byte[] input= {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};

System.out.println("Source Data: "+Arrays.toString(input));

String password="123456";

byte[] temp;

temp=testEncrypt(input,password);

System.out.println("Encrypt Data: "+Arrays.toString(temp));

byte[] output=testDecrpyt(temp,password);

System.out.println("Decrypt Data: "+Arrays.toString(output));

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值