Java Tutorial/Security/Digest Stream — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 05:01, 1 июня 2010

Create a checksum

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
public class Main {
  public static void main(String args[]) throws Exception {
    InputStream fis = new FileInputStream("a.exe");
    byte[] buffer = new byte[1024];
    MessageDigest complete = MessageDigest.getInstance("MD5");
    int numRead;
    do {
      numRead = fis.read(buffer);
      if (numRead > 0) {
        complete.update(buffer, 0, numRead);
      }
    } while (numRead != -1);
    fis.close();
    
    byte[] b = complete.digest();
    String result = "";
    for (int i = 0; i < b.length; i++) {
      result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
    }
    System.out.println(result);
  }
}





Cryptography Streams: True Mirror

import java.io.InputStream;
import java.net.URL;
import java.security.MessageDigest;
public class Main {
  public static void main(String[] args) throws Exception {
    URL source = new URL("http://www.a.ru");
    URL mirror = new URL("http://www.b.ru");
    byte[] sourceDigest = getDigestFromURL(source);
    byte[] mirrorDigest = getDigestFromURL(mirror);
    if (MessageDigest.isEqual(sourceDigest, mirrorDigest)) {
      System.out.println(mirror + " is up to date");
    } else {
      System.out.println(mirror + " needs to be updated");
    }
  }
  public static byte[] getDigestFromURL(URL u) throws Exception {
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    InputStream in = u.openStream();
    byte[] data = new byte[1024];
    int bytesRead = -1;
    while ((bytesRead = in.read(data)) >= 0) {
      md5.update(data, 0, bytesRead);
    }
    return md5.digest();
  }
}





Using DigestInputStream

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
public class MainClass {
  public static void main(String args[]) throws Exception {
    FileInputStream fis = new FileInputStream("test");
    MessageDigest md = MessageDigest.getInstance("SHA");
    DigestInputStream dis = new DigestInputStream(fis, md);
    ObjectInputStream ois = new ObjectInputStream(dis);
    Object o = ois.readObject();
    if (!(o instanceof String)) {
      System.out.println("Unexpected data in file");
      System.exit(-1);
    }
    String data = (String) o;
    System.out.println("Got message " + data);
    dis.on(false);
    o = ois.readObject();
    if (!(o instanceof byte[])) {
      System.out.println("Unexpected data in file");
      System.exit(-1);
    }
    byte origDigest[] = (byte[]) o;
    System.out.println(MessageDigest.isEqual(md.digest(), origDigest));
  }
}