几种常用的加密方法

public static void main(String[] args) throws Exception {
        String md5Str = encodeToMD532("hello word");
        //32位,小写
        String md532Lower = md5Str.toLowerCase();
        //32位,大写
        String md532Upper = md532Lower.toUpperCase();
        //16位,小写
        String md516Lower = md532Lower.substring(8, 24);
        //16位,大写
        String md516Upper = md532Lower.substring(8, 24).toUpperCase();
    }

    private static String encodeToMD532(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(text.getBytes());
            byte[] digest = md.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private static String encodeSHA256(String msg) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-256");
            byte[] digest = md.digest(msg.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                hexString.append(String.format("%02x", b));
            }
            return hexString.toString();
        } catch (Exception e) {
            // 处理算法不可用的情况
            throw new RuntimeException(e);
        }
    }

  private static String encodeBase64(String msg) {
        return Base64.getEncoder().encodeToString(msg.getBytes());
    }
posted @ 2023-12-27 17:03  Dyaqi  阅读(17)  评论(0编辑  收藏  举报