加密算法的 Java 使用方法:MD5,SHA1,AES,RSA

 

一、摘要算法

MD5

public static String getmd5(String path) {
    String pathName = path;
    String md5 = "";

    try {
        // 读入文件
        File file = new File(pathName);
        FileInputStream ins = new FileInputStream(file);
        FileChannel ch = ins.getChannel();
        MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
        MessageDigest md = MessageDigest.getInstance("MD5");
        // 使用指定的 byteBuffer 更新摘要
        md.update(byteBuffer);
        ins.close();

        // 转换成 32 位的 16 进制字符串
        md5 = toHexString(md.digest());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return md5;
}

final static char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

/**
 * 转换成 32 位的 16 进制字符串
 *
 * @param tmp
 * @return
 */
public static String toHexString(byte[] tmp) {
    String s;
    char str[] = new char[tmp.length * 2];
    int k = 0;
    for (int i = 0; i < tmp.length; i++) {
        byte byte0 = tmp[i];
        str[k++] = hex[byte0 >>> 4 & 0xf];
        str[k++] = hex[byte0 & 0xf];
    }
    s = new String(str);

    return s;
}

SHA1

/**
 * SHA1
 *
 * @param path
 * @return
 */
public static String getsha1(String path) {
    String pathName = path;
    String sha1 = "";

    try {
        File file = new File(pathName);
        FileInputStream ins = new FileInputStream(file);
        FileChannel ch = ins.getChannel();

        MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());

        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        sha.update(byteBuffer);
        ins.close();
        sha1 = Encryption.toHexString(sha.digest());

    } catch (Exception e) {
        e.printStackTrace();
    }

    return sha1;
}

二、对称加密算法

/**
 * AES 加密
 *
 * @param str
 * @param key
 * @return
 */
public static byte[] aesEncrypt(String str, String key) throws Exception {
    if (str == null || key == null) {
        return null;
    }
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
    byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));

    return bytes;
}

/**
 * AES 解密
 *
 * @param bytes
 * @param key
 * @return
 * @throws Exception
 */
public static String aesDecrypt(byte[] bytes, String key) throws Exception {
    if (bytes == null || key == null) {
        return null;
    }
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
    bytes = cipher.doFinal(bytes);

    return new String(bytes, "utf-8");
}

三、非对称加密

RSA

posted @ 2019-08-20 15:20  duniqb  阅读(419)  评论(0编辑  收藏  举报