Skip to content

Instantly share code, notes, and snippets.

@kaka2008
Last active August 29, 2015 14:05
Show Gist options
  • Save kaka2008/f663646cb0eed9ed29ce to your computer and use it in GitHub Desktop.
Save kaka2008/f663646cb0eed9ed29ce to your computer and use it in GitHub Desktop.
Java方式des-ecb加密和解密
// des-ecb方式加密解密的key
public static final String DES_ECB_KEY = "01234567";
/**
* 采用DES-ECB方式加密
*
* @param text
* @return
*/
public static String encryptText(String text) {
byte[] key = DES_ECB_KEY.getBytes();
byte[] plainText = text.getBytes();
SecretKey secretKey = new SecretKeySpec(key, "DES");
// encrypt
Cipher cipher = null;
try {
cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
try {
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
byte[] encryptedData = null;
try {
encryptedData = cipher.doFinal(plainText);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return Hex.encodeHexString(encryptedData);
}
/**
* 采用DES-ECB方式解密
*
* @param text
* @return
*/
public static String decryptText(String text) {
byte[] key = DES_ECB_KEY.getBytes();
SecretKey secretKey = new SecretKeySpec(key, "DES");
// encrypt
Cipher cipher = null;
try {
cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
// decrypt
try {
cipher.init(Cipher.DECRYPT_MODE, secretKey);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
byte[] decryptPlainText = null;
try {
decryptPlainText = cipher
.doFinal(Hex.decodeHex(text.toCharArray()));
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (DecoderException e) {
e.printStackTrace();
}
return new String(decryptPlainText);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment