DES是一种对称的加密方式,即需要相同的密钥进行加密解密。为了方便日后使用,此处将DES的加解密方法进行了封装,参数和返回值统一String数据类型。代码较为简单,不多解释,如有不对的地方,望多多指教。
package encrypt;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import org.apache.commons.codec.binary.Base64;
import java.security.Key;
import java.security.SecureRandom;
public class DESUtils {
private static Key key;
private static String KEY_STR = "aaaaaaaaaa"; //密钥
private static String CHARSET_NAME = "UTF-8"; //编码格式
private static String ALGORITHM = "DES";
//初始化
static {
try {
KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(KEY_STR.getBytes());
generator.init(secureRandom);
key = generator.generateKey();
generator = null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//输入原文加密,返回密文字符串
public static String getEncryptString(String str) {
Base64 base64encoder = new Base64();
try {
byte[] bytes = str.getBytes(CHARSET_NAME);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] doFinal = cipher.doFinal(bytes);
return base64encoder.encodeToString(doFinal);
} catch (Exception e) {
// TODO: handle exception
throw new RuntimeException(e);
}
}
//输入密文,解密的原文 字符串
public static String getDecryptString(String str) {
Base64 base64decoder = new Base64();
try {
byte[] bytes = base64decoder.decodeBase64(str);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] doFinal = cipher.doFinal(bytes);
return new String(doFinal, CHARSET_NAME);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
String password = "roodfdfddfdadfad大t";
System.out.println("===明文===:"+password);
String password_Encrypt = getEncryptString(password);
System.out.print("===密文===:"+password_Encrypt);
String password_decrypt = getDecryptString(password_Encrypt);
System.out.println("===原文===:"+password_decrypt);
}
}
测试如下: