您当前的位置: 首页 >  Java

柳鲲鹏

暂无认证

  • 0浏览

    0关注

    4642博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

JAVA DES加密解密代码范例

柳鲲鹏 发布时间:2021-09-22 13:43:36 ,浏览量:0

测试通过:

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

关注
打赏
1665724893
查看更多评论
立即登录/注册

微信扫码登录

0.0482s