java DES ECB模式加解密

import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
/***
 * DES ECB PKCS5Padding 对称加密 解密
 */
public class DesECBUtil {
    /**
     * 加密数据
     * @param encryptString
     * @param encryptKey
     * @return
     * @throws Exception
     */

    public static String encryptDES(String encryptString, String encryptKey) throws Exception {
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(getKey(encryptKey), "DES"));
        byte[] encryptedData = cipher.doFinal(encryptString.getBytes("UTF-8"));
        return Base64.encodeBase64String(encryptedData);
    }

    /**
     * key 不足8位补位
     *
     * @param string
     */
    public static byte[] getKey(String keyRule) {
        Key key = null;
        byte[] keyByte = keyRule.getBytes();
// 创建一个空的八位数组,默认情况下为0
        byte[] byteTemp = new byte[8];
// 将用户指定的规则转换成八位数组
        for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {
            byteTemp[i] = keyByte[i];
        }
        key = new SecretKeySpec(byteTemp, "DES");
        return key.getEncoded();
    }

    /***
     * 解密数据
     * @param decryptString
     * @param decryptKey
     * @return
     * @throws Exception
     */

    public static String decryptDES(String decryptString, String decryptKey) throws Exception {
        byte[] sourceBytes = Base64.decodeBase64(decryptString);
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(getKey(decryptKey), "DES"));
        byte[] decoded = cipher.doFinal(sourceBytes);
        return new String(decoded, "UTF-8");
    }

    public static void main(String[] args) throws Exception {
        String clearText = "0";
        String key = "12345678";//密钥
        System.out.println("明文:" + clearText + "\n密钥:" + key);
        String encryptText = encryptDES(clearText, key);
        System.out.println("加密后:" + encryptText);
        String decryptText = decryptDES(encryptText, key);
        System.out.println("解密后:" + decryptText);
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值