Example usage for org.bouncycastle.crypto.signers DSASigner verifySignature

List of usage examples for org.bouncycastle.crypto.signers DSASigner verifySignature

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.signers DSASigner verifySignature.

Prototype

public boolean verifySignature(byte[] message, BigInteger r, BigInteger s) 

Source Link

Document

return true if the value r and s represent a DSA signature for the passed in message for standard DSA the message should be a SHA-1 hash of the real message to be verified.

Usage

From source file:dorkbox.util.crypto.CryptoDSA.java

License:Apache License

/**
 * The message will have the SHA1 hash calculated and used for the signature.
 * <p/>/*from w w w .  j  a  v  a 2s .  c  o m*/
 * Note: this is here just for keeping track of how this is done. This should NOT be used, and instead use ECC crypto.
 *
 * @param signature
 *                 is the {r,s} signature array.
 *
 * @return true if the signature is valid
 */
public static boolean verifySignature(DSAPublicKeyParameters publicKey, byte[] message,
        BigInteger[] signature) {
    SHA1Digest sha1Digest = new SHA1Digest();
    byte[] checksum = new byte[sha1Digest.getDigestSize()];

    sha1Digest.update(message, 0, message.length);
    sha1Digest.doFinal(checksum, 0);

    DSASigner dsa = new DSASigner();

    dsa.init(false, publicKey);

    return dsa.verifySignature(checksum, signature[0], signature[1]);
}

From source file:freenet.keys.SSKBlock.java

License:GNU General Public License

/**
 * Initialize, and verify data, headers against key. Provided
 * key must have a pubkey, or we throw.//from ww w  .j  av a2s .  c o  m
 */
public SSKBlock(byte[] data, byte[] headers, NodeSSK nodeKey, boolean dontVerify) throws SSKVerifyException {
    if (headers.length != TOTAL_HEADERS_LENGTH)
        throw new IllegalArgumentException(
                "Headers.length=" + headers.length + " should be " + TOTAL_HEADERS_LENGTH);
    this.data = data;
    this.headers = headers;
    this.nodeKey = nodeKey;
    if (data.length != DATA_LENGTH)
        throw new SSKVerifyException("Data length wrong: " + data.length + " should be " + DATA_LENGTH);
    this.pubKey = nodeKey.getPubKey();
    if (pubKey == null)
        throw new SSKVerifyException("PubKey was null from " + nodeKey);
    // Now verify it
    hashIdentifier = (short) (((headers[0] & 0xff) << 8) + (headers[1] & 0xff));
    if (hashIdentifier != HASH_SHA256)
        throw new SSKVerifyException("Hash not SHA-256");
    int x = 2;
    symCipherIdentifier = (short) (((headers[x] & 0xff) << 8) + (headers[x + 1] & 0xff));
    x += 2;
    // Then E(H(docname))
    byte[] ehDocname = new byte[E_H_DOCNAME_LENGTH];
    System.arraycopy(headers, x, ehDocname, 0, ehDocname.length);
    x += E_H_DOCNAME_LENGTH;
    headersOffset = x; // is index to start of encrypted headers
    x += ENCRYPTED_HEADERS_LENGTH;
    // Extract the signature
    if (x + SIG_R_LENGTH + SIG_S_LENGTH > headers.length)
        throw new SSKVerifyException("Headers too short: " + headers.length + " should be at least " + x
                + SIG_R_LENGTH + SIG_S_LENGTH);
    // Compute the hash on the data
    if (!dontVerify || logMINOR) { // force verify on log minor
        byte[] bufR = new byte[SIG_R_LENGTH];
        byte[] bufS = new byte[SIG_S_LENGTH];

        System.arraycopy(headers, x, bufR, 0, SIG_R_LENGTH);
        x += SIG_R_LENGTH;
        System.arraycopy(headers, x, bufS, 0, SIG_S_LENGTH);
        x += SIG_S_LENGTH;

        MessageDigest md = null;
        byte[] overallHash;
        try {
            md = SHA256.getMessageDigest();
            md.update(data);
            byte[] dataHash = md.digest();
            // All headers up to and not including the signature
            md.update(headers, 0, headersOffset + ENCRYPTED_HEADERS_LENGTH);
            // Then the implicit data hash
            md.update(dataHash);
            // Makes the implicit overall hash
            overallHash = md.digest();
        } finally {
            SHA256.returnMessageDigest(md);
        }

        // Now verify it
        BigInteger r = new BigInteger(1, bufR);
        BigInteger s = new BigInteger(1, bufS);
        DSASigner dsa = new DSASigner();
        dsa.init(false, new DSAPublicKeyParameters(pubKey.getY(), Global.getDSAgroupBigAParameters()));

        // We probably don't need to try both here...
        // but that's what the legacy code was doing...
        // @see comments in Global before touching it
        if (!(dsa.verifySignature(Global.truncateHash(overallHash), r, s)
                || dsa.verifySignature(overallHash, r, s))) {
            if (dontVerify)
                Logger.error(this, "DSA verification failed with dontVerify!!!!");
            throw new SSKVerifyException("Signature verification failed for node-level SSK");
        }
    } // x isn't verified otherwise so no need to += SIG_R_LENGTH + SIG_S_LENGTH
    if (!Arrays.equals(ehDocname, nodeKey.encryptedHashedDocname))
        throw new SSKVerifyException(
                "E(H(docname)) wrong - wrong key?? \nfrom headers: " + HexUtil.bytesToHex(ehDocname)
                        + "\nfrom key:     " + HexUtil.bytesToHex(nodeKey.encryptedHashedDocname));
    hashCode = Fields.hashCode(data) ^ Fields.hashCode(headers) ^ nodeKey.hashCode() ^ pubKey.hashCode()
            ^ hashIdentifier;
}

From source file:net.java.otr4j.crypto.DSAKeyPair.java

License:LGPL

/**
 * Verify a message using a signature represented as two MPI components: 'r' and 's'.
 *
 * @param b      the message in bytes/*w ww.j a v a2s  .  c  om*/
 * @param pubKey the DSA public key
 * @param r      the signature component 'r'
 * @param s      the signature component 's'
 * @throws OtrCryptoException In case of illegal signature.
 */
public static void verifySignature(final byte[] b, final DSAPublicKey pubKey, final BigInteger r,
        final BigInteger s) throws OtrCryptoException {
    requireNonNull(b);
    assert !allZeroBytes(
            b) : "Expected non-zero bytes for b. This may indicate that a critical bug is present, or it may be a false warning.";
    final DSAParams dsaParams = pubKey.getParams();
    final BigInteger q = dsaParams.getQ();
    final DSAParameters bcDSAParams = new DSAParameters(dsaParams.getP(), q, dsaParams.getG());
    final DSAPublicKeyParameters dsaPubParams;
    try {
        dsaPubParams = new DSAPublicKeyParameters(pubKey.getY(), bcDSAParams);
    } catch (final IllegalArgumentException e) {
        throw new OtrCryptoException("Illegal parameters provided for DSA public key parameters.", e);
    }

    // Ian: Note that if you can get the standard DSA implementation you're
    // using to not hash its input, you should be able to pass it ((256-bit
    // value) mod q), (rather than truncating the 256-bit value) and all
    // should be well.
    // ref: Interop problems with libotr - DSA signature
    final DSASigner dsaSigner = new DSASigner();
    dsaSigner.init(false, dsaPubParams);

    final BigInteger bmpi = new BigInteger(1, b);
    if (!dsaSigner.verifySignature(asUnsignedByteArray(bmpi.mod(q)), r, s)) {
        throw new OtrCryptoException("DSA signature verification failed.");
    }
}

From source file:net.java.otr4j.crypto.OtrCryptoEngineImpl.java

License:Apache License

private Boolean verify(byte[] b, PublicKey pubKey, BigInteger r, BigInteger s) throws OtrCryptoException {
    if (!(pubKey instanceof DSAPublicKey))
        throw new IllegalArgumentException();

    DSAParams dsaParams = ((DSAPublicKey) pubKey).getParams();

    BigInteger q = dsaParams.getQ();
    DSAParameters bcDSAParams = new DSAParameters(dsaParams.getP(), q, dsaParams.getG());

    DSAPublicKey dsaPrivateKey = (DSAPublicKey) pubKey;
    DSAPublicKeyParameters dsaPrivParms = new DSAPublicKeyParameters(dsaPrivateKey.getY(), bcDSAParams);

    // Ian: Note that if you can get the standard DSA implementation you're
    // using to not hash its input, you should be able to pass it ((256-bit
    // value) mod q), (rather than truncating the 256-bit value) and all
    // should be well.
    // ref: Interop problems with libotr - DSA signature
    DSASigner dsaSigner = new DSASigner();
    dsaSigner.init(false, dsaPrivParms);

    BigInteger bmpi = new BigInteger(1, b);
    Boolean result = dsaSigner.verifySignature(BigIntegers.asUnsignedByteArray(bmpi.mod(q)), r, s);
    return result;
}

From source file:org.cryptacular.util.KeyPairUtil.java

License:Open Source License

/**
 * Determines whether the given DSA public and private keys form a proper key
 * pair by computing and verifying a digital signature with the keys.
 *
 * @param  pubKey  DSA public key.//from ww  w  .  j av a  2s  .c o  m
 * @param  privKey  DSA private key.
 *
 * @return  True if the keys form a functioning keypair, false otherwise.
 *          Errors during signature verification are treated as false.
 */
public static boolean isKeyPair(final DSAPublicKey pubKey, final DSAPrivateKey privKey) {
    final DSASigner signer = new DSASigner();
    final DSAParameters params = new DSAParameters(privKey.getParams().getP(), privKey.getParams().getQ(),
            privKey.getParams().getG());
    signer.init(true, new DSAPrivateKeyParameters(privKey.getX(), params));

    final BigInteger[] sig = signer.generateSignature(SIGN_BYTES);
    signer.init(false, new DSAPublicKeyParameters(pubKey.getY(), params));
    try {
        return signer.verifySignature(SIGN_BYTES, sig[0], sig[1]);
    } catch (Exception e) {
        return false;
    }
}