AES/DES加密解密及设备唯一标识获取

来源:互联网 发布:nx飞行战记 知乎 编辑:程序博客网 时间:2024/06/07 04:52

一、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;    }

传送门



苦难与挫折只是个躯壳,真正广阔的生活好处在于咱们对生活理想所持的生生不息的虔诚与热情中所体现的坚强的信念——“坚信自我能飞!”

原创粉丝点击