java安全1

package com.ngsn.security;


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

/**
 * 对称加密(加密解密的密钥一样)
 * @author John.Yao
 *
 */
public class SecretKeyTest {
	
	public static void main(String[] args) throws Exception{
		//Cipher  此类为加密和解密提供密码功能
		Cipher cipher = Cipher.getInstance("AES");
		//根据AES的加密方法生成一个密钥
		SecretKey key = KeyGenerator.getInstance("AES").generateKey();
		//初始化
		//Cipher.ENCRYPT_MODE 为加密模式
		//key 为加密的密钥
		cipher.init(Cipher.ENCRYPT_MODE,key);
		//对byte[] 进行加密,返回一个加密后的byte[]
		byte[] result = cipher.doFinal("abc".getBytes());
		System.out.println("result----->"+new String(result));
		
		
		//解密
		//初始化
		cipher.init(Cipher.DECRYPT_MODE, key);
		//对加密后的byte[]进行解密
		byte[] b = cipher.doFinal(result);
		System.out.println("b------>"+new String(b));
		
		
	}
}

你可能感兴趣的:(java)