Android

来源:互联网 发布:怎么找放单的淘宝商家 编辑:程序博客网 时间:2024/05/23 23:18

1.字符串的加密

    /**     * 加密     **/    private String encryptPassword(String clearText) {        try {            DESKeySpec keySpec = new DESKeySpec(                    MyConstant.PASSWORD_ENC_SECRET.getBytes("UTF-8"));            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");            SecretKey key = keyFactory.generateSecret(keySpec);            Cipher cipher = Cipher.getInstance("DES");            cipher.init(Cipher.ENCRYPT_MODE, key);            String encrypedPwd = Base64.encodeToString(cipher.doFinal(clearText                    .getBytes("UTF-8")), Base64.DEFAULT);            return encrypedPwd;        } catch (Exception e) {        }        return clearText;    }

2.字符串的解密

    /**     * 解密     **/    private String decryptPassword(String encryptedPwd) {        try {            DESKeySpec keySpec = new DESKeySpec(MyConstant.PASSWORD_ENC_SECRET.getBytes("UTF-8"));            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");            SecretKey key = keyFactory.generateSecret(keySpec);            byte[] encryptedWithoutB64 = Base64.decode(encryptedPwd, Base64.DEFAULT);            Cipher cipher = Cipher.getInstance("DES");            cipher.init(Cipher.DECRYPT_MODE, key);            byte[] plainTextPwdBytes = cipher.doFinal(encryptedWithoutB64);            return new String(plainTextPwdBytes);        } catch (Exception e) {        }        return encryptedPwd;    }

备注:常量PASSWORD_ENC_SECRET可自行定义。

public class MyConstant {    public static final String PASSWORD_ENC_SECRET = "mythmayor";}

3.下载Demo

字符串加密和解密Demo下载

原创粉丝点击