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
        {
            return new SecretKeySpec(password.getBytes(CHARSET), ALGORITHM);
        }
        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));
    }
}
 
上一篇:启明云端分享:可私人订制UI的86盒智能新型开关面板


下一篇:Kubernetesv1.20.5 集群搭建