1. 程式人生 > >字符串加密解密

字符串加密解密

div pan generated str and cto package class zha

DES加密解密算法

註意:此帶密匙,密匙長度貌似要8位及以上

package com.yc.security;

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

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.IOException;
import
java.security.SecureRandom; /** * DES加密 解密算法 * * @author zhangdi */ public class DesUtil { private final static String DES = "DES"; private final static String ENCODE = "GBK"; /** * Description 根據鍵值進行加密 * * @param data 待加密數據 * @param key 密鑰 *
@return * @throws Exception */ public static String encrypt(String data, String key) throws Exception { byte[] bt = encrypt(data.getBytes(ENCODE), key.getBytes(ENCODE)); String strs = new BASE64Encoder().encode(bt); return strs; } /** * 根據鍵值進行解密 * *
@param data 待解密數據 * @param key 密鑰 * @return * @throws IOException * @throws Exception */ public static String decrypt(String data, String key) throws IOException, Exception { if (data == null) return null; BASE64Decoder decoder = new BASE64Decoder(); byte[] buf = decoder.decodeBuffer(data); byte[] bt = decrypt(buf, key.getBytes(ENCODE)); return new String(bt, ENCODE); } /** * Description 根據鍵值進行加密 * * @param data * @param key 加密鍵byte數組 * @return * @throws Exception */ private static byte[] encrypt(byte[] data, byte[] key) throws Exception { // 生成一個可信任的隨機數源 SecureRandom sr = new SecureRandom(); // 從原始密鑰數據創建DESKeySpec對象 DESKeySpec dks = new DESKeySpec(key); // 創建一個密鑰工廠,然後用它把DESKeySpec轉換成SecretKey對象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher對象實際完成加密操作 Cipher cipher = Cipher.getInstance(DES); // 用密鑰初始化Cipher對象 cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); return cipher.doFinal(data); } /** * Description 根據鍵值進行解密 * * @param data * @param key 加密鍵byte數組 * @return * @throws Exception */ private static byte[] decrypt(byte[] data, byte[] key) throws Exception { // 生成一個可信任的隨機數源 SecureRandom sr = new SecureRandom(); // 從原始密鑰數據創建DESKeySpec對象 DESKeySpec dks = new DESKeySpec(key); // 創建一個密鑰工廠,然後用它把DESKeySpec轉換成SecretKey對象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher對象實際完成解密操作 Cipher cipher = Cipher.getInstance(DES); // 用密鑰初始化Cipher對象 cipher.init(Cipher.DECRYPT_MODE, securekey, sr); return cipher.doFinal(data); } public static void main(String[] args) { String data = "123@!456wudafa"; String key = "aaasfcaad"; System.out.println("加密前===>" + data); try { String encrypt = encrypt(data, key); System.err.println("加密後: " + encrypt(data, key)); System.err.println("解密後: " + decrypt(encrypt, key)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

字符串加密解密