欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA DES加密解密代码范例

程序员文章站 2022-03-12 20:57:09
...

测试通过:

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));
    }
}