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加密
  • 相关阅读:
    (15)疯狂的程序员----《绝影》
    (14)嵌入式软件开发工程师技能要求总结
    (13)碎片化阅读只会让你变得越来越愚蠢
    (12)QT中搭建opencv开发环境
    (11)git服务器的安装和配置
    (10)python学习笔记一
    (3.3)狄泰软件学院C++课程学习剖析四
    (9)Linux下gdb调试学习
    (8)Linux(客户端)和Windows(服务端)下socket通信实例
    springMVC伪静态
  • 原文地址:https://www.cnblogs.com/0616--ataozhijia/p/5253500.html
Copyright © 2011-2022 走看看