Java Code Examples for java.security.MessageDigest.isEqual()

The following are Jave code examples for showing how to use isEqual() of the java.security.MessageDigest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: atbash-octopus   File: SimpleCredentialsMatcher.java   View Source Code Vote up 6 votes
/**
 * Returns {@code true} if the {@code tokenCredentials} argument is logically equal to the
 * {@code accountCredentials} argument.
 * <p/>
 * <p>If both arguments are either a byte array (byte[]), char array (char[]) or String, they will be both be
 * converted to raw byte arrays via the {@link #toBytes toBytes} method first, and then resulting byte arrays
 * are compared via {@link Arrays#equals(byte[], byte[]) Arrays.equals(byte[],byte[])}.</p>
 * <p/>
 * <p>If either argument cannot be converted to a byte array as described, a simple Object <code>equals</code>
 * comparison is made.</p>
 * <p/>
 * <p>Subclasses should override this method for more explicit equality checks.
 *
 * @param tokenCredentials   the {@code AuthenticationToken}'s associated credentials.
 * @param accountCredentials the {@code AuthenticationInfo}'s stored credentials.
 * @return {@code true} if the {@code tokenCredentials} are equal to the {@code accountCredentials}.
 */
protected boolean equals(Object tokenCredentials, Object accountCredentials) {
    if (tokenCredentials == null || accountCredentials == null) {
        return false;
    }

    if (log.isDebugEnabled()) {
        log.debug("Performing credentials equality check for tokenCredentials of type [" +
                tokenCredentials.getClass().getName() + " and accountCredentials of type [" +
                accountCredentials.getClass().getName() + "]");
    }
    if (isByteSource(tokenCredentials) && isByteSource(accountCredentials)) {
        if (log.isDebugEnabled()) {
            log.debug("Both credentials arguments can be easily converted to byte arrays.  Performing " +
                    "array equals comparison");
        }
        byte[] tokenBytes = toBytes(tokenCredentials);
        byte[] accountBytes = toBytes(accountCredentials);
        return MessageDigest.isEqual(tokenBytes, accountBytes);
    } else {
        return accountCredentials.equals(tokenCredentials);
    }
}
 
Example 2
Project: jdk8u-jdk   File: DESKey.java   View Source Code Vote up 6 votes
public boolean equals(Object obj) {
    if (this == obj)
        return true;

    if (!(obj instanceof SecretKey))
        return false;

    String thatAlg = ((SecretKey)obj).getAlgorithm();
    if (!(thatAlg.equalsIgnoreCase("DES")))
        return false;

    byte[] thatKey = ((SecretKey)obj).getEncoded();
    boolean ret = MessageDigest.isEqual(this.key, thatKey);
    java.util.Arrays.fill(thatKey, (byte)0x00);
    return ret;
}
 
Example 3
Project: jdk8u-jdk   File: DESedeKey.java   View Source Code Vote up 6 votes
public boolean equals(Object obj) {
    if (this == obj)
        return true;

    if (!(obj instanceof SecretKey))
        return false;

    String thatAlg = ((SecretKey)obj).getAlgorithm();
    if (!(thatAlg.equalsIgnoreCase("DESede"))
        && !(thatAlg.equalsIgnoreCase("TripleDES")))
        return false;

    byte[] thatKey = ((SecretKey)obj).getEncoded();
    boolean ret = MessageDigest.isEqual(this.key, thatKey);
    java.util.Arrays.fill(thatKey, (byte)0x00);
    return ret;
}
 
Example 4
Project: openjdk-jdk10   File: MessageToken_v2.java   View Source Code Vote up 6 votes
/**
 * Verifies the validity of checksum field
 *
 * @param data the application data
 * @param offset the offset where the data begins
 * @param len the length of the application data
 *
 * @throws GSSException if an error occurs in the checksum calculation
 */
public final boolean verifySign(byte[] data, int offset, int len)
    throws GSSException {

    // debug("\t====In verifySign:====\n");
    // debug("\t\t checksum:   [" + getHexBytes(checksum) + "]\n");
    // debug("\t\t data = [" + getHexBytes(data) + "]\n");

    byte[] myChecksum = getChecksum(data, offset, len);
    // debug("\t\t mychecksum: [" + getHexBytes(myChecksum) +"]\n");

    if (MessageDigest.isEqual(checksum, myChecksum)) {
        // debug("\t\t====Checksum PASS:====\n");
        return true;
    }
    return false;
}
 
Example 5
Project: OpenJSharp   File: MessageToken_v2.java   View Source Code Vote up 6 votes
/**
 * Verifies the validity of checksum field
 *
 * @param data the application data
 * @param offset the offset where the data begins
 * @param len the length of the application data
 *
 * @throws GSSException if an error occurs in the checksum calculation
 */
public final boolean verifySign(byte[] data, int offset, int len)
    throws GSSException {

    // debug("\t====In verifySign:====\n");
    // debug("\t\t checksum:   [" + getHexBytes(checksum) + "]\n");
    // debug("\t\t data = [" + getHexBytes(data) + "]\n");

    byte[] myChecksum = getChecksum(data, offset, len);
    // debug("\t\t mychecksum: [" + getHexBytes(myChecksum) +"]\n");

    if (MessageDigest.isEqual(checksum, myChecksum)) {
        // debug("\t\t====Checksum PASS:====\n");
        return true;
    }
    return false;
}
 
Example 6
Project: jdk8u-jdk   File: SecretKeySpec.java   View Source Code Vote up 6 votes
/**
 * Tests for equality between the specified object and this
 * object. Two SecretKeySpec objects are considered equal if
 * they are both SecretKey instances which have the
 * same case-insensitive algorithm name and key encoding.
 *
 * @param obj the object to test for equality with this object.
 *
 * @return true if the objects are considered equal, false if
 * <code>obj</code> is null or otherwise.
 */
public boolean equals(Object obj) {
    if (this == obj)
        return true;

    if (!(obj instanceof SecretKey))
        return false;

    String thatAlg = ((SecretKey)obj).getAlgorithm();
    if (!(thatAlg.equalsIgnoreCase(this.algorithm))) {
        if ((!(thatAlg.equalsIgnoreCase("DESede"))
             || !(this.algorithm.equalsIgnoreCase("TripleDES")))
            && (!(thatAlg.equalsIgnoreCase("TripleDES"))
                || !(this.algorithm.equalsIgnoreCase("DESede"))))
        return false;
    }

    byte[] thatKey = ((SecretKey)obj).getEncoded();

    return MessageDigest.isEqual(this.key, thatKey);
}
 
Example 7
Project: jdk8u-jdk   File: PBKDF2KeyImpl.java   View Source Code Vote up 6 votes
public boolean equals(Object obj) {
    if (obj == this)
        return true;

    if (!(obj instanceof SecretKey))
        return false;

    SecretKey that = (SecretKey) obj;

    if (!(that.getAlgorithm().equalsIgnoreCase(getAlgorithm())))
        return false;
    if (!(that.getFormat().equalsIgnoreCase("RAW")))
        return false;
    byte[] thatEncoded = that.getEncoded();
    boolean ret = MessageDigest.isEqual(key, that.getEncoded());
    java.util.Arrays.fill(thatEncoded, (byte)0x00);
    return ret;
}
 
Example 8
Project: jdk8u-jdk   File: MessageToken_v2.java   View Source Code Vote up 6 votes
/**
 * Verifies the validity of checksum field
 *
 * @param data the application data
 * @param offset the offset where the data begins
 * @param len the length of the application data
 *
 * @throws GSSException if an error occurs in the checksum calculation
 */
public final boolean verifySign(byte[] data, int offset, int len)
    throws GSSException {

    // debug("\t====In verifySign:====\n");
    // debug("\t\t checksum:   [" + getHexBytes(checksum) + "]\n");
    // debug("\t\t data = [" + getHexBytes(data) + "]\n");

    byte[] myChecksum = getChecksum(data, offset, len);
    // debug("\t\t mychecksum: [" + getHexBytes(myChecksum) +"]\n");

    if (MessageDigest.isEqual(checksum, myChecksum)) {
        // debug("\t\t====Checksum PASS:====\n");
        return true;
    }
    return false;
}
 
Example 9
Project: xsalsa20poly1305   File: SecretBox.java   View Source Code Vote up 5 votes
/**
 * Decrypt a ciphertext using the given key and nonce.
 *
 * @param nonce a 24-byte nonce
 * @param ciphertext the encrypted message
 * @return an {@link Optional} of the original plaintext, or if either the key, nonce, or
 *     ciphertext was modified, an empty {@link Optional}
 * @see #nonce(ByteString)
 * @see #nonce()
 */
public Optional<ByteString> open(@Nonnull ByteString nonce, @Nonnull ByteString ciphertext) {
  final byte[] in = ciphertext.toByteArray();
  final XSalsa20Engine xsalsa20 = new XSalsa20Engine();
  final Poly1305 poly1305 = new Poly1305();

  // initialize XSalsa20
  xsalsa20.init(false, new ParametersWithIV(new KeyParameter(key), nonce.toByteArray()));

  // generate mac subkey
  final byte[] sk = new byte[32];
  xsalsa20.processBytes(sk, 0, sk.length, sk, 0);

  // hash ciphertext
  poly1305.init(new KeyParameter(sk));
  final int len = Math.max(ciphertext.size() - 16, 0);
  poly1305.update(in, 16, len);
  final byte[] calculatedMAC = new byte[16];
  poly1305.doFinal(calculatedMAC, 0);

  // extract mac
  final byte[] presentedMAC = new byte[16];
  System.arraycopy(in, 0, presentedMAC, 0, Math.min(ciphertext.size(), 16));

  // compare macs
  if (!MessageDigest.isEqual(calculatedMAC, presentedMAC)) {
    return Optional.empty();
  }

  // decrypt ciphertext
  final byte[] plaintext = new byte[len];
  xsalsa20.processBytes(in, 16, plaintext.length, plaintext, 0);
  return Optional.of(ByteString.of(plaintext));
}
 
Example 10
Project: syndesis   File: ClientSideState.java   View Source Code Vote up 5 votes
<T> TimestampedState<T> restoreWithTimestamp(final Cookie cookie, final Class<T> type) {
    final String value = cookie.getValue();

    final String[] parts = value.split("\\|", 5);

    final byte[] atime = DECODER.decode(parts[1]);

    final long atimeLong = atime(atime);

    if (atimeLong + timeout < timeSource.getAsLong()) {
        throw new IllegalArgumentException("Given value has timed out at: " + Instant.ofEpochSecond(atimeLong));
    }

    final byte[] tid = DECODER.decode(parts[2]);
    if (!MessageDigest.isEqual(tid, edition.tid)) {
        throw new IllegalArgumentException(String.format("Given TID `%s`, mismatches current TID `%s`",
            new BigInteger(tid).toString(16), new BigInteger(edition.tid).toString(16)));
    }

    final KeySource keySource = edition.keySource();
    final int lastSeparatorIdx = value.lastIndexOf('|');
    final byte[] mac = DECODER.decode(parts[4]);
    final byte[] calculated = mac(edition.authenticationAlgorithm, value.substring(0, lastSeparatorIdx),
        keySource.authenticationKey());
    if (!MessageDigest.isEqual(mac, calculated)) {
        throw new IllegalArgumentException("Cookie value fails authenticity check");
    }

    final byte[] iv = DECODER.decode(parts[3]);
    final byte[] encrypted = DECODER.decode(parts[0]);
    final byte[] clear = decrypt(edition.encryptionAlgorithm, iv, encrypted, keySource.encryptionKey());

    @SuppressWarnings("unchecked")
    final T ret = (T) deserialization.apply(type, clear);

    return new TimestampedState<>(ret, atimeLong);
}
 
Example 11
Project: PeSanKita-lib   File: AttachmentCipherInputStream.java   View Source Code Vote up 5 votes
private void verifyMac(File file, Mac mac, Optional<byte[]> theirDigest)
    throws FileNotFoundException, InvalidMacException
{
  try {
    MessageDigest   digest        = MessageDigest.getInstance("SHA256");
    FileInputStream fin           = new FileInputStream(file);
    int             remainingData = Util.toIntExact(file.length()) - mac.getMacLength();
    byte[]          buffer        = new byte[4096];

    while (remainingData > 0) {
      int read = fin.read(buffer, 0, Math.min(buffer.length, remainingData));
      mac.update(buffer, 0, read);
      digest.update(buffer, 0, read);
      remainingData -= read;
    }

    byte[] ourMac   = mac.doFinal();
    byte[] theirMac = new byte[mac.getMacLength()];
    Util.readFully(fin, theirMac);

    if (!MessageDigest.isEqual(ourMac, theirMac)) {
      throw new InvalidMacException("MAC doesn't match!");
    }

    byte[] ourDigest = digest.digest(theirMac);

    if (theirDigest.isPresent() && !MessageDigest.isEqual(ourDigest, theirDigest.get())) {
      throw new InvalidMacException("Digest doesn't match!");
    }

  } catch (IOException | ArithmeticException e1) {
    throw new InvalidMacException(e1);
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
 
Example 12
Project: jdk8u-jdk   File: DOMHMACSignatureMethod.java   View Source Code Vote up 5 votes
boolean verify(Key key, SignedInfo si, byte[] sig,
               XMLValidateContext context)
    throws InvalidKeyException, SignatureException, XMLSignatureException
{
    if (key == null || si == null || sig == null) {
        throw new NullPointerException();
    }
    if (!(key instanceof SecretKey)) {
        throw new InvalidKeyException("key must be SecretKey");
    }
    if (hmac == null) {
        try {
            hmac = Mac.getInstance(getJCAAlgorithm());
        } catch (NoSuchAlgorithmException nsae) {
            throw new XMLSignatureException(nsae);
        }
    }
    if (outputLengthSet && outputLength < getDigestLength()) {
        throw new XMLSignatureException
            ("HMACOutputLength must not be less than " + getDigestLength());
    }
    hmac.init((SecretKey)key);
    ((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac));
    byte[] result = hmac.doFinal();

    return MessageDigest.isEqual(sig, result);
}
 
Example 13
Project: Cable-Android   File: UpdateApkJob.java   View Source Code Vote up 5 votes
private DownloadStatus getDownloadStatus(String uri, byte[] theirDigest) {
  DownloadManager       downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
  DownloadManager.Query query           = new DownloadManager.Query();

  query.setFilterByStatus(DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_SUCCESSFUL);

  long   pendingDownloadId = TextSecurePreferences.getUpdateApkDownloadId(context);
  byte[] pendingDigest     = getPendingDigest(context);
  Cursor cursor            = downloadManager.query(query);

  try {
    DownloadStatus status = new DownloadStatus(DownloadStatus.Status.MISSING, -1);

    while (cursor != null && cursor.moveToNext()) {
      int    jobStatus         = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
      String jobRemoteUri      = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_URI));
      long   downloadId        = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID));
      byte[] digest            = getDigestForDownloadId(downloadId);

      if (jobRemoteUri != null && jobRemoteUri.equals(uri) && downloadId == pendingDownloadId) {

        if (jobStatus == DownloadManager.STATUS_SUCCESSFUL    &&
            digest != null && pendingDigest != null           &&
            MessageDigest.isEqual(pendingDigest, theirDigest) &&
            MessageDigest.isEqual(digest, theirDigest))
        {
          return new DownloadStatus(DownloadStatus.Status.COMPLETE, downloadId);
        } else if (jobStatus != DownloadManager.STATUS_SUCCESSFUL) {
          status = new DownloadStatus(DownloadStatus.Status.PENDING, downloadId);
        }
      }
    }

    return status;
  } finally {
    if (cursor != null) cursor.close();
  }
}
 
Example 14
Project: openjdk-jdk10   File: TestSameValue.java   View Source Code Vote up 4 votes
private void run() throws Exception {

        byte[] data = new byte[6706];
        MessageDigest md = null;
        // Initialize input data
        RandomFactory.getRandom().nextBytes(data);

        String[] algorithmArr = { "SHA", "Sha", "MD5", "md5", "SHA-224",
                "SHA-256", "SHA-384", "SHA-512", "SHA3-224", "SHA3-256",
                "SHA3-384", "SHA3-512" };

        for (String algorithm : algorithmArr) {
            try {
                md = MessageDigest.getInstance(algorithm);

                for (UpdateDigestMethod updateMethod : UpdateDigestMethod
                        .values()) {
                    byte[] output = updateMethod.updateDigest(data, md);
                    // Get the output and the "correct" one
                    byte[] standard = md.digest(data);
                    // Compare input and output
                    if (!MessageDigest.isEqual(output, standard)) {
                        throw new RuntimeException(
                                "Test failed at algorithm/provider/numUpdate:"
                                        + algorithm + "/" + md.getProvider()
                                        + "/" + updateMethod);
                    }
                }
            } catch (NoSuchAlgorithmException nae) {
                if (algorithm.startsWith("SHA3") && !isSHA3supported()) {
                    continue;
                } else {
                    throw nae;
                }
            }
        }

        out.println("All "
                + algorithmArr.length * UpdateDigestMethod.values().length
                + " tests Passed");
    }
 
Example 15
Project: jdk8u-jdk   File: SignatureFileVerifier.java   View Source Code Vote up 4 votes
private boolean verifyManifestMainAttrs(Manifest sf,
                                    ManifestDigester md)
     throws IOException, SignatureException
{
    Attributes mattr = sf.getMainAttributes();
    boolean attrsVerified = true;

    // go through all the attributes and process
    // digest entries for the manifest main attributes
    for (Map.Entry<Object,Object> se : mattr.entrySet()) {
        String key = se.getKey().toString();

        if (key.toUpperCase(Locale.ENGLISH).endsWith(ATTR_DIGEST)) {
            String algorithm =
                    key.substring(0, key.length() - ATTR_DIGEST.length());

            MessageDigest digest = getDigest(algorithm);
            if (digest != null) {
                ManifestDigester.Entry mde =
                    md.get(ManifestDigester.MF_MAIN_ATTRS, false);
                byte[] computedHash = mde.digest(digest);
                byte[] expectedHash =
                    Base64.getMimeDecoder().decode((String)se.getValue());

                if (debug != null) {
                 debug.println("Signature File: " +
                                    "Manifest Main Attributes digest " +
                                    digest.getAlgorithm());
                 debug.println( "  sigfile  " + toHex(expectedHash));
                 debug.println( "  computed " + toHex(computedHash));
                 debug.println();
                }

                if (MessageDigest.isEqual(computedHash,
                                          expectedHash)) {
                    // good
                } else {
                    // we will *not* continue and verify each section
                    attrsVerified = false;
                    if (debug != null) {
                        debug.println("Verification of " +
                                    "Manifest main attributes failed");
                        debug.println();
                    }
                    break;
                }
            }
        }
    }

    // this method returns 'true' if either:
    //      . manifest main attributes were not signed, or
    //      . manifest main attributes were signed and verified
    return attrsVerified;
}
 
Example 16
Project: mobile-store   File: JKS.java   View Source Code Vote up 4 votes
public void engineLoad(InputStream in, char[] passwd)
    throws IOException, NoSuchAlgorithmException, CertificateException
{
    MessageDigest md = MessageDigest.getInstance("SHA");
    if (passwd != null) md.update(charsToBytes(passwd));
    md.update("Mighty Aphrodite".getBytes("UTF-8")); // HAR HAR
    aliases.clear();
    trustedCerts.clear();
    privateKeys.clear();
    certChains.clear();
    dates.clear();
    if (in == null) return;
    DataInputStream din = new DataInputStream(new DigestInputStream(in, md));
    if (din.readInt() != MAGIC)
        throw new IOException("not a JavaKeyStore");
    din.readInt();  // version no.
    final int n = din.readInt();
    aliases.ensureCapacity(n);
    if (n < 0)
        throw new LoadKeystoreException("Malformed key store");
    for (int i = 0; i < n; i++)
    {
        int type = din.readInt();
        String alias = din.readUTF();
        aliases.add(alias);
        dates.put(alias, new Date(din.readLong()));
        switch (type)
        {
            case PRIVATE_KEY:
                int len = din.readInt();
                byte[] encoded = new byte[len];
                din.read(encoded);
                privateKeys.put(alias, encoded);
                int count = din.readInt();
                Certificate[] chain = new Certificate[count];
                for (int j = 0; j < count; j++)
                    chain[j] = readCert(din);
                certChains.put(alias, chain);
                break;

            case TRUSTED_CERT:
                trustedCerts.put(alias, readCert(din));
                break;

            default:
                throw new LoadKeystoreException("Malformed key store");
        }
    }

    if (passwd != null) {
        byte[] computedHash = md.digest();
        byte[] storedHash = new byte[20];
        din.read(storedHash);
        if (!MessageDigest.isEqual(storedHash, computedHash)) {
            throw new LoadKeystoreException("Incorrect password, or integrity check failed.");
        }
    }
}
 
Example 17
Project: jdk8u-jdk   File: PBKDF2KeyImpl.java   View Source Code Vote up 4 votes
private static byte[] deriveKey(final Mac prf, final byte[] password,
        byte[] salt, int iterCount, int keyLengthInBit) {
    int keyLength = keyLengthInBit/8;
    byte[] key = new byte[keyLength];
    try {
        int hlen = prf.getMacLength();
        int intL = (keyLength + hlen - 1)/hlen; // ceiling
        int intR = keyLength - (intL - 1)*hlen; // residue
        byte[] ui = new byte[hlen];
        byte[] ti = new byte[hlen];
        // SecretKeySpec cannot be used, since password can be empty here.
        SecretKey macKey = new SecretKey() {
            private static final long serialVersionUID = 7874493593505141603L;
            @Override
            public String getAlgorithm() {
                return prf.getAlgorithm();
            }
            @Override
            public String getFormat() {
                return "RAW";
            }
            @Override
            public byte[] getEncoded() {
                return password;
            }
            @Override
            public int hashCode() {
                return Arrays.hashCode(password) * 41 +
                  prf.getAlgorithm().toLowerCase(Locale.ENGLISH).hashCode();
            }
            @Override
            public boolean equals(Object obj) {
                if (this == obj) return true;
                if (this.getClass() != obj.getClass()) return false;
                SecretKey sk = (SecretKey)obj;
                return prf.getAlgorithm().equalsIgnoreCase(
                    sk.getAlgorithm()) &&
                    MessageDigest.isEqual(password, sk.getEncoded());
            }
        };
        prf.init(macKey);

        byte[] ibytes = new byte[4];
        for (int i = 1; i <= intL; i++) {
            prf.update(salt);
            ibytes[3] = (byte) i;
            ibytes[2] = (byte) ((i >> 8) & 0xff);
            ibytes[1] = (byte) ((i >> 16) & 0xff);
            ibytes[0] = (byte) ((i >> 24) & 0xff);
            prf.update(ibytes);
            prf.doFinal(ui, 0);
            System.arraycopy(ui, 0, ti, 0, ui.length);

            for (int j = 2; j <= iterCount; j++) {
                prf.update(ui);
                prf.doFinal(ui, 0);
                // XOR the intermediate Ui's together.
                for (int k = 0; k < ui.length; k++) {
                    ti[k] ^= ui[k];
                }
            }
            if (i == intL) {
                System.arraycopy(ti, 0, key, (i-1)*hlen, intR);
            } else {
                System.arraycopy(ti, 0, key, (i-1)*hlen, hlen);
            }
        }
    } catch (GeneralSecurityException gse) {
        throw new RuntimeException("Error deriving PBKDF2 keys");
    }
    return key;
}
 
Example 18
Project: googles-monorepo-demo   File: HashCodeBenchmark.java   View Source Code Vote up 4 votes
@Override boolean doEquals(byte[] a, byte[] b) {
  return MessageDigest.isEqual(a, b);
}
 
Example 19
Project: guava-mock   File: HashCodeBenchmark.java   View Source Code Vote up 4 votes
@Override boolean doEquals(byte[] a, byte[] b) {
  return MessageDigest.isEqual(a, b);
}
 
Example 20
Project: jdk8u-jdk   File: MessageToken.java   View Source Code Vote up 4 votes
/**
 * Verifies that the checksum field and sequence number direction bytes
 * are valid and consistent with the application data.
 *
 * @param optionalHeader an optional header that will be processed first
 * during checksum calculation.
 *
 * @param data the application data
 * @param offset the offset where the data begins
 * @param len the length of the application data
 *
 * @param optionalTrailer an optional trailer that will be processed last
 * during checksum calculation. e.g., padding that should be appended to
 * the application data
 *
 * @throws GSSException if an error occurs in the checksum calculation or
 * encryption sequence number calculation.
 */
public final boolean verifySignAndSeqNumber(byte[] optionalHeader,
                                    byte[] data, int offset, int len,
                                    byte[] optionalTrailer)
    throws GSSException {
     // debug("\tIn verifySign:\n");

     // debug("\t\tchecksum:   [" + getHexBytes(checksum) + "]\n");

    byte[] myChecksum =
        getChecksum(optionalHeader, data, offset, len, optionalTrailer);

    // debug("\t\tmychecksum: [" + getHexBytes(myChecksum) +"]\n");
    // debug("\t\tchecksum:   [" + getHexBytes(checksum) + "]\n");

    if (MessageDigest.isEqual(checksum, myChecksum)) {

        seqNumberData = cipherHelper.decryptSeq(
            checksum, encSeqNumber, 0, 8);

        // debug("\t\tencSeqNumber:   [" + getHexBytes(encSeqNumber)
        //  + "]\n");
        // debug("\t\tseqNumberData:   [" + getHexBytes(seqNumberData)
        //  + "]\n");

        /*
         * The token from the initiator has direction bytes 0x00 and
         * the token from the acceptor has direction bytes 0xff.
         */
        byte directionByte = 0;
        if (initiator)
            directionByte = (byte) 0xff; // Received token from acceptor

        if ((seqNumberData[4] == directionByte) &&
              (seqNumberData[5] == directionByte) &&
              (seqNumberData[6] == directionByte) &&
              (seqNumberData[7] == directionByte))
            return true;
    }

    return false;

}