加密步骤:
  • 编写extractSalt()方法,该方法可生成返回一个随机盐值.
  • 编写生成MD5摘要方法:getMd5Hex(String
    str),参数为String,返回32位hex字符串.该方法需导入jar包:commons-codec-1.10.jar.
  • 编写密码生成方法:generateKeywordText(String pwd,String
    salt),在generateKeywordText()方法中,获得getMd5Hex(salt+pwd)返回之字符串hexs,新建48位char数组cs,通过for循环,分别截取hexs和salt自定义规律位置之单字符,然后一一赋予cs,将cs转为字符串os,os即为最终密码原文.
解密步骤
  • 编写方法verify(String pass,String origin);
  • verify()方法内,分别新建digestChar字符数组[32]和saltChar字符数组[16],使用for循环,按照之前自定义的位置规律,从origin逆向截取单个字符,赋予digestChar[]和saltChar[],将saltChar[]转为字符串salt.
  • 最后利用getMd5Hex(salt+pass)返还的hexString,与new String(digestChar)相比较即可.
Java代码
  /**
     * 提取盐
     *
     * @return
     */
    public String extractSalt() {
        Random random = new Random();
        StringBuilder builder = new StringBuilder(16);
        builder.append(random.nextInt(99999999));

        int length = builder.length();

        if (length < 16) {
            for (int i = 0; i < 16 - length; i++) {
                int n = random.nextInt(9);
                builder.append(n + "");
            }
        }

        return builder.toString();
    }

    /**
     * 获取十六进制字符串形式的MD5摘要(digest)
     *
     * @param src
     * @return
     */
    private String getMd5Hex(String src) {
        MessageDigest md5 = null;

        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        byte[] bs = md5.digest(src.getBytes());

        byte[] encode = new Hex().encode(bs);

        return new String(encode);

    }

    /**
     * 代入页面提交的原始密码,生成并返回密文
     * 
     * @param pwd 原始素材
     * @param salt
     * @return
     */
    public String generateKeywordText(String pwd, String salt) {
        // 撒盐,并在MD5hex方法内均匀搅拌
        String hex = getMd5Hex(salt + pwd);

        char[] cs = new char[48];
        // 再加密
        for (int i = 0; i < 48; i += 3) {
            cs[i] = hex.charAt(i / 3 * 2);
            cs[i + 1] = salt.charAt(i / 3);
            cs[i + 2] = hex.charAt(i / 3 * 2 + 1);
        }
        
        return new String(cs);

    }

    /**
     * 校验加盐后是否和原文一致,逆向解密
     *
     * @param password
     *            提交之密码
     * @param text
     *            原文
     * @return
     */
    public boolean verify(String password, String text) {
        char[] digestStr = new char[32];
        char[] saltStr = new char[16];

        for (int i = 0; i < 48; i += 3) {
            digestStr[i / 3 * 2] = text.charAt(i);
            digestStr[i / 3 * 2 + 1] = text.charAt(i + 2);

            saltStr[i / 3] = text.charAt(i + 1);
        }

        String salt = new String(saltStr);
        
        boolean b = getMd5Hex(salt + password).equals(new String(digestStr));
        
        return b;
        
    }

DEFAULT
19 声望2 粉丝