md5加密

MD5加密算法详解
本文详细介绍了如何使用MD5算法对文件和平文内容进行加密处理,并提供了具体的Java实现代码。文章包括了计算文件的MD5摘要码及平文字符串的MD5加密方法。
对文件进行加密:
/**
     * 计算文件的Md5
     * 
     * @param file
     * @return MD5摘要码
     */
    public static String calcMd5Checksum(File file) {
        FileInputStream fis = null;
        byte[] buffer = new byte[2048];
        int numRead = 0;
        
        try {
            fis = new FileInputStream(file);
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            while ((numRead = fis.read(buffer)) > 0) {
                algorithm.update(buffer, 0, numRead);
            }
            return toHexString(algorithm.digest(), "");
        } catch (NoSuchAlgorithmException e) {
            Log.w(TAG, "toMd5(): " + e);
            throw new RuntimeException(e);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                fis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }


private static String toHexString(byte[] bytes, String separator) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            hexString.append(Integer.toHexString(0xFF & b)).append(separator);
        }
        return hexString.toString();
    }


对PlainText加密:

public static String calcMd5Checksum(String plainText, int size) {
        return calcMd5Checksum(plainText).substring(0, size);
    }

/**
     * 计算Md5
     * 
     * @param plainText
     * @return
     */
    public static String calcMd5Checksum(String plainText) {
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(plainText.getBytes());
            return toHexString(algorithm.digest(), "");
        } catch (NoSuchAlgorithmException e) {
            Log.w(TAG, "toMd5(): " + e);
            throw new RuntimeException(e);
        }
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值