Example usage for org.bouncycastle.crypto.digests SHA256Digest SHA256Digest

List of usage examples for org.bouncycastle.crypto.digests SHA256Digest SHA256Digest

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.digests SHA256Digest SHA256Digest.

Prototype

public SHA256Digest() 

Source Link

Document

Standard constructor

Usage

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

License:Open Source License

/**
 * Determines whether the given RSA public and private keys form a proper key
 * pair by computing and verifying a digital signature with the keys.
 *
 * @param  pubKey  RSA public key./*from   w  ww. ja v a2s .c  om*/
 * @param  privKey  RSA 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 RSAPublicKey pubKey, final RSAPrivateKey privKey) {
    final RSADigestSigner signer = new RSADigestSigner(new SHA256Digest());
    signer.init(true, new RSAKeyParameters(true, privKey.getModulus(), privKey.getPrivateExponent()));
    signer.update(SIGN_BYTES, 0, SIGN_BYTES.length);
    try {
        final byte[] sig = signer.generateSignature();
        signer.init(false, new RSAKeyParameters(false, pubKey.getModulus(), pubKey.getPublicExponent()));
        signer.update(SIGN_BYTES, 0, SIGN_BYTES.length);
        return signer.verifySignature(sig);
    } catch (CryptoException e) {
        return false;
    }
}

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

License:Open Source License

/**
 * Creates a new DRBG instance based on a SHA-256 digest.
 *
 * @param  length  Length in bits of values to be produced by DRBG instance.
 *
 * @return  New DRGB instance./* w ww  . ja va 2s  . c o m*/
 */
public static SP80090DRBG newRBG(final int length) {
    return newRBG(new SHA256Digest(), length);
}

From source file:org.crypto.sse.CryptoPrimitives.java

License:Open Source License

public static byte[] generateHmac(byte[] key, String msg) throws UnsupportedEncodingException {

    HMac hmac = new HMac(new SHA256Digest());
    byte[] result = new byte[hmac.getMacSize()];
    byte[] msgAry = msg.getBytes("UTF-8");
    hmac.init(new KeyParameter(key));
    hmac.reset();/*from   w  w w  . ja v  a 2  s. c  om*/
    hmac.update(msgAry, 0, msgAry.length);
    hmac.doFinal(result, 0);
    return result;
}

From source file:org.crypto.sse.CryptoPrimitives.java

License:Open Source License

public static byte[] generateHmac(byte[] key, byte[] msg) throws UnsupportedEncodingException {

    HMac hmac = new HMac(new SHA256Digest());
    byte[] result = new byte[hmac.getMacSize()];
    hmac.init(new KeyParameter(key));
    hmac.reset();/*from  w  w  w . ja va2 s. c om*/
    hmac.update(msg, 0, msg.length);
    hmac.doFinal(result, 0);
    return result;
}

From source file:org.cryptoworkshop.ximix.common.crypto.ECDecryptionProof.java

License:Apache License

private BigInteger computeChallenge(ECPoint a, ECPoint b, ECPoint c, ECPoint partial, ECPoint g, ECPoint q) {
    SHA256Digest sha256 = new SHA256Digest();

    addIn(sha256, a);/*w w w .j  a  va2  s.c o m*/
    addIn(sha256, b);
    addIn(sha256, c);

    addIn(sha256, partial);
    addIn(sha256, g);
    addIn(sha256, q);

    byte[] res = new byte[sha256.getDigestSize()];

    sha256.doFinal(res, 0);

    return new BigInteger(1, res);
}

From source file:org.cryptoworkshop.ximix.common.util.challenge.SeededChallenger.java

License:Apache License

/**
 * Base constructor.//  www.  j av a  2s . c om
 *
 * @param size the number of messages on the board we are issuing challenges on.
 * @param stepNo the number of the step in the shuffling process.
 * @param seed a random seed for creating index numbers to challenge on - must be at least 55 bytes.
 */
public SeededChallenger(Integer size, Integer stepNo, byte[] seed) {
    this.counter = 0;
    this.startIndex = 0;

    this.bitSet = buildBitSet(size, new HashSP800DRBG(new SHA256Digest(), 256,
            new SingleEntropySourceProvider(seed).get(440), null, null));
    this.isMirror = (((seed[seed.length - 1] & 0xff) + stepNo) & 0x01) == 0;
    this.max = (isMirror) ? (size - (size / 2)) : (size / 2);
}

From source file:org.cryptoworkshop.ximix.demo.client.Main.java

License:Apache License

public static void main(String[] args) throws Exception {
    XimixRegistrar registrar = XimixRegistrarFactory.createServicesRegistrar(new File(args[0]),
            new EventNotifier() {
                @Override/*  w w w . j av a  2  s  .com*/
                public void notify(Level level, Throwable throwable) {
                    System.err.print(level + " " + throwable.getMessage());
                    throwable.printStackTrace(System.err);
                }

                @Override
                public void notify(Level level, Object detail) {
                    System.err.println(level + " " + detail.toString());
                }

                @Override
                public void notify(Level level, Object detail, Throwable throwable) {
                    System.err.println(level + " " + detail.toString());
                    throwable.printStackTrace(System.err);
                }
            });

    KeyService keyFetcher = registrar.connect(KeyService.class);
    //UploadService client = registrar.connect(UploadService.class);
    SigningService signingService = registrar.connect(SigningService.class);

    byte[] encPubKey = keyFetcher.fetchPublicKey("ECENCKEY");

    ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.createKey(encPubKey);

    ECElGamalEncryptor encryptor = new ECElGamalEncryptor();

    encryptor.init(pubKey);

    ECPoint candidate1 = generatePoint(pubKey.getParameters(), new SecureRandom());

    ECPoint candidate2 = generatePoint(pubKey.getParameters(), new SecureRandom());

    //
    // encrypt two candidate numbers
    //
    ECPair encCandidate1 = encryptor.encrypt(candidate1);
    ECPair encCandidate2 = encryptor.encrypt(candidate2);

    PairSequence ballot = new PairSequence(encCandidate1, encCandidate2);

    // client.uploadMessage("FRED", ballot.getEncoded());

    SHA256Digest sha256 = new SHA256Digest();

    byte[] message = ballot.getEncoded();
    byte[] hash = new byte[sha256.getDigestSize()];

    sha256.update(message, 0, message.length);

    sha256.doFinal(hash, 0);

    //
    // ECDSA
    //
    SignatureGenerationOptions sigGenOptions = new SignatureGenerationOptions.Builder(Algorithm.ECDSA)
            .withThreshold(2).withNodes("A", "B", "C", "D").build();

    byte[] dsaSig = signingService.generateSignature("ECSIGKEY", sigGenOptions, hash);

    //
    // check the signature locally.
    //
    ECDSASigner signer = new ECDSASigner();

    ECPublicKeyParameters sigPubKey = (ECPublicKeyParameters) PublicKeyFactory
            .createKey(signingService.fetchPublicKey("ECSIGKEY"));

    signer.init(false, sigPubKey);

    BigInteger[] rs = decodeSig(dsaSig);

    if (signer.verifySignature(hash, rs[0], rs[1])) {
        System.out.println("sig verified!");
    } else {
        System.out.println("sig failed...");
    }

    SignatureGenerationOptions blsSigGenOptions = new SignatureGenerationOptions.Builder(Algorithm.BLS)
            .withThreshold(3).withNodes("B", "C", "D").build();

    byte[] blsSig = signingService.generateSignature("BLSSIGKEY", blsSigGenOptions, hash);

    //
    // check the signature locally.
    //
    BLS01Signer blsSigner = new BLS01Signer(sha256);

    BLS01PublicKeyParameters blsPubKey = BLSPublicKeyFactory
            .createKey(signingService.fetchPublicKey("BLSSIGKEY"));

    blsSigner.init(false, blsPubKey);

    blsSigner.update(message, 0, message.length);

    if (blsSigner.verifySignature(blsSig)) {
        System.out.println("sig verified!");
    } else {
        System.out.println("sig failed...");
    }

    keyFetcher.shutdown();
    signingService.shutdown();
    registrar.shutdown();
}

From source file:org.cryptoworkshop.ximix.node.mixnet.shuffle.TransformShuffleAndMoveTask.java

License:Apache License

public void run() {
    BulletinBoard board = boardRegistry.getTransitBoard(message.getOperationNumber(), message.getBoardName(),
            message.getStepNumber());// w  w  w .jav  a2 s .  c o m
    Transform transform = boardRegistry.getTransform(message.getTransformName());
    IndexCommitter committer = new IndexCommitter(new SHA256Digest(), new SecureRandom());

    try {
        PostedMessageBlock.Builder messageBlockBuilder = new PostedMessageBlock.Builder(20); // TODO: make configurable
        MessageWitnessBlock.Builder messageWitnessBlockBuilder = new MessageWitnessBlock.Builder(
                messageBlockBuilder.capacity());

        RandomIndexNumberGenerator indexGen = new RandomIndexNumberGenerator(board.size(), new SecureRandom()); // TODO: specify random

        int nextStepNumber = message.getStepNumber() + 1;

        if (message.getKeyID() != null) {
            SubjectPublicKeyInfo keyInfo = nodeContext.getPublicKey(message.getKeyID());
            ECPublicKeyParameters key;

            if (keyInfo != null) {
                key = (ECPublicKeyParameters) PublicKeyFactory.createKey(keyInfo);
            } else {
                // see if the key exists elsewhere on the MIXNET.
                FetchPublicKeyMessage fetchMessage = new FetchPublicKeyMessage(message.getKeyID());

                MessageReply reply = nodeContext.getPeerMap().values().iterator().next()
                        .sendMessage(ClientMessage.Type.FETCH_PUBLIC_KEY, fetchMessage);

                if (reply.getPayload() != null) {
                    key = (ECPublicKeyParameters) PublicKeyFactory
                            .createKey(reply.getPayload().toASN1Primitive().getEncoded());
                } else {
                    nodeContext.getEventNotifier().notify(EventNotifier.Level.ERROR,
                            "Unable to find public key " + message.getKeyID());
                    return;
                }
            }

            transform.init(key);

            for (PostedMessage postedMessage : board) {
                byte[] transformed = transform.transform(postedMessage.getMessage());
                int newIndex = indexGen.nextIndex();
                Commitment commitment = committer.commit(newIndex);

                messageBlockBuilder.add(newIndex, transformed, commitment.getCommitment());
                messageWitnessBlockBuilder.add(postedMessage.getIndex(),
                        new MessageCommitment(newIndex, commitment.getSecret(), transform.getLastDetail()));

                if (messageBlockBuilder.isFull()) {
                    processMessageBlock(messageBlockBuilder, nextStepNumber);
                    processWitnessBlock(board, messageWitnessBlockBuilder);
                }
            }
        } else {
            for (PostedMessage postedMessage : board) {
                int newIndex = indexGen.nextIndex();
                Commitment commitment = committer.commit(newIndex);

                messageBlockBuilder.add(newIndex, postedMessage.getMessage(), commitment.getCommitment());
                messageWitnessBlockBuilder.add(postedMessage.getIndex(),
                        new MessageCommitment(newIndex, commitment.getSecret()));

                if (messageBlockBuilder.isFull()) {
                    processMessageBlock(messageBlockBuilder, nextStepNumber);
                    processWitnessBlock(board, messageWitnessBlockBuilder);
                }
            }
        }

        if (!messageBlockBuilder.isEmpty()) {
            processMessageBlock(messageBlockBuilder, nextStepNumber);
            processWitnessBlock(board, messageWitnessBlockBuilder);
        }

        MessageReply reply = peerConnection.sendMessage(CommandMessage.Type.TRANSFER_TO_BOARD_ENDED,
                new TransitBoardMessage(message.getOperationNumber(), board.getName(), nextStepNumber));

        if (reply.getType() != MessageReply.Type.OKAY) {
            nodeContext.getEventNotifier().notify(EventNotifier.Level.ERROR,
                    "End of transfer message failed: " + reply.interpretPayloadAsError());
        }
    } catch (ServiceConnectionException e) {
        nodeContext.getEventNotifier().notify(EventNotifier.Level.ERROR, "Connection failed: " + e.getMessage(),
                e);
    } catch (Exception e) {
        nodeContext.getEventNotifier().notify(EventNotifier.Level.ERROR,
                "TransformShuffleAndMoveTask connection failed: " + e.getMessage(), e);
    }
}

From source file:org.cryptoworkshop.ximix.test.tests.BLSProcessingTest.java

License:Apache License

@Test
public void testBLSSigning() throws Exception {

    SquelchingThrowableHandler handler = new SquelchingThrowableHandler();

    ////from www .j av a 2  s .c o m
    // Squelch out socket exceptions emitted by close of connections below.
    //
    handler.squelchType(SocketException.class);

    XimixNode nodeOne = getXimixNode("/conf/mixnet.xml", "/conf/node1.xml", handler);
    NodeTestUtil.launch(nodeOne);

    XimixNode nodeTwo = getXimixNode("/conf/mixnet.xml", "/conf/node2.xml", handler);
    NodeTestUtil.launch(nodeTwo);

    XimixNode nodeThree = getXimixNode("/conf/mixnet.xml", "/conf/node3.xml", handler);
    NodeTestUtil.launch(nodeThree);

    XimixNode nodeFour = getXimixNode("/conf/mixnet.xml", "/conf/node4.xml", handler);
    NodeTestUtil.launch(nodeFour);

    XimixNode nodeFive = getXimixNode("/conf/mixnet.xml", "/conf/node5.xml", handler);
    NodeTestUtil.launch(nodeFive);

    XimixRegistrar registrar = XimixRegistrarFactory
            .createAdminServiceRegistrar(ResourceAnchor.load("/conf/mixnet.xml"), new TestNotifier());

    KeyGenerationService keyGenerationService = registrar.connect(KeyGenerationService.class);

    KeyGenerationOptions keyGenOptions = new KeyGenerationOptions.Builder(Algorithm.BLS, "secp256r1")
            .withThreshold(3).withNodes("A", "B", "C", "D").build();

    BLS01PublicKeyParameters sigPubKey = BLSPublicKeyFactory
            .createKey(keyGenerationService.generatePublicKey("BLSKEY", keyGenOptions));

    SigningService signingService = registrar.connect(SigningService.class);

    SHA256Digest sha256 = new SHA256Digest();

    byte[] message = "hello world!".getBytes();
    byte[] hash = new byte[sha256.getDigestSize()];

    sha256.update(message, 0, message.length);

    sha256.doFinal(hash, 0);

    SignatureGenerationOptions sigGenOptions = new SignatureGenerationOptions.Builder(Algorithm.BLS)
            .withThreshold(3).withNodes("A", "B", "C", "D").build();

    byte[] blsSig = signingService.generateSignature("BLSKEY", sigGenOptions, hash);

    //
    // check the signature locally.
    //
    BLS01Signer signer = new BLS01Signer(sha256);

    signer.init(false, sigPubKey);

    signer.update(message, 0, message.length);

    Assert.assertTrue(signer.verifySignature(blsSig));

    //
    // Shutdown nodes and close services.
    //
    keyGenerationService.shutdown();
    signingService.shutdown();

    NodeTestUtil.shutdownNodes();
}

From source file:org.cryptoworkshop.ximix.test.tests.BLSProcessingTest.java

License:Apache License

private void doMixedMissingTest(SigningService signingService, final BLS01PublicKeyParameters sigPubKey,
        String[] sigNodes) throws Exception {
    SHA256Digest sha256 = new SHA256Digest();

    byte[] message = "hello world!".getBytes();
    byte[] hash = new byte[sha256.getDigestSize()];

    sha256.update(message, 0, message.length);

    sha256.doFinal(hash, 0);/*from  w  ww.  j  ava2 s  .  c  o  m*/

    SignatureGenerationOptions sigGenOptions = new SignatureGenerationOptions.Builder(Algorithm.BLS)
            .withThreshold(2).withNodes(sigNodes).build();

    byte[] blsSig = signingService.generateSignature("BLSKEY", sigGenOptions, hash);

    //
    // check the signature locally.
    //
    BLS01Signer signer = new BLS01Signer(sha256);

    signer.init(false, sigPubKey);

    signer.update(message, 0, message.length);

    Assert.assertTrue(signer.verifySignature(blsSig));
}