Java實現AES對稱加密算法


Java代碼實現

 

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class AesEntriptor {
	private Cipher encryptCipher; // 負責加密工作
	private Cipher decryptCipher; // 負責解密工作
	public AesEntriptor(String rules) throws Exception {
		// 1.實例化AES算法密鑰生成器
		KeyGenerator keygen = KeyGenerator.getInstance("AES");
		// 2.根據傳入的字節數組,生成一個128位的隨機源
		keygen.init(128, new SecureRandom(rules.getBytes()));
		// 3.生成密鑰
		SecretKey secretKey = keygen.generateKey();
		// 4.生成Cipher對象,指定其支持AES算法
		encryptCipher = Cipher.getInstance("AES");
		decryptCipher = Cipher.getInstance("AES");
		// 5.初始化加密對象及解密對象
		encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey);
		decryptCipher.init(Cipher.DECRYPT_MODE, secretKey);
	}

	public byte[] encrypt(byte[] source) throws Exception {
		return encryptCipher.doFinal(source);
	}

	public byte[] decrypt(byte[] source) throws Exception {
		return decryptCipher.doFinal(source);
	}

	public static void main(String[] args) throws Exception {
		AesEntriptor aesEntriptor = new AesEntriptor("123456");
		byte[] encrypt = aesEntriptor.encrypt("Napolean".getBytes());
		byte[] decrypt = aesEntriptor.decrypt(encrypt);
		System.out.println(new String(decrypt));
	}
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM