美文网首页Android学习笔记
Java消息摘要: DigestOutputStream和Dig

Java消息摘要: DigestOutputStream和Dig

作者: 飞牛在天 | 来源:发表于2019-07-13 11:36 被阅读0次
    public static void main(String[] args) {
    
        new DigestOutputStreamDemo().test();
    }
    
    static class DigestOutputStreamDemo {
    
        public void test() {
            try {
    
                String sha = "SHA";
                String md5 = "MD5";
    
                FileInputStream fis = new FileInputStream("/Users/alan/digest/1.txt");
    
                FileOutputStream fos = new FileOutputStream("/Users/alan/digest/2.txt");
    
                MessageDigest digest = MessageDigest.getInstance(md5);
                DigestOutputStream dos = new DigestOutputStream(fos, digest);
                MessageDigest digest2 = MessageDigest.getInstance(md5);
                DigestInputStream dis = new DigestInputStream(fis, digest2);
    
    
                byte[] bytes = new byte[1024];
    
                int len = 0;
    
                while ((len = dis.read(bytes)) > 0) {
                    dos.write(bytes, 0, len);
                }
    
                fis.close();
    
                dos.flush();
                dos.close();
                printDigest(dos.getMessageDigest().digest());
                printDigest(dis.getMessageDigest().digest());
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void printDigest(byte[] digestBytes) {
    
        for (int i = 0; i < digestBytes.length; i++) {
            System.out.print(String.format("%02X:", digestBytes[i]));
        }
        System.out.println("");
    }

    相关文章

      网友评论

        本文标题:Java消息摘要: DigestOutputStream和Dig

        本文链接:https://www.haomeiwen.com/subject/csmpkctx.html