当前位置:首页 > 开发 > 系统架构 > 架构 > 正文

java 简单实现AES/DES加解密

发表于: 2014-07-28   作者:antlove   来源:转载   浏览:
摘要: util.SecurityUtil.java package util; import java.security.Key; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey;

util.SecurityUtil.java

package util;

import java.security.Key;
import java.security.SecureRandom;

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

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class SecurityUtil {
	public static String DES = "AES"; // optional value AES/DES/DESede
	
	public static String CIPHER_ALGORITHM = "AES"; // optional value AES/DES/DESede
	

	public static Key getSecretKey(String key) throws Exception{
		SecretKey securekey = null;
		if(key == null){
			key = "";
		}
		KeyGenerator keyGenerator = KeyGenerator.getInstance(DES);
		keyGenerator.init(new SecureRandom(key.getBytes()));
		securekey = keyGenerator.generateKey();
		return securekey;
	}
	
	public static String encrypt(String data,String key) throws Exception {
        SecureRandom sr = new SecureRandom();
        Key securekey = getSecretKey(key);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
        byte[] bt = cipher.doFinal(data.getBytes());
        String strs = new BASE64Encoder().encode(bt);
        return strs;
    }
    
	
	public static String detrypt(String message,String key) throws Exception{
		SecureRandom sr = new SecureRandom();
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		Key securekey = getSecretKey(key);
		cipher.init(Cipher.DECRYPT_MODE, securekey,sr);
		byte[] res = new BASE64Decoder().decodeBuffer(message);
		res = cipher.doFinal(res);
		return new String(res);
	}
	
	public static void main(String[] args)throws Exception{
		String message = "password";
		String key = "";
		String entryptedMsg = encrypt(message,key);
		System.out.println("encrypted message is below :");
		System.out.println(entryptedMsg);
		
		String decryptedMsg = detrypt(entryptedMsg,key);
		System.out.println("decrypted message is below :");
		System.out.println(decryptedMsg);
	}
}

 

java 简单实现AES/DES加解密

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号