• [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加密
  • 相关阅读:
    UVA-11437 Triangle Fun
    UVA 10491
    CF 223C
    poj 3273
    由异常掉电问题---谈xfs文件系统
    好久没有写博客了,最近一段时间做一下总结吧!
    Json.Net
    div 旋转
    VirtualBox虚拟机网络设置
    windows 2003 安装 MVC 环境 404错误,无法找到该页
  • 原文地址:https://www.cnblogs.com/0616--ataozhijia/p/5253500.html
Copyright © 2020-2023  润新知