Example usage for org.bouncycastle.util BigIntegers createRandomInRange

List of usage examples for org.bouncycastle.util BigIntegers createRandomInRange

Introduction

In this page you can find the example usage for org.bouncycastle.util BigIntegers createRandomInRange.

Prototype

public static BigInteger createRandomInRange(BigInteger min, BigInteger max, SecureRandom random) 

Source Link

Document

Return a random BigInteger not less than 'min' and not greater than 'max'

Usage

From source file:com.enioka.jqm.pki.CertificateRequest.java

License:Open Source License

private void generateX509() throws Exception {
    SecureRandom random = new SecureRandom();
    X500Name dnName = new X500Name(Subject);
    Calendar endValidity = Calendar.getInstance();
    endValidity.add(Calendar.YEAR, validityYear);

    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());

    X509v3CertificateBuilder gen = new X509v3CertificateBuilder(
            authorityCertificate == null ? dnName : authorityCertificate.getSubject(),
            BigIntegers.createRandomInRange(BigInteger.ZERO, BigInteger.valueOf(Long.MAX_VALUE), random),
            new Date(), endValidity.getTime(), dnName, publicKeyInfo);

    // Public key ID
    DigestCalculator digCalc = new BcDigestCalculatorProvider()
            .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
    X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);
    gen.addExtension(Extension.subjectKeyIdentifier, false,
            x509ExtensionUtils.createSubjectKeyIdentifier(publicKeyInfo));

    // EKU/*from  w ww . j a  v a2 s .c  om*/
    gen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));

    // Basic constraints (is CA?)
    if (authorityCertificate == null) {
        gen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    }

    // Key usage
    gen.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsage));

    // Subject Alt names ?

    // Authority
    if (authorityCertificate != null) {
        gen.addExtension(Extension.authorityKeyIdentifier, false,
                new AuthorityKeyIdentifier(authorityCertificate.getSubjectPublicKeyInfo()));
    }

    // Signer
    ContentSigner signer = new JcaContentSignerBuilder("SHA512WithRSAEncryption")
            .setProvider(Constants.JCA_PROVIDER).build(authorityKey == null ? privateKey : authorityKey);

    // Go
    holder = gen.build(signer);
}

From source file:com.joyent.http.signature.crypto.NativeRSABlindedEngine.java

License:Open Source License

/**
 * Process a single block using the basic RSA algorithm.
 *
 * @param in the input array./*w  w  w.  j a v  a 2s  .co  m*/
 * @param inOff the offset into the input buffer where the data starts.
 * @param inLen the length of the data to be processed.
 * @return the result of the RSA process.
 * @exception DataLengthException the input block is too large.
 */
@Override
public byte[] processBlock(final byte[] in, final int inOff, final int inLen) {
    if (key == null) {
        throw new IllegalStateException("RSA engine not initialised");
    }

    BigInteger input = core.convertInput(in, inOff, inLen);

    BigInteger result;
    if (key instanceof RSAPrivateCrtKeyParameters) {
        RSAPrivateCrtKeyParameters k = (RSAPrivateCrtKeyParameters) key;

        BigInteger e = k.getPublicExponent();
        // can't do blinding without a public exponent
        if (e != null) {
            BigInteger m = k.getModulus();
            BigInteger r = BigIntegers.createRandomInRange(ONE, m.subtract(ONE), random);

            // This is a modification to use the GMP native library method
            BigInteger blindedModPow = Gmp.modPowSecure(r, e, m);

            BigInteger blindedInput = blindedModPow.multiply(input).mod(m);
            BigInteger blindedResult = core.processBlock(blindedInput);

            // This is a modification to use the GMP native library method
            BigInteger rInv = Gmp.modInverse(r, m);

            result = blindedResult.multiply(rInv).mod(m);
            // defence against Arjen Lenstras CRT attack
            // This is a modification to use the GMP native library method
            if (!input.equals(Gmp.modPowInsecure(result, e, m))) {
                throw new IllegalStateException("RSA engine faulty decryption/signing detected");
            }
        } else {
            result = core.processBlock(input);
        }
    } else {
        result = core.processBlock(input);
    }

    return core.convertOutput(result);
}

From source file:edu.biu.scapi.interactiveMidProtocols.commitmentScheme.elGamal.CmtElGamalCommitterCore.java

License:Open Source License

/**
 * Computes the commitment object of the commitment scheme. <p>
 * Pseudo code:<p>/* w  w  w  .j  av  a  2s  .c  om*/
 * "SAMPLE random values  r <- Zq <p>
 *   COMPUTE u = g^r and v = h^r * x". <p>
 * @return the created commitment.
 */
public CmtCCommitmentMsg generateCommitmentMsg(CmtCommitValue input, long id) {

    //Sample random r <-Zq.
    BigInteger r = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, random);

    //Compute u = g^r and v = h^r * x.
    //This is actually the encryption of x.
    AsymmetricCiphertext c = elGamal.encrypt(input.convertToPlaintext(), r);

    //keep the committed value in the map together with its ID.
    commitmentMap.put(Long.valueOf(id),
            new CmtElGamalCommitmentPhaseValues(new BigIntegerRandomValue(r), input, c));

    return new CmtElGamalCommitmentMessage((ElGamalCiphertextSendableData) c.generateSendableData(), id);
}

From source file:edu.biu.scapi.interactiveMidProtocols.commitmentScheme.pedersen.CmtPedersenCommitter.java

License:Open Source License

/**
 * This function samples random commit value and returns it.
 * @return the sampled commit value//  w w w . j a v a 2  s . c  om
 */
public CmtCommitValue sampleRandomCommitValue() {
    BigInteger qMinusOne = dlog.getOrder().subtract(BigInteger.ONE);
    BigInteger val = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, random);
    return new CmtBigIntegerCommitValue(val);
}

From source file:edu.biu.scapi.interactiveMidProtocols.commitmentScheme.pedersen.CmtPedersenCommitterCore.java

License:Open Source License

/**
 * Runs the following lines of the commitment scheme: <P>
 * "SAMPLE a random value r <- Zq<P>
 *    COMPUTE  c = g^r * h^x". <p>
 *///from  w ww .j  a v a 2 s. c  om
public CmtCCommitmentMsg generateCommitmentMsg(CmtCommitValue input, long id) {

    if (!(input instanceof CmtBigIntegerCommitValue))
        throw new IllegalArgumentException("The input must be of type CmtBigIntegerCommitValue");

    BigInteger x = ((CmtBigIntegerCommitValue) input).getX();
    //Check that the input is in Zq.
    if ((x.compareTo(BigInteger.ZERO) < 0) || (x.compareTo(dlog.getOrder()) > 0)) {
        throw new IllegalArgumentException("The input must be in Zq");
    }

    //Sample a random value r <- Zq
    BigInteger r = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, random);

    //Compute  c = g^r * h^x
    GroupElement gToR = dlog.exponentiate(dlog.getGenerator(), r);
    GroupElement hToX = dlog.exponentiate(h, x);
    GroupElement c = dlog.multiplyGroupElements(gToR, hToX);

    //Keep the committed value in the map together with its ID.
    commitmentMap.put(Long.valueOf(id), new CmtPedersenCommitmentPhaseValues(new BigIntegerRandomValue(r),
            new CmtBigIntegerCommitValue(x), c));

    //Send c
    return new CmtPedersenCommitmentMessage(c.generateSendableData(), id);

}

From source file:edu.biu.scapi.interactiveMidProtocols.commitmentScheme.pedersen.CmtPedersenReceiverCore.java

License:Open Source License

/**
 * Runs the preprocess stage of the protocol:
 * "SAMPLE a random value a <- Zq//  ww w .j  av  a 2  s  .c  o m
 *   COMPUTE h = g^a
 *   SEND h to C".
 * The pre-process phase is performed once per instance. 
 * If different values are required, a new instance of the receiver and the committer 
 * need to be created.
 */
private void preProcess() throws IOException {
    trapdoor = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, random);
    h = dlog.exponentiate(dlog.getGenerator(), trapdoor);

    CmtPedersenPreprocessMessage msg = new CmtPedersenPreprocessMessage(h.generateSendableData());
    try {
        channel.send(msg);
    } catch (IOException e) {
        throw new IOException("failed to send the message. The error is: " + e.getMessage());
    }

}

From source file:edu.biu.scapi.interactiveMidProtocols.ot.fullSimulation.OTFullSimReceiverPreprocessUtil.java

License:Open Source License

/**
 * Runs the preprocess phase of the protocol, where the receiver input is not yet necessary.<p>
 *    "SAMPLE random values y, alpha0 <- {0, . . . , q-1} <p>
 *   SET alpha1 = alpha0 + 1 <p>//from  ww  w  .j  a  v a  2s. c o m
 *   COMPUTE <p>
 *    1. g1 = (g0)^y<p>
 *     2. h0 = (g0)^(alpha0)<p>
 *     3. h1 = (g1)^(alpha1)<p>
 *   SEND (g1,h0,h1) to S<p>
 *  Run the prover in ZKPOK_FROM_SIGMA with Sigma protocol SIGMA_DH. Use common input (g0,g1,h0,h1/g1) and private input alpha0."
 * @param channel
 * @param dlog
 * @param zkProver used to prove the ZKPOK_FROM_SIGMA
 * @param random
 * @return the values calculated in the preprocess
 * @throws ClassNotFoundException if there was a problem during the serialization mechanism in the preprocess phase.
 * @throws CheatAttemptException if the receiver suspects that the sender is trying to cheat in the preprocess phase.
 * @throws IOException if there was a problem during the communication in the preprocess phase.
 * @throws CommitValueException can occur in case of ElGamal commitment scheme.
 */
public static OTFullSimPreprocessPhaseValues preProcess(DlogGroup dlog, ZKPOKProver zkProver, Channel channel,
        SecureRandom random)
        throws IOException, CheatAttemptException, ClassNotFoundException, CommitValueException {
    BigInteger qMinusOne = dlog.getOrder().subtract(BigInteger.ONE);

    //Sample random values 
    BigInteger y = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, random);
    BigInteger alpha0 = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, random);

    //Set alpha1 = alpha0 + 1 
    BigInteger alpha1 = alpha0.add(BigInteger.ONE);

    //Calculate tuple elements
    GroupElement g0 = dlog.getGenerator();
    GroupElement g1 = dlog.exponentiate(g0, y);
    GroupElement h0 = dlog.exponentiate(g0, alpha0);
    GroupElement h1 = dlog.exponentiate(g1, alpha1);

    OTFullSimDDHReceiverMsg tuple = new OTFullSimDDHReceiverMsg(g1.generateSendableData(),
            h0.generateSendableData(), h1.generateSendableData());

    //Send tuple to sender.
    sendTupleToSender(channel, tuple);

    //Run the prover in ZKPOK_FROM_SIGMA with Sigma protocol SIGMA_DH.
    GroupElement g1Inv = dlog.getInverse(g1);
    GroupElement h1DivG1 = dlog.multiplyGroupElements(h1, g1Inv);

    zkProver.prove(new SigmaDHProverInput(g1, h0, h1DivG1, alpha0));

    return new OTFullSimPreprocessPhaseValues(g0, g1, h0, h1);
}

From source file:edu.biu.scapi.interactiveMidProtocols.ot.fullSimulation.OTFullSimReceiverTransferUtilAbs.java

License:Open Source License

/**
 * /*ww  w. ja va  2 s  .c  o m*/
 * Run the transfer phase of the OT protocol.<p>
 * Transfer Phase (with inputs sigma) <p>
 *      SAMPLE a random value r <- {0, . . . , q-1} <p>
 *      COMPUTE<p>
 *      4.   g = (gSigma)^r<p>
 *      5.   h = (hSigma)^r<p>
 *      SEND (g,h) to S<p>
 *      WAIT for messages (u0,c0) and (u1,c1) from S<p>
 *      In ByteArray scenario:<p>
 *      IF  NOT<p>
 *         u0, u1 in G, AND<p>
 *         c0, c1 are binary strings of the same length<p>
 *            REPORT ERROR<p>
 *      OUTPUT  xSigma = cSigma XOR KDF(|cSigma|,(uSigma)^r)<p>
 *      In GroupElement scenario:<p>
 *      IF  NOT<p>
 *         u0, u1, c0, c1 in G<p>
 *            REPORT ERROR<p>
 *      OUTPUT  xSigma = cSigma * (uSigma)^(-r)<p>
 * This is the transfer stage of OT protocol which can be called several times in parallel.<p>
 * The OT implementation support usage of many calls to transfer, with single preprocess execution. <p>
 * This way, one can execute batch OT by creating the OT receiver once and call the transfer function for each input couple.<p>
 * In order to enable the parallel calls, each transfer call should use a different channel to send and receive messages.
 * This way the parallel executions of the function will not block each other.
 * @param channel each call should get a different one.
 * @param input MUST be OTRBasicInput. The parameters given in the input must match the DlogGroup member of this class, which given in the constructor.
 * @param preprocessValues hold the values calculated in the preprocess phase.
 * @return OTROutput, the output of the protocol.
 * @throws CheatAttemptException if there was a cheat attempt during the execution of the protocol.
 * @throws IOException if the send or receive functions failed
 * @throws ClassNotFoundException if there was a problem during the serialization mechanism
 */
public OTROutput transfer(Channel channel, OTRInput input, OTFullSimPreprocessPhaseValues preprocessValues)
        throws IOException, ClassNotFoundException, CheatAttemptException {
    //check if the input is valid.
    //If input is not instance of OTRBasicInput, throw Exception.
    if (!(input instanceof OTRBasicInput)) {
        throw new IllegalArgumentException("input should contain sigma.");
    }

    byte sigma = ((OTRBasicInput) input).getSigma();

    //The given sigma should be 0 or 1.
    if ((sigma != 0) && (sigma != 1)) {
        throw new IllegalArgumentException("Sigma should be 0 or 1");
    }

    //Sample a random value r <- {0, . . . , q-1} 
    BigInteger r = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, random);

    //Compute tuple (g,h) for sender.
    OTRGroupElementPairMsg a = computeSecondTuple(sigma, r, preprocessValues);

    //Send tuple to sender.
    sendTupleToSender(channel, a);

    //Wait for message from sender.
    OTSMsg message = waitForMessageFromSender(channel);

    //Compute the final calculations to get xSigma.
    return checkMessgeAndComputeX(sigma, r, message);
}

From source file:edu.biu.scapi.interactiveMidProtocols.ot.oneSidedSimulation.OTOneSidedSimDDHReceiverAbs.java

License:Open Source License

/**
 * Runs the transfer phase of the OT protocol.<p>
 * This is the part of the protocol where the receiver input is necessary.<p>
 * "SAMPLE random values alpha, beta, gamma in {0, . . . , q-1} <p>
 *   COMPUTE a as follows:<p>/*from  www  .  j ava  2 s .c o m*/
 *   1.   If sigma = 0 then a = (g^alpha, g^beta, g^(alpha*beta), g^gamma)<p>
 *   2.   If sigma = 1 then a = (g^alpha, g^beta, g^gamma, g^(alpha*beta))<p>
 *   SEND a to S<p>
 *   Run the prover in ZKPOK_FROM_SIGMA with Sigma protocol SIGMA_DLOG. Use common input x and private input alpha.<p>
 *   WAIT for message pairs (w0, c0) and (w1, c1)  from S<p>
 *   In ByteArray scenario:<p>
 *      IF  NOT <p>
 *         1. w0, w1 in the DlogGroup, AND<p>
 *         2. c0, c1 are binary strings of the same length<p>
 *           REPORT ERROR<p>
 *      COMPUTE kSigma = (wSigma)^beta<p>
 *      OUTPUT  xSigma = cSigma XOR KDF(|cSigma|,kSigma)<p>
 *   In GroupElement scenario:<p>
 *      IF  NOT <p>
 *         1. w0, w1, c0, c1 in the DlogGroup<p>
 *           REPORT ERROR<p>
 *      COMPUTE (kSigma)^(-1) = (wSigma)^(-beta)<p>
 *      OUTPUT  xSigma = cSigma * (kSigma)^(-1)"<p>
 * @return OTROutput, the output of the protocol.
 */
public OTROutput transfer(Channel channel, OTRInput input)
        throws CheatAttemptException, IOException, ClassNotFoundException {
    //check if the input is valid.
    //If input is not instance of OTRBasicInput, throw Exception.
    if (!(input instanceof OTRBasicInput)) {
        throw new IllegalArgumentException("input should contain sigma.");
    }

    byte sigma = ((OTRBasicInput) input).getSigma();

    //The given sigma should be 0 or 1.
    if ((sigma != 0) && (sigma != 1)) {
        throw new IllegalArgumentException("Sigma should be 0 or 1");
    }

    /* Run the following part of the protocol:
       SAMPLE random values alpha, beta, gamma in [0, . . . , q-1] 
       COMPUTE a as follows:
       1.   If sigma = 0 then a = (g^alpha, g^beta, g^(alpha*beta), g^gamma)
       2.   If sigma = 1 then a = (g^alpha, g^beta, g^gamma, g^(alpha*beta))
       SEND a to S
       Run the prover in ZKPOK_FROM_SIGMA with Sigma protocol SIGMA_DLOG. Use gAlpha and private input alpha.
       WAIT for message pairs (w0, c0) and (w1, c1)  from S
       In ByteArray scenario:
    IF  NOT 
       1. w0, w1 in the DlogGroup, AND
       2. c0, c1 are binary strings of the same length
       REPORT ERROR
    COMPUTE kSigma = (wSigma)^beta
    OUTPUT  xSigma = cSigma XOR KDF(|cSigma|,kSigma)
       In GroupElement scenario:
    IF  NOT 
       1. w0, w1, c0, c1 in the DlogGroup
       REPORT ERROR
    COMPUTE (kSigma)^(-1) = (wSigma)^(-beta)
    OUTPUT  xSigma = cSigma * (kSigma)^(-1)
            
    */

    //Sample random values alpha, beta in [0, . . . , q-1]
    BigInteger alpha = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, random);
    BigInteger beta = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, random);

    //Compute g^alpha
    GroupElement g = dlog.getGenerator();
    GroupElement gAlpha = dlog.exponentiate(g, alpha);

    //complete calculations for tuple and create tuple for sender.
    OTRGroupElementQuadMsg a = computeTuple(sigma, alpha, beta, gAlpha);

    //Send tuple to sender.
    sendTupleToSender(channel, a);

    //Run the prover in ZKPOK_FROM_SIGMA with Sigma protocol SIGMA_DLOG.
    runZKPOK(channel, gAlpha, alpha);

    //Wait for message from sender.
    OTSMsg message = waitForMessageFromSender(channel);

    //Compute the final calculations to get xSigma.
    return checkMessgeAndComputeX(sigma, beta, message);
}

From source file:edu.biu.scapi.interactiveMidProtocols.ot.oneSidedSimulation.OTOneSidedSimDDHReceiverAbs.java

License:Open Source License

/**
 * Runs the following lines from the protocol:
 * "COMPUTE a as follows:/*from w w w.  j  av a2  s. c o  m*/
 *         1.   If sigma = 0 then a = (g^alpha, g^beta, g^(alpha*beta), g^gamma)
 *         2.   If sigma = 1 then a = (g^alpha, g^beta, g^gamma, g^(alpha*beta))"
 * @param sigma input for the protocol
 * @param alpha random value sampled in the protocol
 * @param beta random value sampled in the protocol
 * @param gAlpha g^alpha
 * @return OTRPrivacyOnlyMessage contains the tuple (x, y, z0, z1).
 */
private OTRGroupElementQuadMsg computeTuple(byte sigma, BigInteger alpha, BigInteger beta,
        GroupElement gAlpha) {
    //Sample random value gamma in [0, . . . , q-1]
    BigInteger gamma = BigIntegers.createRandomInRange(BigInteger.ZERO, qMinusOne, random);

    //Calculates g^beta, g^(alpha*beta), g^gamma.
    GroupElement g = dlog.getGenerator();
    GroupElement gBeta = dlog.exponentiate(g, beta);
    GroupElement gGamma = dlog.exponentiate(g, gamma);
    GroupElement gAlphaBeta = dlog.exponentiate(g, alpha.multiply(beta));

    //Create the tuple.
    if (sigma == 0) {
        return new OTRGroupElementQuadMsg(gAlpha.generateSendableData(), gBeta.generateSendableData(),
                gAlphaBeta.generateSendableData(), gGamma.generateSendableData());
    } else {
        return new OTRGroupElementQuadMsg(gAlpha.generateSendableData(), gBeta.generateSendableData(),
                gGamma.generateSendableData(), gAlphaBeta.generateSendableData());
    }
}