Java消息摘要: DigestOutputStream和DigestInputStream

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和DigestInputStream)