Android 3DES加密

/** * 3DES加密解密工具类 * Created by 犀利的小牛 on 2016/7/29. */
public class DES3Util {
    // 密钥
    private final static String secretKey = "aaaaaaaaaaaaaaaaaaadaaaaa";
    // 向量
    private final static String iv = "999929999";
    // 加解密统一使用的编码方式
    private final static String encoding = "UTF-8";

    /** * 3DES加密并UrL转码 */
    public static String encode(String plainText) {
        try {
            SecretKey deskey = null;
            DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
            deskey = keyfactory.generateSecret(spec);

            Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
            IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
            byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
            return URLEncoder.encode(Base64.encode(encryptData), encoding);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /** * UrL解码并3DES解密 */
    public static String decode(String encryptText) {
     try {
            SecretKey deskey = null;
            DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
            deskey = keyfactory.generateSecret(spec);
            Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
            IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
            byte[] decryptData = cipher.doFinal(Base64.decode(URLDecoder.decode(encryptText, encoding)));

            return new String(decryptData, encoding);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

你可能感兴趣的:(android,加密,解密,3des)