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

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

Introduction

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

Prototype

public int getDigestSize() 

Source Link

Usage

From source file:net.sourceforge.keepassj2me.keydb.KeydbUtil.java

License:Open Source License

/**
 * Get hash of binary chanks/*  w  w w . j  a v  a 2s .  c o m*/
 * @param bufs
 * @return hash
 */
public static byte[] hash(byte[][] bufs) {
    SHA256Digest digest = new SHA256Digest();
    for (int i = 0; i < bufs.length; ++i)
        digest.update(bufs[i], 0, bufs[i].length);
    byte[] hash = new byte[digest.getDigestSize()];
    digest.doFinal(hash, 0);
    return hash;
}

From source file:net.sourceforge.keepassj2me.keydb.KeydbUtil.java

License:Open Source License

/**
 * Get hash of buffer part/* ww w  . j  a  v a 2s .com*/
 * @param buf
 * @param offset
 * @param length
 * @return hash
 */
public static byte[] hash(byte[] buf, int offset, int length) {
    SHA256Digest digest = new SHA256Digest();
    digest.update(buf, offset, length);
    byte[] hash = new byte[digest.getDigestSize()];
    digest.doFinal(hash, 0);
    return hash;
}

From source file:no.digipost.api.client.filters.response.ResponseContentSHA256Filter.java

License:Apache License

private void validerBytesMotHashHeader(final String serverHash, final byte[] entityBytes) {
    SHA256Digest digest = new SHA256Digest();

    digest.update(entityBytes, 0, entityBytes.length);
    byte[] result = new byte[digest.getDigestSize()];
    digest.doFinal(result, 0);//from  w w  w.j  av a  2 s .com
    String ourHash = new String(Base64.encode(result));
    if (!serverHash.equals(ourHash)) {
        throw new DigipostClientException(SERVER_SIGNATURE_ERROR,
                "X-Content-SHA256-header matchet ikke innholdet - server-signatur er feil.");
    }
}

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);//from  www  . ja v  a  2  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.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/*from   w  ww. j av  a  2s  .  c om*/
                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.test.tests.BLSProcessingTest.java

License:Apache License

@Test
public void testBLSSigning() throws Exception {

    SquelchingThrowableHandler handler = new SquelchingThrowableHandler();

    ////from w w w . j  ava 2s.co 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);//  w  w w . j a  va2s. co  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));
}

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

License:Apache License

@Test
public void testECDSASigning() throws Exception {

    SquelchingThrowableHandler handler = new SquelchingThrowableHandler();

    ////from ww  w .ja  v a2 s  .  c om
    // 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.ECDSA, "secp256r1")
            .withThreshold(2).withNodes("A", "B", "C", "D").build();

    ECPublicKeyParameters sigPubKey = (ECPublicKeyParameters) PublicKeyFactory
            .createKey(keyGenerationService.generatePublicKey("ECKEY", 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.ECDSA)
            .withThreshold(2).withNodes("A", "B", "C", "D").build();

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

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

    signer.init(false, sigPubKey);

    BigInteger[] rs = decodeSig(dsaSig);

    Assert.assertTrue(signer.verifySignature(hash, rs[0], rs[1]));

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

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

License:Apache License

private void doMixedMissingTest(SigningService signingService, final ECPublicKeyParameters 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);/*  w  ww  .jav  a 2 s. co m*/

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

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

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

    signer.init(false, sigPubKey);

    BigInteger[] rs = decodeSig(dsaSig);

    Assert.assertTrue(signer.verifySignature(hash, rs[0], rs[1]));
}

From source file:org.freenetproject.freemail.RTSFetcher.java

License:Open Source License

private boolean handle_rts(File rtsmessage) throws ConnectionTerminatedException, InterruptedException {
    // sanity check!
    if (!rtsmessage.exists())
        return false;

    if (rtsmessage.length() > RTS_MAX_SIZE) {
        Logger.normal(this, "RTS Message is too large - discarding!");
        return true;
    }/*from   w  w w  .  jav a  2 s  .co  m*/

    // decrypt
    byte[] plaintext;
    try {
        plaintext = decrypt_rts(rtsmessage);
    } catch (IOException ioe) {
        Logger.normal(this, "Error reading RTS message!");
        return false;
    } catch (InvalidCipherTextException icte) {
        Logger.normal(this, "Could not decrypt RTS message - discarding. " + icte.getMessage());
        return true;
    }

    File rtsfile = null;
    byte[] their_encrypted_sig;
    int messagebytes = 0;
    LineReadingInputStream lis = null;
    PrintStream ps = null;
    try {
        rtsfile = File.createTempFile("rtstmp", "tmp", Freemail.getTempDir());

        ByteArrayInputStream bis = new ByteArrayInputStream(plaintext);
        lis = new LineReadingInputStream(bis);
        ps = new PrintStream(new FileOutputStream(rtsfile));

        String line;
        while (true) {
            try {
                line = lis.readLine(200, 200, false);
            } catch (TooLongException tle) {
                Logger.normal(this, "RTS message has lines that are too long. Discarding.");
                rtsfile.delete();
                return true;
            }
            messagebytes += lis.getLastBytesRead();

            if (line == null || line.equals(""))
                break;
            //FreemailLogger.normal(this, line);

            ps.println(line);
        }

        if (line == null) {
            // that's not right, we shouldn't have reached the end of the file, just the blank line before the signature

            Logger.normal(this, "Couldn't find signature on RTS message - ignoring!");
            rtsfile.delete();
            return true;
        }

        // read the rest of the file into a byte array.
        // will probably have extra stuff on the end because
        // the byte array returned by the decrypt function
        // isn't resized when we know how much plaintext
        // there is. It would be a waste of time, we know
        // we have to read exactly one RSA block's worth.
        their_encrypted_sig = new byte[bis.available()];

        int totalread = 0;
        while (true) {
            int read = bis.read(their_encrypted_sig, totalread, bis.available());
            if (read <= 0)
                break;
            totalread += read;
        }
    } catch (IOException ioe) {
        Logger.normal(this, "IO error whilst handling RTS message. " + ioe.getMessage());
        ioe.printStackTrace();
        if (rtsfile != null)
            rtsfile.delete();
        return false;
    } finally {
        if (ps != null) {
            ps.close();
        }
        if (lis != null) {
            try {
                lis.close();
            } catch (IOException e) {
                Logger.error(this, "Caugth IOException while closing input", e);
            }
        }
    }

    PropsFile rtsprops = PropsFile.createPropsFile(rtsfile);

    try {
        validate_rts(rtsprops);
    } catch (Exception e) {
        Logger.normal(this,
                "RTS message does not contain vital information: " + e.getMessage() + " - discarding");
        rtsfile.delete();
        return true;
    }

    // verify the signature
    String their_mailsite = rtsprops.get("mailsite");

    SHA256Digest sha256 = new SHA256Digest();
    sha256.update(plaintext, 0, messagebytes);
    byte[] our_hash = new byte[sha256.getDigestSize()];
    sha256.doFinal(our_hash, 0);

    HighLevelFCPClient fcpcli = new HighLevelFCPClient();

    Logger.normal(this, "Trying to fetch sender's mailsite: " + their_mailsite);
    File msfile;
    try {
        msfile = fcpcli.fetch(their_mailsite);
    } catch (FCPFetchException fe) {
        // oh well, try again in a bit
        rtsfile.delete();
        return false;
    } catch (FCPException e) {
        Logger.error(this, "Unknown error while checking sender's mailsite: " + e.getMessage());

        //Try again later
        rtsfile.delete();
        return false;
    }

    PropsFile mailsite = PropsFile.createPropsFile(msfile);
    String their_exponent = mailsite.get("asymkey.pubexponent");
    String their_modulus = mailsite.get("asymkey.modulus");

    if (their_exponent == null || their_modulus == null) {
        Logger.normal(this,
                "Mailsite fetched successfully but missing vital information! Discarding this RTS.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }

    RSAKeyParameters their_pubkey = new RSAKeyParameters(false, new BigInteger(their_modulus, 32),
            new BigInteger(their_exponent, 32));
    AsymmetricBlockCipher deccipher = new RSAEngine();
    deccipher.init(false, their_pubkey);

    byte[] their_hash;
    try {
        their_hash = deccipher.processBlock(their_encrypted_sig, 0, deccipher.getInputBlockSize());
    } catch (InvalidCipherTextException icte) {
        Logger.normal(this,
                "It was not possible to decrypt the signature of this RTS message. Discarding the RTS message.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }

    // finally we can now check that our hash and their hash
    // match!
    if (their_hash.length < our_hash.length) {
        Logger.normal(this, "The signature of the RTS message is not valid (our hash: " + our_hash.length
                + "bytes, their hash: " + their_hash.length + "bytes. Discarding the RTS message.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }
    int i;
    for (i = 0; i < our_hash.length; i++) {
        if (their_hash[i] != our_hash[i]) {
            Logger.normal(this, "The signature of the RTS message is not valid. Discarding the RTS message.");
            msfile.delete();
            rtsfile.delete();
            return true;
        }
    }
    Logger.normal(this, "Signature valid :)");
    // the signature is valid! Hooray!
    // Now verify the message is for us
    if (!account.getIdentity().equals(rtsprops.get("to"))) {
        Logger.normal(this, "Recieved an RTS message that was not intended for the recipient. Discarding.");
        msfile.delete();
        rtsfile.delete();
        return true;
    }

    Logger.normal(this, "Original message intended for us :)");

    //Clean up temp files
    if (!msfile.delete()) {
        Logger.error(this, "Couldn't delete fetched mailsite: " + msfile);
    }
    if (!rtsfile.delete()) {
        Logger.error(this, "Couldn't delete rts file: " + rtsfile);
    }

    account.getMessageHandler().createChannelFromRTS(rtsprops);

    return true;
}