import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; import javax.crypto.spec.SecretKeySpec; public class CipherCode { private static CipherCode cipherCode; private Cipher cipher; private Key key; private boolean isEncrpts; private CipherCode() { isEncrpts = true; try { cipher = Cipher.getInstance("DES"); } catch (NoSuchAlgorithmException e) { cipherCode = null; e.printStackTrace(); } catch (NoSuchPaddingException e) { cipherCode = null; e.printStackTrace(); } } public static CipherCode getInstance() { if (cipherCode == null) { cipherCode = new CipherCode(); } return cipherCode; } public void setKey(String keyString) { byte[] keyData = keyString.getBytes(); key = new SecretKeySpec(keyData, 0, keyData.length, "DES"); } public String doFinal(String sourceString) throws InvalidKeyException, IllegalStateException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException { String cryptedString = null; if (isEncrpts) cipher.init(Cipher.ENCRYPT_MODE, key); else cipher.init(Cipher.DECRYPT_MODE, key); int cypheredBytes = 0; byte[] inputBytes = sourceString.getBytes("iso-8859-1"); byte[] outputBytes = new byte[256]; while (true) { try { cypheredBytes = cipher.doFinal(inputBytes, 0, inputBytes.length, outputBytes, 0); break; } catch (ShortBufferException e) { outputBytes = new byte[outputBytes.length * 2]; } } cryptedString = new String(outputBytes, 0, cypheredBytes, "iso-8859-1"); return cryptedString; } public void isEncrpts(boolean isEncrpts) { this.isEncrpts = isEncrpts; } } 使用的时候只要调用就行了,isEncrpts(true)为加密,isEncrpts(false)为解密。 还有一点非常重要,这个输出的字符串是iso8859-1编码,无法输出汉字,要再加转换。所以加密也不能是汉字。