java 代码
- public class CryptoUtils {
- private static final String KEY = "12345678123456781234567811111111";
- public static String encrypt(String strDataToEncrypt) {
- byte[] key = KEY.getBytes();
- Provider sunJCE = new com.sun.crypto.provider.SunJCE();
- Security.addProvider(sunJCE);
- String strAlgorithm = "DES";
- SecretKeySpec keySpec = null;
- DESKeySpec deskey = null;
- String strResult = "";
- try {
- deskey = new DESKeySpec(key);
- keySpec = new SecretKeySpec(deskey.getKey(), "DES");
- Cipher cipher = Cipher.getInstance(strAlgorithm);
- cipher.init(Cipher.ENCRYPT_MODE, keySpec);
- byte[] utf8 = strDataToEncrypt.getBytes("UTF8");
- byte[] enc = cipher.doFinal(utf8);
- strResult = new sun.misc.BASE64Encoder().encode(enc);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return strResult;
- }
- /**
- * This function decrypt a given string using the DES algorithm.
- * @param strDataToDecrypt The String to decrypt
- * @param strKey The generated key used to decrypt
- * @return The encrypted string
- */
- public static String decrypt(String strDataToDecrypt) {
- byte[] key = KEY.getBytes();
- Provider sunJCE = new com.sun.crypto.provider.SunJCE();
- Security.addProvider(sunJCE);
- String strAlgorithm = "DES";
- SecretKeySpec keySpec = null;
- DESKeySpec deskey = null;
- String strResult = "";
- try {
- deskey = new DESKeySpec(key);
- keySpec = new SecretKeySpec(deskey.getKey(), "DES");
- Cipher cipher = Cipher.getInstance(strAlgorithm);
- cipher.init(Cipher.DECRYPT_MODE, keySpec);
- byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(strDataToDecrypt);
- byte[] utf8 = cipher.doFinal(dec);
- return new String(utf8, "UTF8");
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- return strResult;
- }
- }