zoukankan      html  css  js  c++  java
  • [Android Pro] DES加密 version1

    reference to : http://blog.csdn.net/wfung_kwok/article/details/7766029

    加密和解密要用同一個key

    AES:

    import java.util.UUID;
    
    import javax.crypto.Cipher;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    
    
    public class DES {
    
        private static final byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
    
        /**
         * 
         * @param encryptString 加密内容
         * @param encryptKey 加密key
         * @return
         * @throws Exception
         */
        public static String encryptDES(String encryptString, String encryptKey)
                throws Exception {
            IvParameterSpec zeroIv = new IvParameterSpec(iv);
            SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
            String tmp = Base64.encodeBytes(encryptString.getBytes("UTF-8"));
            byte[] encryptedData = cipher.doFinal(tmp.getBytes("UTF-8"));
            return Base64.encodeBytes(encryptedData);
        }
        
        /**
         * 
         * @param decryptString 解密内容
         * @param encryptKey 解密key
         * @return
         * @throws Exception
         */
        public static String decryptDES(String decryptString,String encryptKey)throws Exception {
            IvParameterSpec zeroIv = new IvParameterSpec(iv);
            SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
            byte[] decryptBytes = cipher.doFinal(Base64.decode(decryptString));
            String tmp = new String(decryptBytes,"UTF-8");
            return new String(Base64.decode(tmp));
        }
        
        public static String getKey(){
            String p = UUID.randomUUID().toString();
            return SHA1.Encrypt(p).substring(0, 8);
        }
        
    }

    Test:

    public static void testDES() throws Exception{
        
            String content = "AES加密";
            String key = DES.getKey();
            String a = DES.encryptDES(content, key);
            System.out.println("DES Encrypt..." + a);
            String b = DES.decryptDES(a, key);
            System.out.println("DES decrypt..." + b);
    }

    Console:

    DES Encrypt...93koM7boCXsNrH91Y0MDJA==
    DES decrypt...AES加密
  • 相关阅读:
    内置函数filter()和匿名函数lambda解析
    time&datetime模块详解
    python学习笔记:*args和**kwargs使用原理?
    python学习笔记:深浅拷贝的使用和原理
    python传参是传值还是传引用
    第215天:Angular---指令
    第214天:Angular 基础概念
    第213天:12个HTML和CSS必须知道的重点难点问题
    第212天:15种CSS居中的方式,最全了
    第211天:git和github的区别和使用详解
  • 原文地址:https://www.cnblogs.com/0616--ataozhijia/p/5253500.html
Copyright © 2011-2022 走看看