下面列出了怎么用java.security.DigestOutputStream的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* java.io.DigestOutputStream#write(byte[], int, int)
*/
public void test_write$BII_7()
throws IOException, NoSuchAlgorithmException {
Support_OutputStream sos = new Support_OutputStream(MY_MESSAGE_LEN);
MessageDigest md = MessageDigest.getInstance(algorithmName[0]);
DigestOutputStream dos = new DigestOutputStream(sos, md);
dos.write(myMessage, 0, MY_MESSAGE_LEN);
try {
// Support_OutputStream throws an IOException if the internal
// buffer is full, which it should be now.
dos.write(myMessage, 0, MY_MESSAGE_LEN);
fail("Test 1: IOException expected.");
} catch (IOException e) {
// Expected.
}
}
public static byte[] streamEncrypt(String message, SecretKey key,
MessageDigest digest)
throws Exception {
byte[] data;
Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
encCipher.init(Cipher.ENCRYPT_MODE, key);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
DigestOutputStream dos = new DigestOutputStream(bos, digest);
CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
oos.writeObject(message);
}
data = bos.toByteArray();
}
if (debug) {
System.out.println(DatatypeConverter.printHexBinary(data));
}
return data;
}
public static byte[] streamEncrypt(String message, SecretKey key,
MessageDigest digest)
throws Exception {
byte[] data;
Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
encCipher.init(Cipher.ENCRYPT_MODE, key);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
DigestOutputStream dos = new DigestOutputStream(bos, digest);
CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
oos.writeObject(message);
}
data = bos.toByteArray();
}
if (debug) {
System.out.println(DatatypeConverter.printHexBinary(data));
}
return data;
}
private static void writeBinaryCheckpoints(TreeMap<Integer, StoredBlock> checkpoints, File file) throws Exception {
final FileOutputStream fileOutputStream = new FileOutputStream(file, false);
MessageDigest digest = Sha256Hash.newDigest();
final DigestOutputStream digestOutputStream = new DigestOutputStream(fileOutputStream, digest);
digestOutputStream.on(false);
final DataOutputStream dataOutputStream = new DataOutputStream(digestOutputStream);
dataOutputStream.writeBytes("CHECKPOINTS 1");
dataOutputStream.writeInt(0); // Number of signatures to read. Do this later.
digestOutputStream.on(true);
dataOutputStream.writeInt(checkpoints.size());
ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE);
for (StoredBlock block : checkpoints.values()) {
block.serializeCompact(buffer);
dataOutputStream.write(buffer.array());
buffer.position(0);
}
dataOutputStream.close();
Sha256Hash checkpointsHash = Sha256Hash.wrap(digest.digest());
System.out.println("Hash of checkpoints data is " + checkpointsHash);
digestOutputStream.close();
fileOutputStream.close();
System.out.println("Checkpoints written to '" + file.getCanonicalPath() + "'.");
}
public static byte[] streamEncrypt(String message, SecretKey key,
MessageDigest digest)
throws Exception {
byte[] data;
Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
encCipher.init(Cipher.ENCRYPT_MODE, key);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
DigestOutputStream dos = new DigestOutputStream(bos, digest);
CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
oos.writeObject(message);
}
data = bos.toByteArray();
}
if (debug) {
System.out.println(DatatypeConverter.printHexBinary(data));
}
return data;
}
public NativeS3FsOutputStream(Configuration conf,
NativeFileSystemStore store, String key, Progressable progress,
int bufferSize) throws IOException {
this.conf = conf;
this.key = key;
this.backupFile = newBackupFile();
try {
this.digest = MessageDigest.getInstance("MD5");
this.backupStream = new BufferedOutputStream(new DigestOutputStream(
new FileOutputStream(backupFile), this.digest));
} catch (NoSuchAlgorithmException e) {
LOG.warn("Cannot load MD5 digest algorithm," +
"skipping message integrity check.", e);
this.backupStream = new BufferedOutputStream(
new FileOutputStream(backupFile));
}
}
private void internalAppendFile(FSDataOutputStream os, File file, List<String> parentDirectories, SquallArchiveCompressor compressor, String archiveFilename) throws IOException {
final String baseFilename = file.getName().replaceAll("\\s+", "_");
final String filename = makeFilename(parentDirectories, baseFilename);
final long size = file.length();
final long timestamp = file.lastModified();
final long startOffset = os.getPos();
final InputStream is = new BufferedInputStream(new FileInputStream(file));
final String checksum;
try {
final CompressionOutputStream cos = compressor.newOutputStream(os);
final DigestOutputStream dos = new DigestOutputStream(cos, ArchiveUtils.getMD5Digest());
ByteStreams.copy(is, dos);
checksum = ArchiveUtils.toHex(dos.getMessageDigest().digest());
cos.finish();
} finally {
is.close();
}
pendingMetadataWrites.add(new FileMetadata(filename, size, timestamp, checksum, startOffset, compressor, archiveFilename));
}
public void create() {
checkFilesAccessibility(bundledPlugins, externalPlugins);
reset();
MessageDigest md5Digest = DigestUtils.getMd5Digest();
try (ZipOutputStream zos = new ZipOutputStream(new DigestOutputStream(new BufferedOutputStream(new FileOutputStream(destZipFile)), md5Digest))) {
for (GoPluginBundleDescriptor agentPlugins : agentPlugins()) {
String zipEntryPrefix = "external/";
if (agentPlugins.isBundledPlugin()) {
zipEntryPrefix = "bundled/";
}
zos.putNextEntry(new ZipEntry(zipEntryPrefix + new File(agentPlugins.bundleJARFileLocation()).getName()));
Files.copy(new File(agentPlugins.bundleJARFileLocation()).toPath(), zos);
zos.closeEntry();
}
} catch (Exception e) {
LOG.error("Could not create zip of plugins for agent to download.", e);
}
md5DigestOfPlugins = Hex.encodeHexString(md5Digest.digest());
}
public static byte[] streamEncrypt(String message, SecretKey key,
MessageDigest digest)
throws Exception {
byte[] data;
Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
encCipher.init(Cipher.ENCRYPT_MODE, key);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
DigestOutputStream dos = new DigestOutputStream(bos, digest);
CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
oos.writeObject(message);
}
data = bos.toByteArray();
}
if (debug) {
System.out.println(DatatypeConverter.printHexBinary(data));
}
return data;
}
public NativeS3FsOutputStream(Configuration conf,
NativeFileSystemStore store, String key, Progressable progress,
int bufferSize) throws IOException {
this.conf = conf;
this.key = key;
this.backupFile = newBackupFile();
LOG.info("OutputStream for key '" + key + "' writing to tempfile '" + this.backupFile + "'");
try {
this.digest = MessageDigest.getInstance("MD5");
this.backupStream = new BufferedOutputStream(new DigestOutputStream(
new FileOutputStream(backupFile), this.digest));
} catch (NoSuchAlgorithmException e) {
LOG.warn("Cannot load MD5 digest algorithm," +
"skipping message integrity check.", e);
this.backupStream = new BufferedOutputStream(
new FileOutputStream(backupFile));
}
}
public static byte[] streamEncrypt(String message, SecretKey key,
MessageDigest digest)
throws Exception {
byte[] data;
Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
encCipher.init(Cipher.ENCRYPT_MODE, key);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
DigestOutputStream dos = new DigestOutputStream(bos, digest);
CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
oos.writeObject(message);
}
data = bos.toByteArray();
}
if (debug) {
System.out.println(DatatypeConverter.printHexBinary(data));
}
return data;
}
public static byte[] streamEncrypt(String message, SecretKey key,
MessageDigest digest)
throws Exception {
byte[] data;
Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
encCipher.init(Cipher.ENCRYPT_MODE, key);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
DigestOutputStream dos = new DigestOutputStream(bos, digest);
CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
oos.writeObject(message);
}
data = bos.toByteArray();
}
if (debug) {
System.out.println(DatatypeConverter.printHexBinary(data));
}
return data;
}
public NativeS3FsOutputStream(Configuration conf,
NativeFileSystemStore store, String key, Progressable progress,
int bufferSize) throws IOException {
this.conf = conf;
this.key = key;
this.backupFile = newBackupFile();
LOG.info("OutputStream for key '" + key + "' writing to tempfile '" + this.backupFile + "'");
try {
this.digest = MessageDigest.getInstance("MD5");
this.backupStream = new BufferedOutputStream(new DigestOutputStream(
new FileOutputStream(backupFile), this.digest));
} catch (NoSuchAlgorithmException e) {
LOG.warn("Cannot load MD5 digest algorithm," +
"skipping message integrity check.", e);
this.backupStream = new BufferedOutputStream(
new FileOutputStream(backupFile));
}
}
protected String xmlDigest(JasperPrint print)
throws NoSuchAlgorithmException, FileNotFoundException, JRException, IOException
{
File outputFile = createXmlOutputFile();
log.debug("XML export output at " + outputFile.getAbsolutePath());
MessageDigest digest = MessageDigest.getInstance("SHA-1");
FileOutputStream output = new FileOutputStream(outputFile);
try
{
DigestOutputStream out = new DigestOutputStream(output, digest);
xmlExport(print, out);
}
finally
{
output.close();
}
return toDigestString(digest);
}
public static byte[] streamEncrypt(String message, SecretKey key,
MessageDigest digest)
throws Exception {
byte[] data;
Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
encCipher.init(Cipher.ENCRYPT_MODE, key);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
DigestOutputStream dos = new DigestOutputStream(bos, digest);
CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
oos.writeObject(message);
}
data = bos.toByteArray();
}
if (debug) {
System.out.println(DatatypeConverter.printHexBinary(data));
}
return data;
}
public static byte[] streamEncrypt(String message, SecretKey key,
MessageDigest digest)
throws Exception {
byte[] data;
Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
encCipher.init(Cipher.ENCRYPT_MODE, key);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
DigestOutputStream dos = new DigestOutputStream(bos, digest);
CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
oos.writeObject(message);
}
data = bos.toByteArray();
}
if (debug) {
System.out.println(DatatypeConverter.printHexBinary(data));
}
return data;
}
@Override
public byte[] addContent(InputStream stream) throws IOException {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
byte[] sha1Bytes;
Path tmp = TempFileManager.INSTANCE.newTempFile("content", ".tmp").toPath();
try (OutputStream fos = Files.newOutputStream(tmp); BufferedInputStream bis = new BufferedInputStream(stream)) {
messageDigest.reset();
try (DigestOutputStream dos = new DigestOutputStream(fos, messageDigest)) {
byte[] bytes = new byte[8192];
int read;
while ((read = bis.read(bytes)) > -1) {
dos.write(bytes, 0, read);
}
fos.flush();
}
sha1Bytes = messageDigest.digest();
}
String key = toKey(sha1Bytes);
this.index.put(key, tmp.toUri());
return sha1Bytes;
} catch (NoSuchAlgorithmException e) {
throw new IOException(e);
}
}
private static void writeBinaryCheckpoints(TreeMap<Integer, StoredBlock> checkpoints, File file) throws Exception {
final FileOutputStream fileOutputStream = new FileOutputStream(file, false);
MessageDigest digest = Sha256Hash.newDigest();
final DigestOutputStream digestOutputStream = new DigestOutputStream(fileOutputStream, digest);
digestOutputStream.on(false);
final DataOutputStream dataOutputStream = new DataOutputStream(digestOutputStream);
dataOutputStream.writeBytes("CHECKPOINTS 1");
dataOutputStream.writeInt(0); // Number of signatures to read. Do this later.
digestOutputStream.on(true);
dataOutputStream.writeInt(checkpoints.size());
ByteBuffer buffer = ByteBuffer.allocate(StoredBlock.COMPACT_SERIALIZED_SIZE);
for (StoredBlock block : checkpoints.values()) {
block.serializeCompact(buffer);
dataOutputStream.write(buffer.array());
buffer.position(0);
}
dataOutputStream.close();
Sha256Hash checkpointsHash = Sha256Hash.wrap(digest.digest());
System.out.println("Hash of checkpoints data is " + checkpointsHash);
digestOutputStream.close();
fileOutputStream.close();
System.out.println("Checkpoints written to '" + file.getCanonicalPath() + "'.");
}
/**
* java.security.DigestOutputStream#setMessageDigest(MessageDigest)
*/
public void test_setMessageDigestLjava_security_MessageDigest() {
MessageDigest digest = new MyMessageDigest1();
OutputStream out = new MyOutputStream();
DigestOutputStream dos = new DigestOutputStream(out, null);
// non-null parameter
dos.setMessageDigest(digest);
assertSame(digest, dos.getMessageDigest());
// null parameter
dos.setMessageDigest(null);
assertNull("getMessageDigest should have returned null", dos.getMessageDigest());
}
/**
* Compute the "method hash" of a remote method. The method hash
* is a long containing the first 64 bits of the SHA digest from
* the UTF encoded string of the method name and descriptor.
*/
public static long computeMethodHash(Method m) {
long hash = 0;
ByteArrayOutputStream sink = new ByteArrayOutputStream(127);
try {
MessageDigest md = MessageDigest.getInstance("SHA");
DataOutputStream out = new DataOutputStream(
new DigestOutputStream(sink, md));
String s = getMethodNameAndDescriptor(m);
if (serverRefLog.isLoggable(Log.VERBOSE)) {
serverRefLog.log(Log.VERBOSE,
"string used for method hash: \"" + s + "\"");
}
out.writeUTF(s);
// use only the first 64 bits of the digest for the hash
out.flush();
byte hasharray[] = md.digest();
for (int i = 0; i < Math.min(8, hasharray.length); i++) {
hash += ((long) (hasharray[i] & 0xFF)) << (i * 8);
}
} catch (IOException ignore) {
/* can't happen, but be deterministic anyway. */
hash = -1;
} catch (NoSuchAlgorithmException complain) {
throw new SecurityException(complain.getMessage());
}
return hash;
}
/**
* Test DigestInputStream and DigestOutputStream digest function when use
* same message digest object.
*
* @param algo
* Message Digest algorithm
* @param dataLength
* plain test data length.
* @exception Exception
* throw unexpected exception
*/
public boolean testMDShare(String algo, int dataLength) throws Exception {
MessageDigest mdCommon = MessageDigest.getInstance(algo);
// Generate the DigestInputStream/DigestOutputStream object
try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
DigestInputStream dis = new DigestInputStream(bais, mdCommon);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DigestOutputStream dos = new DigestOutputStream(baos, mdCommon);) {
// Perform the update using all available/possible update methods
int k = 0;
byte[] buffer = new byte[10];
// use both read() and read(byte[], int, int)
while (k < data.length) {
int len = dis.read(buffer, 0, buffer.length);
if (len != -1) {
k += len;
if (k < data.length) {
dos.write(data[k]);
k++;
dis.skip(1);
}
}
}
// Get the output and the "correct" digest values
byte[] output = mdCommon.digest();
byte[] standard = md.digest(data);
// Compare generated digest values
return MessageDigest.isEqual(output, standard);
} catch (Exception ex) {
out.println("TestMDShare failed at:" + algo + "/" + dataLength
+ " with unexpected exception");
throw ex;
}
}
/**
* java.security.DigestOutputStream#write(byte[], int, int)
*/
public void test_write$BII_5() throws Exception {
// Test for method void java.security.DigestOutputStream.write(byte [],
// int, int)
DigestOutputStream dos = new DigestOutputStream(
new ByteArrayOutputStream(), MessageDigest.getInstance("SHA"));
byte digestArray[] = { 23, 43, 44 };
dos.write(digestArray, 1, 1);
byte digestResult[] = dos.getMessageDigest().digest();
byte expected[] = { -87, 121, -17, 16, -52, 111, 106, 54, -33, 107,
-118, 50, 51, 7, -18, 59, -78, -30, -37, -100 };
assertTrue("Digest did not return expected result.",
Arrays.equals(digestResult, expected));
}
/**
* Test DigestInputStream and DigestOutputStream digest function when use
* same message digest object.
*
* @param algo
* Message Digest algorithm
* @param dataLength
* plain test data length.
* @exception Exception
* throw unexpected exception
*/
public boolean testMDShare(String algo, int dataLength) throws Exception {
MessageDigest mdCommon = MessageDigest.getInstance(algo);
// Generate the DigestInputStream/DigestOutputStream object
try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
DigestInputStream dis = new DigestInputStream(bais, mdCommon);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DigestOutputStream dos = new DigestOutputStream(baos, mdCommon);) {
// Perform the update using all available/possible update methods
int k = 0;
byte[] buffer = new byte[10];
// use both read() and read(byte[], int, int)
while (k < data.length) {
int len = dis.read(buffer, 0, buffer.length);
if (len != -1) {
k += len;
if (k < data.length) {
dos.write(data[k]);
k++;
dis.skip(1);
}
}
}
// Get the output and the "correct" digest values
byte[] output = mdCommon.digest();
byte[] standard = md.digest(data);
// Compare generated digest values
return MessageDigest.isEqual(output, standard);
} catch (Exception ex) {
out.println("TestMDShare failed at:" + algo + "/" + dataLength
+ " with unexpected exception");
throw ex;
}
}
/**
*
* @param stream The stream to compress
* @param checksumAlgo checksum algorithm
* @throws NoSuchAlgorithmException nosuchalgorithmexception
* @throws IOException ioexception
*/
public CompressingDigestOutputWriter(OutputStream stream, String checksumAlgo)
throws NoSuchAlgorithmException, IOException {
compressedDigestStream = new DigestOutputStream(stream,
MessageDigest.getInstance(checksumAlgo));
compressedStream = new GZIPOutputStream(compressedDigestStream);
uncompressedDigestStream = new DigestOutputStream(compressedStream,
MessageDigest.getInstance(checksumAlgo));
bufferedStream = new BufferedOutputStream(uncompressedDigestStream);
}
/**
* Compute the "method hash" of a remote method. The method hash
* is a long containing the first 64 bits of the SHA digest from
* the UTF encoded string of the method name and descriptor.
*/
public static long computeMethodHash(Method m) {
long hash = 0;
ByteArrayOutputStream sink = new ByteArrayOutputStream(127);
try {
MessageDigest md = MessageDigest.getInstance("SHA");
DataOutputStream out = new DataOutputStream(
new DigestOutputStream(sink, md));
String s = getMethodNameAndDescriptor(m);
if (serverRefLog.isLoggable(Log.VERBOSE)) {
serverRefLog.log(Log.VERBOSE,
"string used for method hash: \"" + s + "\"");
}
out.writeUTF(s);
// use only the first 64 bits of the digest for the hash
out.flush();
byte hasharray[] = md.digest();
for (int i = 0; i < Math.min(8, hasharray.length); i++) {
hash += ((long) (hasharray[i] & 0xFF)) << (i * 8);
}
} catch (IOException ignore) {
/* can't happen, but be deterministic anyway. */
hash = -1;
} catch (NoSuchAlgorithmException complain) {
throw new SecurityException(complain.getMessage());
}
return hash;
}
public void engineStore(OutputStream out, char[] passwd)
throws IOException, NoSuchAlgorithmException, CertificateException
{
MessageDigest md = MessageDigest.getInstance("SHA1");
md.update(charsToBytes(passwd));
md.update("Mighty Aphrodite".getBytes("UTF-8"));
DataOutputStream dout = new DataOutputStream(new DigestOutputStream(out, md));
dout.writeInt(MAGIC);
dout.writeInt(2);
dout.writeInt(aliases.size());
for (Enumeration e = aliases.elements(); e.hasMoreElements(); )
{
String alias = (String) e.nextElement();
if (trustedCerts.containsKey(alias))
{
dout.writeInt(TRUSTED_CERT);
dout.writeUTF(alias);
dout.writeLong(((Date) dates.get(alias)).getTime());
writeCert(dout, (Certificate) trustedCerts.get(alias));
}
else
{
dout.writeInt(PRIVATE_KEY);
dout.writeUTF(alias);
dout.writeLong(((Date) dates.get(alias)).getTime());
byte[] key = (byte[]) privateKeys.get(alias);
dout.writeInt(key.length);
dout.write(key);
Certificate[] chain = (Certificate[]) certChains.get(alias);
dout.writeInt(chain.length);
for (int i = 0; i < chain.length; i++)
writeCert(dout, chain[i]);
}
}
byte[] digest = md.digest();
dout.write(digest);
}
/**
* Test #2 for <code>write(byte[],int,int)</code> method<br>
*
* Assertion: put bytes into output stream<br>
*
* Assertion: updates associated digest<br>
*/
public final void test_write$BII_2() throws IOException {
// check precondition
assertEquals(0, MY_MESSAGE_LEN % CHUNK_SIZE);
for (int k=0; k<algorithmName.length; k++) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream(MY_MESSAGE_LEN);
MessageDigest md = MessageDigest.getInstance(algorithmName[k]);
DigestOutputStream dos = new DigestOutputStream(bos, md);
// write message by chunks
for (int i=0; i<MY_MESSAGE_LEN/CHUNK_SIZE; i++) {
dos.write(myMessage, i*CHUNK_SIZE, CHUNK_SIZE);
}
// check write
assertTrue("write", Arrays.equals(myMessage, bos.toByteArray()));
// check that associated digest has been updated properly
assertTrue("update", Arrays.equals(dos.getMessageDigest().digest(),
MDGoldenData.getDigest(algorithmName[k])));
return;
} catch (NoSuchAlgorithmException e) {
// allowed failure
}
}
fail(getName() + ": no MessageDigest algorithms available - test not performed");
}
/**
* Compute the "method hash" of a remote method. The method hash
* is a long containing the first 64 bits of the SHA digest from
* the UTF encoded string of the method name and descriptor.
*/
public static long computeMethodHash(Method m) {
long hash = 0;
ByteArrayOutputStream sink = new ByteArrayOutputStream(127);
try {
MessageDigest md = MessageDigest.getInstance("SHA");
DataOutputStream out = new DataOutputStream(
new DigestOutputStream(sink, md));
String s = getMethodNameAndDescriptor(m);
if (serverRefLog.isLoggable(Log.VERBOSE)) {
serverRefLog.log(Log.VERBOSE,
"string used for method hash: \"" + s + "\"");
}
out.writeUTF(s);
// use only the first 64 bits of the digest for the hash
out.flush();
byte hasharray[] = md.digest();
for (int i = 0; i < Math.min(8, hasharray.length); i++) {
hash += ((long) (hasharray[i] & 0xFF)) << (i * 8);
}
} catch (IOException ignore) {
/* can't happen, but be deterministic anyway. */
hash = -1;
} catch (NoSuchAlgorithmException complain) {
throw new SecurityException(complain.getMessage());
}
return hash;
}
/**
* Test DigestInputStream and DigestOutputStream digest function when use
* same message digest object.
*
* @param algo
* Message Digest algorithm
* @param dataLength
* plain test data length.
* @exception Exception
* throw unexpected exception
*/
public boolean testMDShare(String algo, int dataLength) throws Exception {
MessageDigest mdCommon = MessageDigest.getInstance(algo);
// Generate the DigestInputStream/DigestOutputStream object
try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
DigestInputStream dis = new DigestInputStream(bais, mdCommon);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DigestOutputStream dos = new DigestOutputStream(baos, mdCommon);) {
// Perform the update using all available/possible update methods
int k = 0;
byte[] buffer = new byte[10];
// use both read() and read(byte[], int, int)
while (k < data.length) {
int len = dis.read(buffer, 0, buffer.length);
if (len != -1) {
k += len;
if (k < data.length) {
dos.write(data[k]);
k++;
dis.skip(1);
}
}
}
// Get the output and the "correct" digest values
byte[] output = mdCommon.digest();
byte[] standard = md.digest(data);
// Compare generated digest values
return MessageDigest.isEqual(output, standard);
} catch (Exception ex) {
out.println("TestMDShare failed at:" + algo + "/" + dataLength
+ " with unexpected exception");
throw ex;
}
}
/**
*
* @param stream The stream to compress
* @param checksumAlgo checksum algorithm
* @throws NoSuchAlgorithmException nosuchalgorithmexception
* @throws IOException ioexception
*/
public CompressingDigestOutputWriter(OutputStream stream, String checksumAlgo)
throws NoSuchAlgorithmException, IOException {
compressedDigestStream = new DigestOutputStream(stream,
MessageDigest.getInstance(checksumAlgo));
compressedStream = new GZIPOutputStream(compressedDigestStream);
uncompressedDigestStream = new DigestOutputStream(compressedStream,
MessageDigest.getInstance(checksumAlgo));
bufferedStream = new BufferedOutputStream(uncompressedDigestStream);
}