DES加密解密

1.DES加密

说明:加密key和解密key一直

 public static String desEncript(String clearText, String originKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
        Cipher cipher=Cipher.getInstance("DES/ECB/PKCS5Padding"); /*提供加密的方式:DES*/
        SecretKeySpec key=getKey1(originKey);  /*对密钥进行操作,产生16个48位长的子密钥*/
        cipher.init(Cipher.ENCRYPT_MODE,key); /*初始化cipher,选定模式,这里为加密模式,并同时传入密钥*/
        byte[] doFinal=cipher.doFinal(clearText.getBytes("UTF-8"));   /*开始加密操作*/
        String encode= Base64.encodeBase64String(doFinal);   /*对加密后的数据按照Base64进行编码*/
        return encode;
    }


2.DES解密

 public static String desDecript(String cipherText, String originKey) throws BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        Cipher cipher=Cipher.getInstance("DES/ECB/PKCS5Padding");   /*初始化加密方式*/
        Key key=getKey1(originKey);  /*获取密钥*/
        cipher.init(Cipher.DECRYPT_MODE,key);  /*初始化操作方式*/
        byte[] decode= org.apache.commons.codec.binary.Base64.decodeBase64(cipherText); /*按照Base64解码*/
        byte[] doFinal=cipher.doFinal(decode);   /*执行解码操作*/
        return new String(doFinal);   /*转换成相应字符串并返回*/
    }
    private static SecretKeySpec getKey1(String originKey) throws UnsupportedEncodingException {
        byte[] buffer=new byte[8];
        byte[] originBytes=originKey.getBytes("UTF-8");
        /**
         * 防止输入的密钥长度超过64位
         */
        for(int i=0;i<8&&i<originBytes.length;i++)
        {
            buffer[i]=originBytes[i];  /*如果originBytes不足8,buffer剩余的补零*/
        }
        SecretKeySpec key=new SecretKeySpec(buffer,"DES"); /*第一个参数是密钥字节数组,第二个参数是加密方式*/
        return key;  /*返回操作之后得到的密钥*/
    }

3.测试

 public static void main(String[] args) throws BadPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {

        String data = "ipDlOxyvlJVivYmdzSfEAaIiZNVc9z0SBhvUZf8mvMoMp6iY+z83qM/iPZQNh6QRYiRVzqHhvX+RLWbseKuUHWqyxPYD4INtfSv8F0PXiB557IgrvoJSOYBZevc3GqzsHxzmpintxncFqhfnzBHnGu4z8M7lVwf4/0LVg0Gv+huiwp6PgYXiphcG21o/ljtJpHX8EC1wuH7cpOHWdrBjkY6j1Nbtmv0kOoUANJTnLfuk4rPjICmLKQ5cIosYmg5+XGYe//iCoqdsHKAL+RjE/JmU03uWKJmgz+I9lA2HpBFuOKGAOdRjcQ==";
        String key = "59750e50-f2de-43bc-8322-f10d1ec52eed";
       String str =  desDecript(data,key);
        System.out.println(str);

    }
posted @ 2021-06-25 09:16  风飘落叶  阅读(240)  评论(0编辑  收藏  举报