Code example for MessageDigest

Methods: digestgetAlgorithmgetDigestLengthresetupdate

0
        if (md == null) {
            throw new NullPointerException("MessageDigest is null");
        } 
         
        // Make sure the digest length is defined 
        int digestLength = md.getDigestLength();
        if (digestLength == 0) {
            throw new IllegalArgumentException("Digest length is undefined");
        } 
         
        // Block size must be greater than zero 
        if (blockSize <= 0) {
            throw new IllegalArgumentException("Illegal block size: " + blockSize);
        } 
         
        // Block size must be greater than digest length 
        if (blockSize <= digestLength) {
            throw new IllegalArgumentException("Block size must be greater than digest length: " 
                    + blockSize + " <= " + digestLength);
        } 
         
        // Create the header 
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeUTF(md.getAlgorithm());
        dos.writeInt(md.getDigestLength());
        dos.writeInt(blockSize);
        dos.close();
         
        byte[] header = baos.toByteArray();
         
        // Write the length of the header 
        out.write((header.length >> 24) & 0xFF);
        out.write((header.length >> 16) & 0xFF);
        out.write((header.length >>  8) & 0xFF);
        out.write((header.length      ) & 0xFF);
         
        // Write the header 
        out.write(header, 0, header.length);
         
        // Write the digest of the header 
        md.update(header, 0, header.length);
        byte[] digest = md.digest();
        out.write(digest, 0, digest.length);
         
        md.reset();
         
        this.md = md;
         
        // [data] + [checksum] == blockSize 
        this.dataSize = blockSize - digestLength;