Java DigestOutputStream getMessageDigest()方法及示例
java.security.DigestOutputStream 类的 getMessageDigest() 方法提供分配给这个DigestOutputStream对象的MessageDigest。
语法
public MessageDigest getMessageDigest()
返回值: 该方法返回分配给它的 MessageDigest对象 。
注意: 本文中的所有程序都不会在在线IDE上运行,因为没有’name’文件存在。你可以在你的系统的Java编译器上检查这段代码。为了检查这段代码,在你的系统上创建一个’name’文件。
下面是说明 getMessageDigest() 方法的例子。
例1 :
// Java program to demonstrate
// getMessageDigest() method
import java.security.*;
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] argv)
{
try {
// creating the object of MessageDigest
// and getting instance
// By using getInstance() method
MessageDigest sr
= MessageDigest.getInstance("MD5");
// creating and initializing
// object of OutputStream
OutputStream is
= new FileOutputStream("f:/java/name.txt");
// creating and initializing
// object of DigestOutputStream
DigestOutputStream di
= new DigestOutputStream(is, sr);
// getting the message digest
// using getMessageDigest() method
MessageDigest str
= di.getMessageDigest();
// display the result
System.out.println("Status : "
+ str.toString());
}
catch (NoSuchAlgorithmException e) {
System.out.println("Exception thrown : " + e);
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
catch (FileNotFoundException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出
Status : MD5 Message Digest from SUN,
例2 :
// Java program to demonstrate
// getMessageDigest() method
import java.security.*;
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] argv)
{
try {
// creating the object of MessageDigest
// and getting instance
// By using getInstance() method
MessageDigest sr
= MessageDigest.getInstance("SHA-1");
// creating and initializing
// object of OutputStream
OutputStream is
= new FileOutputStream("f:/java/name.txt");
// creating and initializing
// object of DigestOutputStream
DigestOutputStream di
= new DigestOutputStream(is, sr);
// getting the message digest
// using getMessageDigest() method
MessageDigest str
= di.getMessageDigest();
// display the result
System.out.println("Status : "
+ str.toString());
}
catch (NoSuchAlgorithmException e) {
System.out.println("Exception thrown : " + e);
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
catch (FileNotFoundException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出
Status : SHA-1 Message Digest from SUN,
参考资料: https://docs.oracle.com/javase/9/docs/api/java/security/DigestOutputStream.html#getMessageDigest-