Example usage for org.bouncycastle.crypto.params ParametersWithRandom ParametersWithRandom

List of usage examples for org.bouncycastle.crypto.params ParametersWithRandom ParametersWithRandom

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.params ParametersWithRandom ParametersWithRandom.

Prototype

public ParametersWithRandom(CipherParameters parameters, SecureRandom random) 

Source Link

Usage

From source file:de.tntinteractive.portalsammler.engine.CryptoHelper.java

License:Open Source License

private static PaddedBufferedBlockCipher initAes(final byte[] key, final SecureRandom srand,
        final boolean forEncryption) {
    final CipherParameters cipherParams = new ParametersWithRandom(new KeyParameter(key), srand);

    final AESFastEngine aes = new AESFastEngine();
    final PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(aes));
    cipher.init(forEncryption, cipherParams);
    return cipher;
}

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/>// w ww .j ava  2 s . com
 * Note: this is here just for keeping track of how this is done. This should NOT be used, and instead use ECC crypto.
 * <p/>
 * The returned signature is the {r,s} signature array.
 */
public static BigInteger[] generateSignature(DSAPrivateKeyParameters privateKey, SecureRandom secureRandom,
        byte[] message) {
    ParametersWithRandom param = new ParametersWithRandom(privateKey, secureRandom);

    DSASigner dsa = new DSASigner();

    dsa.init(true, param);

    SHA1Digest sha1Digest = new SHA1Digest();
    byte[] checksum = new byte[sha1Digest.getDigestSize()];

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

    return dsa.generateSignature(checksum);
}

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

License:Apache License

/**
 * The message will use the bytes AS THE HASHED VALUE to calculate the signature.
 * <p/>/*from  w ww  .j ava  2s.  c o m*/
 * The returned signature is the {r,s} signature array.
 */
public static BigInteger[] generateSignatureForHash(ECPrivateKeyParameters privateKey,
        SecureRandom secureRandom, byte[] hashBytes) {

    ParametersWithRandom param = new ParametersWithRandom(privateKey, secureRandom);

    ECDSASigner ecdsa = new ECDSASigner();
    ecdsa.init(true, param);

    return ecdsa.generateSignature(hashBytes);
}

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

License:Apache License

@Test
public void EccDsa() throws IOException {
    SecureRandom secureRandom = new SecureRandom();

    AsymmetricCipherKeyPair key1 = CryptoECC.generateKeyPair(CryptoECC.default_curve, secureRandom);

    ParametersWithRandom param = new ParametersWithRandom(key1.getPrivate(), new SecureRandom());

    ECDSASigner ecdsa = new ECDSASigner();

    ecdsa.init(true, param);/* w  ww  .  ja v a 2 s  .c o m*/

    byte[] message = new BigInteger("345234598734987394672039478602934578").toByteArray();
    BigInteger[] sig = ecdsa.generateSignature(message);

    ecdsa.init(false, key1.getPublic());

    if (!ecdsa.verifySignature(message, sig[0], sig[1])) {
        fail("ECDSA signature fails");
    }
}

From source file:edu.biu.scapi.tools.Translation.BCParametersTranslator.java

License:Open Source License

/** 
 * Translates the key and the source of randomness into a CipherParameter of BC. If one of the arguments is null then 
 * pass to one of the other two translateParameter functions.
 * @param key the Key to translate to CipherParameters of BC
 * @param random the source of randomness to translate
 *///from  ww  w.  j ava 2 s .c o  m
public CipherParameters translateParameter(Key key, SecureRandom random) {
    /*
     * Note - because the translation of a Key to KeySpec is different in each algorithm (some have KeyFactory, some doesn't),
     * the translation must be specific to the algorithm of the key.
     * So, although the reasonable parameter to this function is KeySpec, we decided to get a Key instead.
     * This way the classes that call this function don't need to behave differently in each key type.
     * In the current implementation, there is no difference between getting KeySpec and Key, 
     * because the current keys we translate are SecretKey that have just the encoded byte array and RSA key that has get functions in the RSAKey interface.
     * Id we will need to translate other keys that require translation to KeySpec, we will add it specifically.
     * 
     */
    if (random == null) {
        return translateParameter(key);
    } else {

        //get the cipher parameter with the key.
        CipherParameters keyparam = translateParameter(key);

        //pass the key and the random
        return new ParametersWithRandom(keyparam, random);

    }

}

From source file:edu.vt.middleware.crypt.signature.AbstractDSASignature.java

License:Open Source License

/**
 * Initialize the signer./*from   ww w .jav a2  s .  c o  m*/
 *
 * @param  forSigning  Whether to initialize signer for the sign operation.
 * @param  params  BC cipher parameters.
 */
protected void init(final boolean forSigning, final CipherParameters params) {
    if (forSigning && randomProvider != null) {
        signer.init(forSigning, new ParametersWithRandom(params, randomProvider));
    } else {
        signer.init(forSigning, params);
    }
}

From source file:edu.vt.middleware.crypt.signature.RSASignature.java

License:Open Source License

/**
 * Initialize the signer.//ww w.ja  va 2s  .c om
 *
 * @param  forSigning  Whether to initialize signer for the sign operation.
 * @param  params  BC cipher parameters.
 */
protected void init(final boolean forSigning, final CipherParameters params) {
    if (randomProvider != null) {
        signer.init(forSigning, new ParametersWithRandom(params, randomProvider));
    } else {
        signer.init(forSigning, params);
    }
}

From source file:org.cryptoworkshop.ximix.node.crypto.test.BasicShamirSharingTest.java

License:Apache License

private void doTest(ECDomainParameters domainParams, AsymmetricCipherKeyPair[] kps, int threshold,
        boolean shouldPass, int... missing) {
    int numberOfPeers = kps.length;

    // create the splitter for the peers/threshold over the order of the curve.
    ShamirSecretSplitter secretSplitter = new ShamirSecretSplitter(numberOfPeers, threshold,
            domainParams.getN(), new SecureRandom());

    // Having created a private key the server creates shares of that
    // private key. It would keep one share for itself and sends the others
    // shares to the other servers.
    BigInteger[][] privateKeyShares = new BigInteger[numberOfPeers][];
    BigInteger[] finalPrivateKeyShares = new BigInteger[numberOfPeers];
    for (int i = 0; i < numberOfPeers; i++) {
        privateKeyShares[i] = secretSplitter.split(((ECPrivateKeyParameters) kps[i].getPrivate()).getD())
                .getShares();//from  w  ww .j  ava 2 s  . c  o  m
    }

    // Simulates distributing shares and combining them
    for (int i = 0; i < numberOfPeers; i++) {
        finalPrivateKeyShares[i] = privateKeyShares[0][i];
        for (int j = 1; j < numberOfPeers; j++) {
            finalPrivateKeyShares[i] = finalPrivateKeyShares[i].add(privateKeyShares[j][i]);
        }
    }

    ECPoint pubPoint = ((ECPublicKeyParameters) kps[0].getPublic()).getQ();

    for (int i = 1; i < numberOfPeers; i++) {
        pubPoint = pubPoint.add(((ECPublicKeyParameters) kps[i].getPublic()).getQ());
    }

    ECPublicKeyParameters jointPub = new ECPublicKeyParameters(pubPoint, domainParams);

    // Create a random plaintext
    ECPoint plaintext = generatePoint(domainParams, new SecureRandom());

    // Encrypt it using the joint public key
    ECEncryptor enc = new ECElGamalEncryptor();

    enc.init(new ParametersWithRandom(jointPub, new SecureRandom()));

    ECPair cipherText = enc.encrypt(plaintext);

    // do partial decrypts
    ECPoint[] partialDecs = new ECPoint[numberOfPeers];

    for (int i = 0; i < numberOfPeers; i++) {
        partialDecs[i] = cipherText.getX().multiply(finalPrivateKeyShares[i]);
    }

    // simulate missing peers
    for (int i = 0; i != missing.length; i++) {
        partialDecs[missing[i]] = null;
    }

    // decryption step
    LagrangeWeightCalculator lagrangeWeightCalculator = new LagrangeWeightCalculator(numberOfPeers,
            domainParams.getN());

    BigInteger[] weights = lagrangeWeightCalculator.computeWeights(partialDecs);

    // weighting
    ECPoint weightedDecryption = partialDecs[0].multiply(weights[0]);
    for (int i = 1; i < weights.length; i++) {
        if (partialDecs[i] != null) {
            weightedDecryption = weightedDecryption.add(partialDecs[i].multiply(weights[i]));
        }
    }

    // Do final decryption to recover plaintext ECPoint
    ECPoint decrypted = cipherText.getY().add(weightedDecryption.negate());

    Assert.assertEquals(shouldPass, plaintext.equals(decrypted));
}

From source file:org.cryptoworkshop.ximix.node.crypto.test.NewDKGTest.java

License:Apache License

private void doTest(ECDomainParameters domainParams, AsymmetricCipherKeyPair[] kps, int threshold,
        boolean shouldPass, int... missing) {
    int numberOfPeers = kps.length;

    // create the splitter for the peers/threshold over the order of the curve.
    ECPoint hVal = domainParams.getG().multiply(getRandomInteger(domainParams.getN(), new SecureRandom()));
    ECNewDKGSecretSplitter secretSplitter = new ECNewDKGSecretSplitter(numberOfPeers, threshold, hVal,
            domainParams, new SecureRandom());

    // Having created a private key the server creates shares of that
    // private key. It would keep one share for itself and sends the others
    // shares to the other servers.
    ECCommittedSplitSecret[] privateKeyShares = new ECCommittedSplitSecret[numberOfPeers];
    BigInteger[] finalPrivateKeyShares = new BigInteger[numberOfPeers];
    for (int i = 0; i < numberOfPeers; i++) {
        privateKeyShares[i] = secretSplitter.split(((ECPrivateKeyParameters) kps[i].getPrivate()).getD());
    }//from ww w  . ja  v a  2 s . com

    // Simulates distributing shares and combining them
    for (int i = 0; i < numberOfPeers; i++) {
        finalPrivateKeyShares[i] = privateKeyShares[0].getShares()[i];
        for (int j = 1; j < numberOfPeers; j++) {
            finalPrivateKeyShares[i] = finalPrivateKeyShares[i].add(privateKeyShares[j].getShares()[i]);
        }
    }

    //
    // check the commitment values.
    //
    for (int i = 0; i != numberOfPeers; i++) {
        ECCommittedSecretShare[] shares = privateKeyShares[i].getCommittedShares();
        for (int j = 0; j != numberOfPeers; j++) {
            Assert.assertTrue(shares[j].isRevealed(j, domainParams, hVal));
        }
    }

    ECPoint pubPoint = ((ECPublicKeyParameters) kps[0].getPublic()).getQ();

    for (int i = 1; i < numberOfPeers; i++) {
        pubPoint = pubPoint.add(((ECPublicKeyParameters) kps[i].getPublic()).getQ());
    }

    ECPublicKeyParameters jointPub = new ECPublicKeyParameters(pubPoint, domainParams);

    //
    // check the public key commitment values.
    //
    for (int i = 0; i != numberOfPeers; i++) {
        BigInteger[] aCoefficients = privateKeyShares[i].getCoefficients();
        ECPoint[] qCommitments = new ECPoint[aCoefficients.length];

        for (int k = 0; k != qCommitments.length; k++) {
            qCommitments[k] = domainParams.getG().multiply(aCoefficients[k]);
        }

        for (int j = 0; j != numberOfPeers; j++) {
            ECPoint val = qCommitments[0];
            for (int k = 1; k != qCommitments.length; k++) {
                val = val.add(qCommitments[k].multiply(BigInteger.valueOf(j + 1).pow(k)));
            }

            Assert.assertEquals(domainParams.getG().multiply(privateKeyShares[i].getShares()[j]), val);
        }
    }

    // Create a random plaintext
    ECPoint plaintext = generatePoint(domainParams, new SecureRandom());

    // Encrypt it using the joint public key
    ECEncryptor enc = new ECElGamalEncryptor();

    enc.init(new ParametersWithRandom(jointPub, new SecureRandom()));

    ECPair cipherText = enc.encrypt(plaintext);

    // do partial decrypts
    ECPoint[] partialDecs = new ECPoint[numberOfPeers];

    for (int i = 0; i < numberOfPeers; i++) {
        partialDecs[i] = cipherText.getX().multiply(finalPrivateKeyShares[i]);
    }

    // simulate missing peers
    for (int i = 0; i != missing.length; i++) {
        partialDecs[missing[i]] = null;
    }

    // decryption step
    LagrangeWeightCalculator lagrangeWeightCalculator = new LagrangeWeightCalculator(numberOfPeers,
            domainParams.getN());

    BigInteger[] weights = lagrangeWeightCalculator.computeWeights(partialDecs);

    // weighting
    ECPoint weightedDecryption = partialDecs[0].multiply(weights[0]);
    for (int i = 1; i < weights.length; i++) {
        if (partialDecs[i] != null) {
            weightedDecryption = weightedDecryption.add(partialDecs[i].multiply(weights[i]));
        }
    }

    // Do final decryption to recover plaintext ECPoint
    ECPoint decrypted = cipherText.getY().add(weightedDecryption.negate());

    Assert.assertEquals(shouldPass, plaintext.equals(decrypted));
}

From source file:org.xipki.commons.security.pkcs11.P11RSAPSSContentSigner.java

License:Open Source License

P11RSAPSSContentSigner(final P11CryptService cryptService, final P11EntityIdentifier identityId,
        final AlgorithmIdentifier signatureAlgId, final SecureRandom random)
        throws XiSecurityException, P11TokenException {
    this.cryptService = ParamUtil.requireNonNull("cryptService", cryptService);
    this.identityId = ParamUtil.requireNonNull("identityId", identityId);
    this.algorithmIdentifier = ParamUtil.requireNonNull("signatureAlgId", signatureAlgId);
    ParamUtil.requireNonNull("random", random);

    if (!PKCSObjectIdentifiers.id_RSASSA_PSS.equals(signatureAlgId.getAlgorithm())) {
        throw new XiSecurityException("unsupported signature algorithm " + signatureAlgId.getAlgorithm());
    }//from  w  w  w. j  av  a  2 s .  c o m

    RSASSAPSSparams asn1Params = RSASSAPSSparams.getInstance(signatureAlgId.getParameters());
    ASN1ObjectIdentifier digestAlgOid = asn1Params.getHashAlgorithm().getAlgorithm();
    HashAlgoType hashAlgo = HashAlgoType.getHashAlgoType(digestAlgOid);
    if (hashAlgo == null) {
        throw new XiSecurityException("unsupported hash algorithm " + digestAlgOid.getId());
    }

    P11SlotIdentifier slotId = identityId.getSlotId();
    P11Slot slot = cryptService.getSlot(slotId);
    if (slot.supportsMechanism(P11Constants.CKM_RSA_PKCS_PSS)) {
        this.mechanism = P11Constants.CKM_RSA_PKCS_PSS;
        this.parameters = new P11RSAPkcsPssParams(asn1Params);
        Digest digest = SignerUtil.getDigest(hashAlgo);
        this.outputStream = new DigestOutputStream(digest);
    } else if (slot.supportsMechanism(P11Constants.CKM_RSA_X_509)) {
        this.mechanism = P11Constants.CKM_RSA_X_509;
        this.parameters = null;
        AsymmetricBlockCipher cipher = new P11PlainRSASigner();
        P11RSAKeyParameter keyParam;
        try {
            keyParam = P11RSAKeyParameter.getInstance(cryptService, identityId);
        } catch (InvalidKeyException ex) {
            throw new XiSecurityException(ex.getMessage(), ex);
        }
        PSSSigner pssSigner = SignerUtil.createPSSRSASigner(signatureAlgId, cipher);
        pssSigner.init(true, new ParametersWithRandom(keyParam, random));
        this.outputStream = new PSSSignerOutputStream(pssSigner);
    } else {
        switch (hashAlgo) {
        case SHA1:
            this.mechanism = P11Constants.CKM_SHA1_RSA_PKCS_PSS;
            break;
        case SHA224:
            this.mechanism = P11Constants.CKM_SHA224_RSA_PKCS_PSS;
            break;
        case SHA256:
            this.mechanism = P11Constants.CKM_SHA256_RSA_PKCS_PSS;
            break;
        case SHA384:
            this.mechanism = P11Constants.CKM_SHA384_RSA_PKCS_PSS;
            break;
        case SHA512:
            this.mechanism = P11Constants.CKM_SHA512_RSA_PKCS_PSS;
            break;
        case SHA3_224:
            this.mechanism = P11Constants.CKM_SHA3_224_RSA_PKCS_PSS;
            break;
        case SHA3_256:
            this.mechanism = P11Constants.CKM_SHA3_256_RSA_PKCS_PSS;
            break;
        case SHA3_384:
            this.mechanism = P11Constants.CKM_SHA3_384_RSA_PKCS_PSS;
            break;
        case SHA3_512:
            this.mechanism = P11Constants.CKM_SHA3_512_RSA_PKCS_PSS;
            break;
        default:
            throw new RuntimeException("should not reach here, unknown HashAlgoType " + hashAlgo);
        }

        if (!slot.supportsMechanism(this.mechanism)) {
            throw new XiSecurityException("unsupported signature algorithm "
                    + PKCSObjectIdentifiers.id_RSASSA_PSS.getId() + " with " + hashAlgo);
        }

        this.parameters = new P11RSAPkcsPssParams(asn1Params);
        this.outputStream = new ByteArrayOutputStream();
    }
}