zoukankan      html  css  js  c++  java
  • 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));
    	}
    }
    

      

  • 相关阅读:
    CentOS7系统基本操作
    python3安装
    nodejs基础【持续更新中】
    基于Jenkins实现持续集成【持续更新中】
    git之merge和rebase的区别
    服务器为什么这么慢?耗尽了CPU、RAM和磁盘I/O资源
    编程的四个境界
    Gunicorn独角兽
    Python 中 logging 日志模块在多进程环境下的使用
    vue+webpack怎么分环境进行打包
  • 原文地址:https://www.cnblogs.com/q924152020/p/12049272.html
Copyright © 2011-2022 走看看