下面是代码的实现:
package com.smt.cipher.symmetry;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
/**
* DES 工具
* @author ZHANGYUKUN
*
*/
public class AESUtil {
public static final String ENCODING = Charset.defaultCharset().name();
/**
* 加密
* @param data 原文
* @param cipherStr 秘钥字符字符串(8的倍数)
* @return
*/
public static String encrypt( String content , String secretkeyStr ) {
String rt = null;
try {
byte[] data = getDESCipher(secretkeyStr, Cipher.ENCRYPT_MODE ).doFinal( content.getBytes(ENCODING) );
rt = new String(Base64.getEncoder().encode(data), ENCODING);
} catch (Exception e) {
e.printStackTrace();
}
return rt;
}
/**
* 解密
* @param data 解密
* @param cipherStr 秘钥字符串(8的倍数)
* @return
*/
public static String descrypt(String data , String secretkeyStr) {
String rt = null;
try {
byte[] cipher = getDESCipher(secretkeyStr, Cipher.DECRYPT_MODE ).doFinal( Base64.getDecoder().decode( data.getBytes() ) );
rt = new String( cipher,ENCODING );
} catch (Exception e) {
e.printStackTrace();
}
return rt;
}
/**
* 得到密码
* @param secretkeyStr
* @param mode
* @return
*/
public static Cipher getDESCipher( String secretkeyStr,int mode ) {
int remainder = secretkeyStr.length()%8;
if( remainder != 0 ) {
throw new RuntimeException("秘钥字符串必须是8的倍数");
}
try {
KeyGenerator keygen =KeyGenerator.getInstance("AES");
keygen.init(128, new SecureRandom(secretkeyStr.getBytes(ENCODING)));
SecretKey secretKey=keygen.generateKey();
Cipher cipher = Cipher.getInstance("AES");
cipher.init( mode , secretKey );
return cipher;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
测试代码:
package com.smt.cipher;
import java.security.NoSuchAlgorithmException;
import com.smt.cipher.symmetry.DESUtil;
public class Main2 {
public static void main(String[] args) throws NoSuchAlgorithmException {
System.out.println( DESUtil.encrypt("测试文本DES", "abcdabcd" ) );
System.out.println( DESUtil.descrypt( DESUtil.encrypt("测试文本DES", "abcdabcd" ) , "abcdabcd"));
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
输出结果:
代码git 下载地址:https://github.com/hualiuwuxin/tools.git