Java将文件经过MD5加密后转为base64码(转码后首字母为0解决)

先说注意点,再看代码。

attention:

后面这个转码真的是花了我整整2天的时间。

第一:一定要穿文件到方法里面,不能直接流化后过去,这个地方也是卡死元凶,导致我后面结果死都不对。

第二:while 读文件的地方,代码我标红了,百度到的那个地方都是直接read.(buffer),亲测不行。

第三:MD5加密后一定要转为十六进制之后再进行base64

1.将文件转为base64码

    public static String fileToBase64(File file) {
        String base64 = null;
        InputStream in = null;
        try {
            //将文件流化file.getInputStream()
            in = new FileInputStream(file);
            byte[] bytes = new byte[(int)file.getSize()];
            int length = in.read(bytes);
            in.close();
            return new BASE64Encoder().encode(bytes );
        } catch (Exception e) {
            return null;
        }  
    }

2.经过MD5加密后转为base64码

public static String getMD5Three(File file) {
 2         BigInteger bi = null;

           MessageDigest  digest ;
 3         try {
 4             byte[] buffer = new byte[1024];
 5             int len = 0;
               InputStream fis= new FileInputStream(file);  
 6             MessageDigest md = MessageDigest.getInstance("MD5");
 7            
 9             while ((len = fis.read(buffer,0,1024)) != -1) {
10                 md.update(buffer, 0, len);
11             }
12             fis.close();
13             byte[] b = md.digest();
14             bi = new BigInteger(1, b);
15         }  catch (Exception e) {
18             e.printStackTrace();
19         }
           String string = byteToHex(digest.digest()).toUpperCase();
           BASE64Encoder base64Encoder = new BASE64Encoder();
20         return base64Encoder.encode(string.getBytes());
21     }

 

/**
* byte数据装维十六进制字符串格式(解决转皇后首位数据0缺失的问题)
*/

private static String byteToHex(final byte[] hash){
    Formatter fm = new Formatter ();
    for (byte b :hash){
        fm.format("%O2x",b);
    }
    String result = fm.toString();
    fm.close();
    return result;
}
    


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值