美文网首页
java进行DES加密

java进行DES加密

作者: 大橙子0717 | 来源:发表于2019-06-14 09:30 被阅读0次
    package com.icbc.api.test;
    
    import javax.crypto.Cipher;
    import javax.crypto.spec.SecretKeySpec;
    import java.security.Key;
    
    /**
     * 描述:3des加密
     *
     * @author wangcheng
     * @create 2019-06-13-16:20
     */
    public class TDESDemo {
        public static String tdes_key="cputest";
        public static void main(String[] args) throws Exception {
            String[] args1 = new String[1];
            args1[0] = "123";
            System.out.println(des_encode(args1));
            String[] args2 = new String[1];
            args2[0] = des_encode(args1);
            System.out.println(des_decode(args2));
        }
        public static String des_encode(String[] args) throws Exception {
            String des_key = tdes_key;
            Key key = Get3DESKey(des_key.getBytes());
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(1, key);
            return byteArr2HexStr(cipher.doFinal(args[0].getBytes()));
        }
        public static String des_decode( String[] args) throws Exception {
    
    
                String des_key = tdes_key;
                Key key = Get3DESKey(des_key.getBytes());
    
                Cipher cipher = Cipher.getInstance("DES");
                cipher.init(2, key);
                return new String(cipher.doFinal(hexStr2ByteArr(args[0])));
    
        }
        private static Key Get3DESKey(byte[] key) throws Exception {
            byte[] tmpKey = new byte[8];
    
            for (int i = 0; (i < key.length) && (i < tmpKey.length); ++i) {
                tmpKey[i] = key[i];
            }
    
            SecretKeySpec secretKeySpec = new SecretKeySpec(tmpKey, "DES");
    
            return secretKeySpec;
        }
        public static String byteArr2HexStr(byte[] value) throws Exception {
            int i = value.length;
    
            StringBuffer buf = new StringBuffer(i * 2);
            for (int j = 0; j < i; ++j) {
                int k = value[j];
    
                while (k < 0) {
                    k += 256;
                }
    
                if (k < 16)
                    buf.append("0");
    
                buf.append(Integer.toString(k, 16));
            }
            return buf.toString();
        }
        public static byte[] hexStr2ByteArr(String value) throws Exception {
            byte[] bs1 = value.getBytes();
            int i = bs1.length;
    
            byte[] bs2 = new byte[i / 2];
            for (int j = 0; j < i; j += 2) {
                String str = new String(bs1, j, 2);
                bs2[(j / 2)] = (byte) Integer.parseInt(str, 16);
            }
            return bs2;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:java进行DES加密

          本文链接:https://www.haomeiwen.com/subject/igayfctx.html