SHA256Utils

SHA256Utils

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

public class SHA256Utils {
    private static final Logger LOG = LoggerFactory.getLogger(SHA256Utils.class);
    /***
     * 利用Apache的工具类实现SHA-256加密
     *
     * @param str 加密后的报文
     * @return
     */
    public static String sha256(String str) {
        MessageDigest messageDigest;
        String encdeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
            encdeStr = Hex.encodeHexString(hash);
        } catch (Exception e) {
            LOG.error("getSHA256Str has error:", e);
            return str;
        }
        return encdeStr;
    }
    /**
     * 密码加盐加密
     *
     * @param password
     * @param salt
     * @return
     */
    public static String encryptPassword(String password, String salt) {
        return sha256(sha256(password) + salt);
    }

    public static void main(String[] args) {
        String abc123 = encryptPassword("abc123", "standard-module-account");
        System.out.println(abc123);
    }

}

6位随机验证码:

public static String genMsgCode() {
        return String.valueOf((int) (((Math.random() * 9) + 1) * 100000));
    }

编码方法:base64 可逆

public static void main(String[] args) {
        // 加密
        java.lang.String str = "我爱java";
        byte[] bytes = Base64.encodeBase64(str.getBytes(), true);
        System.out.println(new java.lang.String(bytes)); // 5oiR54ixamF2YQ==

        System.out.println("------------------------------");

        // 解密
        String string = "5oiR54ixamF2YQ==";
        byte[] bytes1 = Base64.decodeBase64(string.getBytes());
        System.out.println(new java.lang.String(bytes1));
    }

你可能感兴趣的:(SHA256Utils)