对称加密-DES解密
生活随笔
收集整理的這篇文章主要介紹了
对称加密-DES解密
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
使用?ctrl + alt + m?快捷鍵抽取代碼
package com.leon.desaes;import com.sun.org.apache.xml.internal.security.utils.Base64;import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec;public class DesDemo {// DES加密算法,key的大小必須是8個字節(jié)public static void main(String[] args) throws Exception {String input ="深圳";// DES加密算法,key的大小必須是8個字節(jié)String key = "12345678";String transformation = "DES"; // 9PQXVUIhaaQ=// 指定獲取密鑰的算法String algorithm = "DES";String encryptDES = encryptDES(input, key, transformation, algorithm);System.out.println("加密:" + encryptDES);String s = decryptDES(encryptDES, key, transformation, algorithm);System.out.println("解密:" + s);}/*** 使用DES加密數(shù)據(jù)** @param input : 原文* @param key : 密鑰(DES,密鑰的長度必須是8個字節(jié))* @param transformation : 獲取Cipher對象的算法* @param algorithm : 獲取密鑰的算法* @return : 密文* @throws Exception*/private static String encryptDES(String input, String key, String transformation, String algorithm) throws Exception {// 獲取加密對象Cipher cipher = Cipher.getInstance(transformation);// 創(chuàng)建加密規(guī)則// 第一個參數(shù)key的字節(jié)// 第二個參數(shù)表示加密算法SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);// ENCRYPT_MODE:加密模式// DECRYPT_MODE: 解密模式// 初始化加密模式和算法cipher.init(Cipher.ENCRYPT_MODE,sks);// 加密byte[] bytes = cipher.doFinal(input.getBytes());// 輸出加密后的數(shù)據(jù)String encode = Base64.encode(bytes);return encode;}/*** 使用DES解密** @param input : 密文* @param key : 密鑰* @param transformation : 獲取Cipher對象的算法* @param algorithm : 獲取密鑰的算法* @throws Exception* @return: 原文*/private static String decryptDES(String input, String key, String transformation, String algorithm) throws Exception {// 1,獲取Cipher對象Cipher cipher = Cipher.getInstance(transformation);// 指定密鑰規(guī)則SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);cipher.init(Cipher.DECRYPT_MODE, sks);// 3. 解密,上面使用的base64編碼,下面直接用密文byte[] bytes = cipher.doFinal(Base64.decode(input));// 因為是明文,所以直接返回return new String(bytes);} }?
總結(jié)
以上是生活随笔為你收集整理的对称加密-DES解密的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 对称加密-DES加密
- 下一篇: base64核心原理