AES/DES加密解密及設備唯一標識獲取

一、AES加密解密

公共變量:

   private static final String keyStr = "UITN25LMUQC436IM";

    private static final String AESTYPE = "AES/CBC/PKCS5Padding";

1,加密

   public static String AES_Encrypt(String plainText){
        byte[] encrypt = null;
        try{
            SecretKeySpec keySpec = new SecretKeySpec(keyStr.getBytes(), "AES");
            //Key key = generateKey(keyStr);
            IvParameterSpec iv = new IvParameterSpec(keyStr.getBytes("utf-8"));
            Key key = keySpec;
            Cipher cipher = Cipher.getInstance(AESTYPE);
            cipher.init(Cipher.ENCRYPT_MODE, key, iv);
            encrypt = cipher.doFinal(plainText.getBytes("utf-8"));
        }catch(Exception e){
            e.printStackTrace();
        }
        return android.util.Base64.encodeToString(encrypt, android.util.Base64.NO_WRAP);
    }

2,解密

    public static String AES_Decrypt(String encryptData){
        byte[] decrypt = null;
        try{
            SecretKeySpec keySpec = new SecretKeySpec(keyStr.getBytes(), "AES");
            //Key key = generateKey(keyStr);
            IvParameterSpec iv = new IvParameterSpec(keyStr.getBytes("utf-8"));
            Key key = keySpec;
            Cipher cipher = Cipher.getInstance(AESTYPE);
            cipher.init(Cipher.DECRYPT_MODE, key, iv);
            decrypt = cipher.doFinal(android.util.Base64.decode(encryptData.getBytes(), android.util.Base64.NO_WRAP));
        }catch(Exception e){
            e.printStackTrace();
            return "";
        }
        return new String(decrypt).trim();
    }

二、DES加密解密

1,CBC模式

    private static byte[] iv = {1, 2, 3, 4, 5, 6, 7, 8};

    public static String encryptDES(String encryptString, String encryptKey) throws Exception {
//      IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);
        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);
        byte[] encryptedData = cipher.doFinal(encryptString.getBytes());

        return Base64Util.encode(encryptedData);
    }

    public static String decryptDES(String decryptString, String decryptKey) throws Exception {
        byte[] byteMi = new Base64Util().decode(decryptString);
        IvParameterSpec zeroIv = new IvParameterSpec(iv);
//      IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);
        SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
        byte decryptedData[] = cipher.doFinal(byteMi);

        return new String(decryptedData);
    }

2,ECB模式

  public static final String ALGORITHM_DES = "DES/ECB/PKCS5Padding";

    /**
     * 加密
     *
     * @param data 待加密字符串
     * @param key  加密私鑰,長度不能夠小於8位
     * @return 加密後的字節數組,一般結合Base64編碼使用
     * @throws Exception 異常
     */

    public static String encode(String key, String data) throws Exception {
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // key的長度不能夠小於8位字節
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] bytes = cipher.doFinal(data.getBytes());
            return Base64.encodeToString(bytes, 3);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }


    /**
     * 解密
     *
     * @param data 待解密字符串
     * @param key  解密私鑰,長度不能夠小於8位
     * @return 解密後的字節數組
     * @throws Exception 異常
     */

    public static byte[] decode(String key, byte[] data) throws Exception {
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // key的長度不能夠小於8位字節
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return cipher.doFinal(data);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }


    /**
     * 獲取編碼後的值
     *
     * @param key
     * @param data
     * @return
     * @throws Exception
     */

    public static String decodeValue(String key, String data) {
        byte[] datas;
        String value = null;
        try {
            if (System.getProperty("os.name") != null
                    && (System.getProperty("os.name").equalsIgnoreCase("sunos") || System
                    .getProperty("os.name").equalsIgnoreCase("linux"))) {
                datas = decode(key, Base64.decode(data, 3));
            } else {
                datas = decode(key, Base64.decode(data, 3));
            }
            value = new String(datas);
        } catch (Exception e) {
            value = "";
        }
        return value;
    }

三、加密解密校驗

加密解密代碼:

        String key = "MNOojhxv";//key保持加密解密一致就好
        String text = "12345678";

        try {
            String result1 = DesUtil.encryptDES(text, key);
            String result2 = DesUtil.decryptDES(result1, key);
            Log.i("DES encode text is ", result1);
            Log.i("DES encode text is ", result2);

            String result3 = AesUtil.AES_Encrypt(text);
            String result4 = AesUtil.AES_Decrypt(result3);
            Log.i("AES encode text is ", result3);
            Log.i("AES encode text is ", result4);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        //        測試(CBC模式的測試和ECB的一樣):
        try {
            //待加密內容url
            String str = "12345678";
            String pwdKey = "moshapp";
            String pwdKeyMD5 = "moshappMd5";
//            String pwdKeyMD5 = MD5Util.encode(pwdKey);
//            System.out.println("pwdKeyMD5:" + pwdKeyMD5);
            String encodeStr = DesUtil.encode(pwdKeyMD5, str);
            String decodeStr = DesUtil.decodeValue(pwdKeyMD5, encodeStr);
            System.out.println("加密前的字符串:" + str);
            System.out.println("加密後的字符串:" + encodeStr);
            System.out.println("解密後的字符串:" + decodeStr);
            // URL轉義
            final String encodedURL = URLEncoder.encode(encodeStr, "UTF-8");
            // URL urlStr = new URL(encodedURL);
            System.out.println("轉義後的字符串:" + encodedURL);
        } catch (Exception e) {
            e.printStackTrace();
        }

結果輸出:


四、設備唯一標識獲取

獲取IMEI:

    /**
     * 獲得手機的IMEI
     */
    private static String getPhoneImei(Context con) {
        TelephonyManager tm = (TelephonyManager) con
                .getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getDeviceId();
    }

存在有些Android手機獲取不成功,在轉換獲取Mac地址:

    private static String getLocalMacAddress(Context con) {
        WifiManager wifi = (WifiManager) con.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        Debug.e("", "info.getMacAddress()=" + info.getMacAddress());
        return info.getMacAddress();
    }

以上獲取Mac地址,在Android6.0及以上版本有可能獲取默認值:02:00:00:00:00:00。

增強使用以下方法:

    public static String getMacAddress(Context context) {
        String macAddress = null;
        try {
            String wifiInterfaceName = "wlan0";
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface iF = interfaces.nextElement();
                if (iF.getName().equalsIgnoreCase(wifiInterfaceName)) {
                    byte[] addr = iF.getHardwareAddress();
                    if (addr == null || addr.length == 0) {
                        return null;
                    }

                    StringBuilder buf = new StringBuilder();
                    for (byte b : addr) {
                        buf.append(String.format("%02X:", b));
                    }
                    if (buf.length() > 0) {
                        buf.deleteCharAt(buf.length() - 1);
                    }
                    macAddress = buf.toString();
                    break;
                }
            }
        } catch (SocketException se) {
            macAddress = null;
        }

        if (TextUtils.isEmpty(macAddress)) {
            android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            macAddress = wifi.getConnectionInfo().getMacAddress();
        }

        return macAddress;
    }

傳送門



苦難與挫折只是個軀殼,真正廣闊的生活好處在於咱們對生活理想所持的生生不息的虔誠與熱情中所體現的堅強的信念——“堅信自我能飛!”

發佈了121 篇原創文章 · 獲贊 32 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章