JAVA DES加密解密代码范例
Posted 柳鲲鹏
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA DES加密解密代码范例相关的知识,希望对你有一定的参考价值。
测试通过:
package tsoffice;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public final class TestDes {
private static final String CHARSET = "utf-8";
private static final String ALGORITHM = "DES";
private static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";
private static Cipher getCipher() throws NoSuchPaddingException, NoSuchAlgorithmException
{
return Cipher.getInstance(CIPHER_ALGORITHM);
}
public static byte[] encrypt(String content, String key)
{
try
{
Cipher cipher = getCipher();
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));
byte[] byteContent = content.getBytes(CHARSET);
return cipher.doFinal(byteContent);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
public static String decrypt(byte[] content, String key)
{
try
{
Cipher cipher = getCipher();
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
byte[] result = cipher.doFinal(content);
return new String(result, CHARSET);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
private static Key getSecretKey(final String password)
{
try
{
DESKeySpec dks = new DESKeySpec(password.getBytes(CHARSET));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
return keyFactory.generateSecret(dks);
}
catch (Exception e)
{
return null;
}
}
public static void main(String[] args)
{
String content = "泰山Office";
String key = "quantum6";
System.out.println("content:" + content);
byte[] s1 = encrypt(content, key);
//输出为乱码,不必理会。
System.out.println("encrypted:" + new String(s1));
System.out.println("decrypted:" + decrypt(s1, key));
}
}
以上是关于JAVA DES加密解密代码范例的主要内容,如果未能解决你的问题,请参考以下文章