Java Tutorial/Security/SHA1 Secure Hash Algorithm
Содержание
Basic IO example using SHA1
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.security.DigestInputStream;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
public class MainClass {
public static void main(String[] args) throws Exception {
byte[] input = "1234567".getBytes();
MessageDigest hash = MessageDigest.getInstance("SHA1");
ByteArrayInputStream bIn = new ByteArrayInputStream(input);
DigestInputStream dIn = new DigestInputStream(bIn, hash);
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
int ch;
while ((ch = dIn.read()) >= 0) {
bOut.write(ch);
}
byte[] newInput = bOut.toByteArray();
System.out.println("in digest : " + new String(dIn.getMessageDigest().digest()));
DigestOutputStream dOut = new DigestOutputStream( new ByteArrayOutputStream(), hash);
dOut.write(newInput);
dOut.close();
System.out.println("out digest: " + new String(dOut.getMessageDigest().digest()));
}
}
Encrypt a password
public class Main {
public static void main(String arg[]) throws Exception {
System.out.println(encrypt("String"));
}
public static byte[] encrypt(String x) throws Exception {
java.security.MessageDigest d = null;
d = java.security.MessageDigest.getInstance("SHA-1");
d.reset();
d.update(x.getBytes());
return d.digest();
}
}
PSS parameter recovery and encoding
import java.security.AlgorithmParameters;
import java.security.Security;
import java.security.Signature;
import java.security.spec.PSSParameterSpec;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.util.ASN1Dump;
public class MainClass {
public static void main(String[] args) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Signature signature = Signature.getInstance("SHA1withRSAandMGF1", "BC");
signature.setParameter(PSSParameterSpec.DEFAULT);
AlgorithmParameters params = signature.getParameters();
ASN1InputStream aIn = new ASN1InputStream(params.getEncoded("ASN.1"));
System.out.println(ASN1Dump.dumpAsString(aIn.readObject()));
}
}
Use SHA1
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
public class MainClass {
private static int BUFFER_SIZE = 32 * 1024;
public static void main(String[] args) throws Exception {
System.out.println("test.txt: " + md("test.txt"));
}
public static String md(String f) throws Exception {
BufferedInputStream file = new BufferedInputStream(new FileInputStream(f));
MessageDigest md = MessageDigest.getInstance("SHA-1");
DigestInputStream in = new DigestInputStream(file, md);
int i;
byte[] buffer = new byte[BUFFER_SIZE];
do {
i = in.read(buffer, 0, BUFFER_SIZE);
} while (i == BUFFER_SIZE);
md = in.getMessageDigest();
in.close();
return new String(md.digest());
}
}