Example usage for org.bouncycastle.crypto.signers HMacDSAKCalculator HMacDSAKCalculator

List of usage examples for org.bouncycastle.crypto.signers HMacDSAKCalculator HMacDSAKCalculator

Introduction

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

Prototype

public HMacDSAKCalculator(Digest digest) 

Source Link

Document

Base constructor.

Usage

From source file:com.facebook.delegatedrecovery.RecoveryToken.java

License:Open Source License

private byte[] getSignature(final byte[] rawArray, final ECPrivateKey privateKey) throws IOException {
    if (this.signature != null) {
        throw new IllegalStateException("This token already has a signature.");
    }/*from w w w  . j  a  v  a  2s . c o  m*/
    final BigInteger privatePoint = privateKey.getS();

    final SHA256Digest digest = new SHA256Digest();
    final byte[] hash = new byte[digest.getByteLength()];
    digest.update(rawArray, 0, rawArray.length);
    digest.doFinal(hash, 0);

    final ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    signer.init(true, new ECPrivateKeyParameters(privatePoint, DelegatedRecoveryUtils.P256_DOMAIN_PARAMS));
    final BigInteger[] signature = signer.generateSignature(hash);
    final ByteArrayOutputStream s = new ByteArrayOutputStream();
    final DERSequenceGenerator seq = new DERSequenceGenerator(s);
    seq.addObject(new ASN1Integer(signature[0]));
    seq.addObject(new ASN1Integer(signature[1]));
    seq.close();

    return s.toByteArray();
}

From source file:COSE.SignCommon.java

byte[] computeSignature(byte[] rgbToBeSigned, CipherParameters key) throws CoseException {
    AlgorithmID alg = AlgorithmID.FromCBOR(findAttribute(HeaderKeys.Algorithm));
    Digest digest;/* w  ww .ja va  2 s  .c om*/
    CBORObject cn;
    switch (alg) {
    case ECDSA_256:
        digest = new SHA256Digest();
        break;

    case ECDSA_384:
        digest = new SHA384Digest();
        break;

    case ECDSA_512:
        digest = new SHA512Digest();
        break;

    default:
        throw new CoseException("Unsupported Algorithm Specified");
    }

    switch (alg) {
    case ECDSA_256:
    case ECDSA_384:
    case ECDSA_512: {
        digest.update(rgbToBeSigned, 0, rgbToBeSigned.length);
        byte[] rgbDigest = new byte[digest.getDigestSize()];
        digest.doFinal(rgbDigest, 0);

        ECDSASigner ecdsa = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
        ecdsa.init(true, key);
        BigInteger[] sig = ecdsa.generateSignature(rgbDigest);

        int cb = (((ECPrivateKeyParameters) key).getParameters().getCurve().getFieldSize() + 7) / 8;
        byte[] r = sig[0].toByteArray();
        byte[] s = sig[1].toByteArray();

        byte[] sigs = new byte[cb * 2];
        int cbR = min(cb, r.length);
        System.arraycopy(r, r.length - cbR, sigs, cb - cbR, cbR);
        cbR = min(cb, s.length);
        System.arraycopy(s, s.length - cbR, sigs, cb + cb - cbR, cbR);

        return sigs;

    }

    default:
        throw new CoseException("Inernal error");
    }
}

From source file:freenet.keys.InsertableClientSSK.java

License:GNU General Public License

public ClientSSKBlock encode(Bucket sourceData, boolean asMetadata, boolean dontCompress,
        short alreadyCompressedCodec, long sourceLength, RandomSource r, String compressordescriptor,
        boolean pre1254) throws SSKEncodeException, IOException, InvalidCompressionCodecException {
    byte[] compressedData;
    short compressionAlgo;
    try {//from  w ww . java  2 s  .c o  m
        Compressed comp = Key.compress(sourceData, dontCompress, alreadyCompressedCodec, sourceLength,
                ClientSSKBlock.MAX_DECOMPRESSED_DATA_LENGTH, SSKBlock.DATA_LENGTH, true, compressordescriptor,
                pre1254);
        compressedData = comp.compressedData;
        compressionAlgo = comp.compressionAlgorithm;
    } catch (KeyEncodeException e) {
        throw new SSKEncodeException(e.getMessage(), e);
    }
    // Pad it
    MessageDigest md256 = SHA256.getMessageDigest();
    try {
        byte[] data;
        // First pad it
        if (compressedData.length != SSKBlock.DATA_LENGTH) {
            // Hash the data
            if (compressedData.length != 0)
                md256.update(compressedData);
            byte[] digest = md256.digest();
            MersenneTwister mt = new MersenneTwister(digest);
            data = Arrays.copyOf(compressedData, SSKBlock.DATA_LENGTH);
            if (compressedData.length > data.length) {
                throw new RuntimeException(
                        "compressedData.length = " + compressedData.length + " but data.length=" + data.length);
            }
            Util.randomBytes(mt, data, compressedData.length, SSKBlock.DATA_LENGTH - compressedData.length);
        } else {
            data = compressedData;
        }

        // Implicit hash of data
        byte[] origDataHash = md256.digest(data);

        Rijndael aes;
        try {
            aes = new Rijndael(256, 256);
        } catch (UnsupportedCipherException e) {
            throw new Error("256/256 Rijndael not supported!");
        }

        // Encrypt data. Data encryption key = H(plaintext data).

        aes.initialize(origDataHash);
        PCFBMode pcfb = PCFBMode.create(aes, origDataHash);

        pcfb.blockEncipher(data, 0, data.length);

        byte[] encryptedDataHash = md256.digest(data);

        // Create headers

        byte[] headers = new byte[SSKBlock.TOTAL_HEADERS_LENGTH];
        // First two bytes = hash ID
        int x = 0;
        headers[x++] = (byte) (KeyBlock.HASH_SHA256 >> 8);
        headers[x++] = (byte) (KeyBlock.HASH_SHA256);
        // Then crypto ID
        headers[x++] = (byte) (Key.ALGO_AES_PCFB_256_SHA256 >> 8);
        headers[x++] = Key.ALGO_AES_PCFB_256_SHA256;
        // Then E(H(docname))
        // Copy to headers
        System.arraycopy(ehDocname, 0, headers, x, ehDocname.length);
        x += ehDocname.length;
        // Now the encrypted headers
        byte[] encryptedHeaders = Arrays.copyOf(origDataHash, SSKBlock.ENCRYPTED_HEADERS_LENGTH);
        int y = origDataHash.length;
        short len = (short) compressedData.length;
        if (asMetadata)
            len |= 32768;
        encryptedHeaders[y++] = (byte) (len >> 8);
        encryptedHeaders[y++] = (byte) len;
        encryptedHeaders[y++] = (byte) (compressionAlgo >> 8);
        encryptedHeaders[y++] = (byte) compressionAlgo;
        if (encryptedHeaders.length != y)
            throw new IllegalStateException("Have more bytes to generate encoding SSK");
        aes.initialize(cryptoKey);
        pcfb.reset(ehDocname);
        pcfb.blockEncipher(encryptedHeaders, 0, encryptedHeaders.length);
        System.arraycopy(encryptedHeaders, 0, headers, x, encryptedHeaders.length);
        x += encryptedHeaders.length;
        // Generate implicit overall hash.
        md256.update(headers, 0, x);
        md256.update(encryptedDataHash);
        byte[] overallHash = md256.digest();
        // Now sign it
        DSASigner dsa = new DSASigner(new HMacDSAKCalculator(new SHA256Digest()));
        dsa.init(true, new DSAPrivateKeyParameters(privKey.getX(), Global.getDSAgroupBigAParameters()));
        BigInteger[] sig = dsa.generateSignature(Global.truncateHash(overallHash));
        // Pack R and S into 32 bytes each, and copy to headers.
        // Then create and return the ClientSSKBlock.
        byte[] rBuf = truncate(sig[0].toByteArray(), SSKBlock.SIG_R_LENGTH);
        byte[] sBuf = truncate(sig[1].toByteArray(), SSKBlock.SIG_S_LENGTH);
        System.arraycopy(rBuf, 0, headers, x, rBuf.length);
        x += rBuf.length;
        System.arraycopy(sBuf, 0, headers, x, sBuf.length);
        x += sBuf.length;
        if (x != SSKBlock.TOTAL_HEADERS_LENGTH)
            throw new IllegalStateException("Too long");
        try {
            return new ClientSSKBlock(data, headers, this, !logMINOR);
        } catch (SSKVerifyException e) {
            throw (AssertionError) new AssertionError("Impossible encoding error").initCause(e);
        }
    } finally {
        SHA256.returnMessageDigest(md256);
    }
}

From source file:me.grapebaba.hyperledger.fabric.Crypto.java

License:Apache License

public BigInteger[] ecdsaSign(PrivateKey privateKey, ByteString message) {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(digest));
    ECPrivateKeyParameters ecdhPrivateKeyParameters;
    try {//from  ww  w . ja  v a 2s . c  om
        ecdhPrivateKeyParameters = (ECPrivateKeyParameters) (PrivateKeyFactory
                .createKey(privateKey.getEncoded()));
    } catch (IOException e) {
        logger.error("ECDSA sign load private key exception", e);
        throw new RuntimeException(e);
    }
    signer.init(true, ecdhPrivateKeyParameters);
    return signer.generateSignature(message.toByteArray());
}

From source file:org.ethereum.crypto.ECKey.java

License:Open Source License

/**
 * Signs the given hash and returns the R and S components as BigIntegers
 * and put them in ECDSASignature/*ww  w  . ja  v  a2 s. com*/
 *
 * @param input to sign
 * @return ECDSASignature signature that contains the R and S components
 */
public ECDSASignature doSign(byte[] input) {
    // No decryption of private key required.
    if (priv == null) {
        throw new MissingPrivateKeyException();
    }
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(priv, CURVE);
    signer.init(true, privKey);
    BigInteger[] components = signer.generateSignature(input);
    return new ECDSASignature(components[0], components[1]).toCanonicalised();
}

From source file:org.hyperledger.common.BouncyCastleCrypto.java

License:Apache License

@Override
public byte[] sign(byte[] hash, byte[] privateKey) {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    signer.init(true, new ECPrivateKeyParameters(new BigInteger(privateKey), domain));
    BigInteger[] signature = signer.generateSignature(hash);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {//from   w ww  . j  a  v a 2  s.c om
        DERSequenceGenerator seq = new DERSequenceGenerator(baos);
        seq.addObject(new ASN1Integer(signature[0]));
        seq.addObject(new ASN1Integer(toCanonicalS(signature[1])));
        seq.close();
        return baos.toByteArray();
    } catch (IOException e) {
        return new byte[0];
    }
}

From source file:org.hyperledger.common.PrivateKey.java

License:Apache License

/**
 * Sign a digest with this key.//from  w  w w  .  j  av  a  2 s. c om
 *
 * @param hash arbitrary data
 * @return signature
 */
public byte[] sign(byte[] hash) {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    signer.init(true, new ECPrivateKeyParameters(priv, domain));
    BigInteger[] signature = signer.generateSignature(hash);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        DERSequenceGenerator seq = new DERSequenceGenerator(baos);
        seq.addObject(new ASN1Integer(signature[0]));
        seq.addObject(new ASN1Integer(toCanonicalS(signature[1])));
        seq.close();
        return baos.toByteArray();
    } catch (IOException e) {
    }
    return null;
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

License:Open Source License

public byte[][] ecdsaSign(PrivateKey privateKey, byte[] data) throws CryptoException {
    try {//from  w  w  w. j a v  a 2  s. co m
        byte[] encoded = hash(data);
        X9ECParameters params = SECNamedCurves.getByName(this.curveName);
        ECDomainParameters ecParams = new ECDomainParameters(params.getCurve(), params.getG(), params.getN(),
                params.getH());

        ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA512Digest()));
        ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(((ECPrivateKey) privateKey).getS(),
                ecParams);
        signer.init(true, privKey);
        BigInteger[] sigs = signer.generateSignature(encoded);
        return new byte[][] { sigs[0].toString().getBytes(UTF_8), sigs[1].toString().getBytes(UTF_8) };
    } catch (Exception e) {
        throw new CryptoException("Could not sign the message using private key", e);
    }

}

From source file:org.ScripterRon.BitcoinCore.ECKey.java

License:Apache License

/**
 * Creates a signature for the supplied contents using the private key
 *
 * @param       contents                Contents to be signed
 * @return                              ECDSA signature
 * @throws      ECException             Unable to create signature
 *///from  w w  w .  j  av  a 2 s.c  o m
public ECDSASignature createSignature(byte[] contents) throws ECException {
    if (privKey == null)
        throw new IllegalStateException("No private key available");
    //
    // Get the double SHA-256 hash of the signed contents
    //
    byte[] contentsHash = Utils.doubleDigest(contents);
    //
    // Create the signature
    //
    BigInteger[] sigs;
    try {
        ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
        ECPrivateKeyParameters privKeyParams = new ECPrivateKeyParameters(privKey, ecParams);
        signer.init(true, privKeyParams);
        sigs = signer.generateSignature(contentsHash);
    } catch (RuntimeException exc) {
        throw new ECException("Exception while creating signature", exc);
    }
    //
    // Create a canonical signature by adjusting the S component to be less than or equal to
    // half the curve order.
    //
    if (sigs[1].compareTo(HALF_CURVE_ORDER) > 0)
        sigs[1] = ecParams.getN().subtract(sigs[1]);
    return new ECDSASignature(sigs[0], sigs[1]);
}