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

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

Introduction

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

Prototype

public int getDigestSize() 

Source Link

Usage

From source file:com.verhas.licensor.License.java

License:Open Source License

/**
 * Calculate the SHA512 digest of the public key ring that is used to decode
 * the license./*from   w  ww.  ja  v  a2s. co m*/
 * 
 * @return the digest as a byte array.
 */
public byte[] calculatePublicKeyRingDigest() {
    final SHA512Digest dig = new SHA512Digest();
    dig.reset();
    dig.update(publicKeyRing, 0, publicKeyRing.length);
    final byte[] digest = new byte[dig.getDigestSize()];
    dig.doFinal(digest, 0);
    return digest;
}

From source file:dorkbox.build.util.jar.JarUtil.java

License:Apache License

private static void packEntry(PackTask task) throws IOException {
    InputStream inputStream = task.inputStream;
    int length = task.length;
    Repack repack = task.pack;/*www .  j a  v a  2  s.c  o  m*/

    // now handle pack/compress/encrypt
    if (Pack200Util.canPack200(repack, task.inputStream)) {
        // Create the Packer object
        ByteArrayOutputStream outputPackStream = Pack200Util.Java.pack200(inputStream, task.debug);

        // convert the output stream to an input stream
        inputStream = new ByteArrayInputStream(outputPackStream.toByteArray());
        length = inputStream.available();
    }

    // we RELY on the the jar ALREADY being NORMALIZED (PACK+UNPACK). pack200 -repack DOES NOT WORK! You must EXPLICITY
    // use the programmatic safePack200 and safeUnpack200 so the jar will be consistent between pack/unpack cycles.
    if (repack.canDo(PackAction.LoadLibray)) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
        Sys.copyStream(inputStream, baos);

        // we make it NOT pack, and since we ARE NOT modifying the input stream, it's safe to read it directly
        byte[] unpackBuffer = baos.toByteArray();
        int unpackLength = unpackBuffer.length;
        SHA512Digest digest = new SHA512Digest();

        // now run the hash on it!
        byte[] hashBytes = new byte[digest.getDigestSize()];

        digest.update(unpackBuffer, 0, unpackLength);
        digest.doFinal(hashBytes, 0);

        task.extraData = hashBytes;

        // since we can only read the input stream once, make sure to make it again.
        inputStream = new ByteArrayInputStream(unpackBuffer);
    }

    if (repack.canDo(PackAction.Lzma)) {
        ByteArrayOutputStream packedOutputStream = new ByteArrayOutputStream(length); // will be size or smaller.
        LZMA.encode(length, inputStream, packedOutputStream);
        Sys.close(inputStream);

        // convert the output stream to an input stream
        inputStream = new ByteArrayInputStream(packedOutputStream.toByteArray());
        length = inputStream.available();
    }

    // we cannot do BOTH encrypt + LGPL. They are mutually exclusive.
    // LGPL will also not be hashed in the signature generation
    if (repack.canDo(PackAction.Encrypt) && !repack.canDo(PackAction.LGPL)) {
        if (task.encryption != null) {
            ByteArrayOutputStream encryptedOutputStream = task.encryption.encrypt(inputStream, length);

            // convert the output stream to an input stream
            inputStream = new ByteArrayInputStream(encryptedOutputStream.toByteArray());
            length = inputStream.available();
        } else {
            throw new RuntimeException("** Unable to encrypt data when AES information is null!!");
        }
    }

    task.inputStream = inputStream;
}

From source file:org.cryptoworkshop.ximix.client.verify.LinkIndexVerifier.java

License:Apache License

public void verify(int stepNo, boolean isWithPairing, InputStream transcript)
        throws TranscriptVerificationException {
    CMSSignedDataParser cmsParser;//from  ww w  .j  a va2  s .  c o m
    SignerId currentSID;
    Set<Integer> pmIndexes = new HashSet<>();
    Set<Integer> cmIndexes = new HashSet<>();

    try {
        cmsParser = new CMSSignedDataParser(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(),
                transcript);

        ASN1InputStream aIn = new ASN1InputStream(cmsParser.getSignedContent().getContentStream());
        Object obj;
        while ((obj = aIn.readObject()) != null) {
            PostedData pM = PostedData.getInstance(obj);
            MessageCommitment cm = MessageCommitment.getInstance(pM.getData());

            pmIndexes.add(pM.getIndex());
            cmIndexes.add(cm.getNewIndex());
        }

        currentSID = ((SignerInformation) cmsParser.getSignerInfos().getSigners().iterator().next()).getSID();
    } catch (Exception e) {
        throw new TranscriptVerificationException("Cannot parse CMS wrapper on transcript: " + e.getMessage(),
                e);
    }

    SHA512Digest seedDigest = new SHA512Digest();
    byte[] stepSeed = new byte[seedDigest.getDigestSize()];

    // we follow the formulation in "Randomized Partial Checking Revisited" where the seed is
    // modified by the step number, the one difference being that in our case this will only take
    // place at the start of a pairing, or on an individual step.
    seedDigest.update(this.challengeSeed, 0, this.challengeSeed.length);

    seedDigest.update((byte) (stepNo >>> 24));
    seedDigest.update((byte) (stepNo >>> 16));
    seedDigest.update((byte) (stepNo >>> 8));
    seedDigest.update((byte) stepNo);

    seedDigest.doFinal(stepSeed, 0);

    IndexNumberGenerator challenger;

    if (boardSize != 1) {
        challenger = new SeededChallenger(boardSize, stepNo, stepSeed);
    } else {
        challenger = new SerialChallenger(boardSize, stepNo, stepSeed);
    }

    Set<Integer> indexes = new HashSet<>();

    while (challenger.hasNext()) {
        indexes.add(challenger.nextIndex());
    }

    if (boardSize != 1 && isWithPairing) {
        if (!currentSID.equals(lastSID)) {
            for (int i = 0; i != boardSize; i++) {
                nextIndexes.add(i);
            }
        } else {
            indexes = new HashSet<>(nextIndexes);
        }
    }

    lastSID = currentSID;

    if (indexes.size() != pmIndexes.size()) {
        throw new TranscriptVerificationException(
                "Entries in witness table do not correspond to seeding - step " + stepNo + " size( "
                        + indexes.size() + ", " + pmIndexes.size() + ")");
    }

    indexes.removeAll(pmIndexes);
    nextIndexes.removeAll(cmIndexes);

    if (!indexes.isEmpty()) {
        throw new TranscriptVerificationException(
                "Entries in witness table do not correspond to seeding - step " + stepNo + " unaccounted "
                        + indexes.size());
    }
}

From source file:org.cryptoworkshop.ximix.node.mixnet.service.BoardHostingService.java

License:Apache License

private FutureTask<MessageReply> submitToHandle(Message message) {
    if (message instanceof CommandMessage) {
        switch (((CommandMessage) message).getType()) {
        case GENERATE_SEED:
            final SeedMessage seedMessage = SeedMessage.getInstance(message.getPayload());
            return boardExecutor.submitTask(seedMessage.getBoardName(), new Callable<MessageReply>() {
                @Override//  w w  w  .j a v a2  s. co m
                public MessageReply call() throws Exception {
                    String seedKey = seedMessage.getBoardName() + "." + seedMessage.getOperationNumber();
                    if (seedsAndWitnesses.containsKey(seedKey)) {
                        return new MessageReply(MessageReply.Type.ERROR,
                                new ErrorMessage("Duplicate seed generation request for operation "
                                        + seedMessage.getOperationNumber()));
                    }
                    // TODO: specify source of randomness
                    SecureRandom random = new SecureRandom();

                    byte[] seed = new byte[64]; // largest we can manage with SHA-512

                    random.nextBytes(seed);

                    GeneralHashCommitter sha512Committer = new GeneralHashCommitter(new SHA512Digest(), random);

                    Commitment commitment = sha512Committer.commit(seed);

                    seedsAndWitnesses.put(seedKey, new byte[][] { seed, commitment.getSecret() });

                    SeedCommitmentMessage seedCommitmentMessage = new SeedCommitmentMessage(
                            seedMessage.getBoardName(), seedMessage.getOperationNumber(),
                            commitment.getCommitment());

                    CMSSignedDataGenerator cmsGen = new CMSSignedDataGenerator();

                    KeyStore nodeCAStore = nodeContext.getNodeCAStore();
                    Certificate[] nodeCerts = nodeCAStore.getCertificateChain("nodeCA");

                    cmsGen.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                            .build("SHA256withECDSA", (PrivateKey) nodeCAStore.getKey("nodeCA", new char[0]),
                                    (X509Certificate) nodeCerts[0]));

                    for (Certificate cert : nodeCerts) {
                        cmsGen.addCertificate(new JcaX509CertificateHolder((X509Certificate) cert));
                    }

                    return new MessageReply(MessageReply.Type.OKAY, cmsGen
                            .generate(new CMSProcessableByteArray(seedCommitmentMessage.getEncoded()), true)
                            .toASN1Structure());
                }
            });
        case FETCH_SEED:
            final SeedMessage seedFetchMessage = SeedMessage.getInstance(message.getPayload());
            return boardExecutor.submitTask(seedFetchMessage.getBoardName(), new Callable<MessageReply>() {
                @Override
                public MessageReply call() throws Exception {
                    String seedKey = seedFetchMessage.getBoardName() + "."
                            + seedFetchMessage.getOperationNumber();
                    byte[][] seedAndWitness = seedsAndWitnesses.get(seedKey);

                    if (seedAndWitness == null) {
                        return new MessageReply(MessageReply.Type.ERROR,
                                new ErrorMessage("Unknown seed requested for key: " + seedKey));
                    }

                    return new MessageReply(MessageReply.Type.OKAY,
                            new SeedAndWitnessMessage(seedAndWitness[0], seedAndWitness[1]));
                }
            });
        case GET_BOARD_DETAILS:
            Callable<MessageReply> replyCallable = new Callable<MessageReply>() {
                @Override
                public MessageReply call() throws Exception {
                    String[] boardNames = boardRegistry.getBoardNames();
                    BoardDetailMessage[] details = new BoardDetailMessage[boardNames.length];

                    int count = 0;
                    for (String boardName : boardNames) {
                        BulletinBoard board = boardRegistry.getBoard(boardName);

                        details[count++] = new BoardDetailMessage(boardName, nodeContext.getName(),
                                board.size(), board.getBackupHost());
                    }

                    return new MessageReply(MessageReply.Type.OKAY, new DERSequence(details));
                }
            };
            FutureTask<MessageReply> task = new FutureTask<>(replyCallable);

            boardExecutor.execute(task);

            return task;
        case GET_BOARD_HOST:
            final BoardMessage boardMessage = BoardMessage.getInstance(message.getPayload());

            return boardExecutor.submitTask(boardMessage.getBoardName(), new Callable<MessageReply>() {
                @Override
                public MessageReply call() throws Exception {
                    String boardHost = nodeContext.getBoardHost(boardMessage.getBoardName());

                    if (boardHost != null) {
                        return new MessageReply(MessageReply.Type.OKAY, new DERUTF8String(boardHost));
                    } else {
                        return new MessageReply(MessageReply.Type.OKAY, DERNull.INSTANCE);
                    }
                }
            });
        case ACTIVATE_BOARD:
            final BoardMessage activateBoardMessage = BoardMessage.getInstance(message.getPayload());
            return boardExecutor.submitTask(activateBoardMessage.getBoardName(), new Callable<MessageReply>() {
                @Override
                public MessageReply call() throws Exception {
                    boardRegistry.activateBoard(activateBoardMessage.getBoardName());
                    return new MessageReply(MessageReply.Type.OKAY, new DERUTF8String(nodeContext.getName()));
                }
            });
        case SUSPEND_BOARD:
            final BoardMessage suspendBoardMessage = BoardMessage.getInstance(message.getPayload());
            return boardExecutor.submitTask(suspendBoardMessage.getBoardName(), new Callable<MessageReply>() {
                @Override
                public MessageReply call() throws Exception {
                    if (boardRegistry.isSuspended(suspendBoardMessage.getBoardName())) {
                        return new MessageReply(MessageReply.Type.ERROR, new BoardErrorStatusMessage(
                                suspendBoardMessage.getBoardName(), BoardErrorStatusMessage.Status.SUSPENDED));
                    }
                    boardRegistry.suspendBoard(suspendBoardMessage.getBoardName());
                    return new MessageReply(MessageReply.Type.OKAY, new DERUTF8String(nodeContext.getName()));
                }
            });
        case BOARD_CREATE:
            final CreateBoardMessage createBoardMessage = CreateBoardMessage.getInstance(message.getPayload());

            return boardExecutor.submitTask(createBoardMessage.getBoardName(), new Callable<MessageReply>() {
                @Override
                public MessageReply call() throws Exception {
                    if (boardRegistry.hasBoard(createBoardMessage.getBoardName())) {
                        return new MessageReply(MessageReply.Type.ERROR,
                                new BoardErrorStatusMessage(createBoardMessage.getBoardName(),
                                        BoardErrorStatusMessage.Status.ALREADY_EXISTS));
                    }

                    if (createBoardMessage.getBackUpHost() != null) {
                        boardRegistry.createBoard(createBoardMessage.getBoardName(),
                                createBoardMessage.getBackUpHost());
                    } else {
                        boardRegistry.createBoard(createBoardMessage.getBoardName());
                    }

                    return new MessageReply(MessageReply.Type.OKAY, new DERUTF8String(nodeContext.getName()));
                }
            });
        case BACKUP_BOARD_CREATE:
            final BoardMessage backupBoardCreateMessage = BoardMessage.getInstance(message.getPayload());
            return boardExecutor.submitTask(backupBoardCreateMessage.getBoardName(),
                    new Callable<MessageReply>() {
                        @Override
                        public MessageReply call() throws Exception {

                            boardRegistry.createBackupBoard(backupBoardCreateMessage.getBoardName());

                            return new MessageReply(MessageReply.Type.OKAY,
                                    new DERUTF8String(nodeContext.getName()));
                        }
                    });
        case BOARD_DOWNLOAD_LOCK:
            final BoardMessage downloadLockBoardMessage = BoardMessage.getInstance(message.getPayload());
            return boardExecutor.submitTask(downloadLockBoardMessage.getBoardName(),
                    new Callable<MessageReply>() {
                        @Override
                        public MessageReply call() throws Exception {
                            if (boardRegistry.isLocked(downloadLockBoardMessage.getBoardName())) {
                                return new MessageReply(MessageReply.Type.ERROR,
                                        new BoardErrorStatusMessage(downloadLockBoardMessage.getBoardName(),
                                                BoardErrorStatusMessage.Status.SUSPENDED));
                            }
                            boardRegistry.downloadLock(downloadLockBoardMessage.getBoardName());
                            return new MessageReply(MessageReply.Type.OKAY,
                                    new DERUTF8String(nodeContext.getName()));
                        }
                    });
        case BOARD_DOWNLOAD_UNLOCK:
            final BoardMessage downloadUnlockBoardMessage = BoardMessage.getInstance(message.getPayload());
            return boardExecutor.submitTask(downloadUnlockBoardMessage.getBoardName(),
                    new Callable<MessageReply>() {
                        @Override
                        public MessageReply call() throws Exception {
                            boardRegistry.downloadUnlock(downloadUnlockBoardMessage.getBoardName());
                            return new MessageReply(MessageReply.Type.OKAY,
                                    new DERUTF8String(nodeContext.getName()));
                        }
                    });
        case BOARD_SHUFFLE_LOCK:
            final BoardMessage shuffleLockBoardMessage = BoardMessage.getInstance(message.getPayload());
            return boardExecutor.submitTask(shuffleLockBoardMessage.getBoardName(),
                    new Callable<MessageReply>() {
                        @Override
                        public MessageReply call() throws Exception {
                            if (boardRegistry.isLocked(shuffleLockBoardMessage.getBoardName())) {
                                return new MessageReply(MessageReply.Type.ERROR,
                                        new BoardErrorStatusMessage(shuffleLockBoardMessage.getBoardName(),
                                                BoardErrorStatusMessage.Status.SUSPENDED));
                            }
                            boardRegistry.shuffleLock(shuffleLockBoardMessage.getBoardName());
                            return new MessageReply(MessageReply.Type.OKAY,
                                    new DERUTF8String(nodeContext.getName()));
                        }
                    });
        case BOARD_SHUFFLE_UNLOCK:
            final BoardMessage shuffleUnlockBoardMessage = BoardMessage.getInstance(message.getPayload());

            return boardExecutor.submitTask(shuffleUnlockBoardMessage.getBoardName(),
                    new Callable<MessageReply>() {
                        @Override
                        public MessageReply call() throws Exception {

                            boardRegistry.shuffleUnlock(shuffleUnlockBoardMessage.getBoardName());
                            return new MessageReply(MessageReply.Type.OKAY,
                                    new DERUTF8String(nodeContext.getName()));
                        }
                    });
        case FETCH_BOARD_STATUS:
            final TransitBoardMessage transitBoardMessage = TransitBoardMessage
                    .getInstance(message.getPayload());
            return boardExecutor.submitTask(transitBoardMessage.getBoardName(), new Callable<MessageReply>() {
                @Override
                public MessageReply call() throws Exception {
                    if (boardRegistry.isInTransit(transitBoardMessage.getOperationNumber(),
                            transitBoardMessage.getBoardName(), transitBoardMessage.getStepNumber())) {
                        return new MessageReply(MessageReply.Type.OKAY, new BoardStatusMessage(
                                transitBoardMessage.getBoardName(), BoardStatusMessage.Status.IN_TRANSIT));
                    }
                    if (boardRegistry.isComplete(transitBoardMessage.getOperationNumber(),
                            transitBoardMessage.getBoardName(), transitBoardMessage.getStepNumber())) {
                        return new MessageReply(MessageReply.Type.OKAY, new BoardStatusMessage(
                                transitBoardMessage.getBoardName(), BoardStatusMessage.Status.COMPLETE));
                    }
                    return new MessageReply(MessageReply.Type.OKAY, new BoardStatusMessage(
                            transitBoardMessage.getBoardName(), BoardStatusMessage.Status.UNKNOWN));
                }
            });
        case FETCH_BOARD_COMPLETION_STATUS:
            final BoardMessage compStatusBoardMessage = BoardMessage.getInstance(message.getPayload());
            return boardExecutor.submitTask(compStatusBoardMessage.getBoardName(),
                    new Callable<MessageReply>() {
                        @Override
                        public MessageReply call() throws Exception {
                            if (boardRegistry.isLocked(compStatusBoardMessage.getBoardName())) {
                                return new MessageReply(MessageReply.Type.OKAY,
                                        new BoardStatusMessage(compStatusBoardMessage.getBoardName(),
                                                BoardStatusMessage.Status.IN_TRANSIT));
                            }
                            return new MessageReply(MessageReply.Type.OKAY, new BoardStatusMessage(
                                    compStatusBoardMessage.getBoardName(), BoardStatusMessage.Status.COMPLETE));
                        }
                    });
        case START_SHUFFLE_AND_MOVE_BOARD_TO_NODE:
            final CopyAndMoveMessage startPandMmessage = CopyAndMoveMessage.getInstance(message.getPayload());

            return boardExecutor.submitTask(startPandMmessage.getBoardName(), new Callable<MessageReply>() {
                @Override
                public MessageReply call() throws Exception {
                    if (!boardRegistry.isShuffleLocked(startPandMmessage.getBoardName())) {
                        return new MessageReply(MessageReply.Type.ERROR,
                                new BoardErrorStatusMessage(startPandMmessage.getBoardName(),
                                        BoardErrorStatusMessage.Status.NOT_SHUFFLE_LOCKED));
                    }

                    nodeContext.execute(new CopyAndMoveTask(nodeContext, boardRegistry,
                            getPeerConnection(startPandMmessage.getDestinationNode()), startPandMmessage));

                    return new MessageReply(MessageReply.Type.OKAY, new DERUTF8String(nodeContext.getName()));
                }
            });
        case SHUFFLE_AND_MOVE_BOARD_TO_NODE:
            final PermuteAndMoveMessage pAndmMessage = PermuteAndMoveMessage.getInstance(message.getPayload());

            return boardExecutor.submitTask(pAndmMessage.getBoardName(), new Callable<MessageReply>() {
                @Override
                public MessageReply call() throws Exception {
                    nodeContext.execute(new TransformShuffleAndMoveTask(nodeContext, boardRegistry,
                            getPeerConnection(pAndmMessage.getDestinationNode()), pAndmMessage));

                    return new MessageReply(MessageReply.Type.OKAY, new DERUTF8String(nodeContext.getName()));
                }
            });
        case RETURN_TO_BOARD:
            final TransitBoardMessage returnToBoardMessage = TransitBoardMessage
                    .getInstance(message.getPayload());

            return boardExecutor.submitTask(returnToBoardMessage.getBoardName(), new Callable<MessageReply>() {
                @Override
                public MessageReply call() throws Exception {
                    nodeContext
                            .execute(new ReturnToBoardTask(nodeContext, boardRegistry, returnToBoardMessage));
                    return new MessageReply(MessageReply.Type.OKAY, new DERUTF8String(nodeContext.getName()));
                }
            });
        case INITIATE_INTRANSIT_BOARD:
            final TransitBoardMessage initiateTransitBoardMessage = TransitBoardMessage
                    .getInstance(message.getPayload());

            return boardExecutor.submitTask(initiateTransitBoardMessage.getBoardName(),
                    new Callable<MessageReply>() {
                        @Override
                        public MessageReply call() throws Exception {
                            boardRegistry.markInTransit(initiateTransitBoardMessage.getOperationNumber(),
                                    initiateTransitBoardMessage.getBoardName(),
                                    initiateTransitBoardMessage.getStepNumber());
                            boardRegistry.getTransitBoard(initiateTransitBoardMessage.getOperationNumber(),
                                    initiateTransitBoardMessage.getBoardName(),
                                    initiateTransitBoardMessage.getStepNumber()).clear();
                            return new MessageReply(MessageReply.Type.OKAY,
                                    new DERUTF8String(nodeContext.getName()));
                        }
                    });
        case TRANSFER_TO_BOARD:
            final BoardUploadBlockMessage uploadMessage = BoardUploadBlockMessage
                    .getInstance(message.getPayload());

            return boardExecutor.submitTask(uploadMessage.getBoardName(), new Callable<MessageReply>() {
                @Override
                public MessageReply call() throws Exception {
                    boardRegistry.markInTransit(uploadMessage.getOperationNumber(),
                            uploadMessage.getBoardName(), uploadMessage.getStepNumber());
                    boardRegistry
                            .getTransitBoard(uploadMessage.getOperationNumber(), uploadMessage.getBoardName(),
                                    uploadMessage.getStepNumber())
                            .postMessageBlock(uploadMessage.getMessageBlock());
                    return new MessageReply(MessageReply.Type.OKAY, new DERUTF8String(nodeContext.getName()));
                }
            });
        case UPLOAD_TO_BOARD:
            final BoardUploadBlockMessage uploadToBoardMessage = BoardUploadBlockMessage
                    .getInstance(message.getPayload());

            return boardExecutor.submitTask(uploadToBoardMessage.getBoardName(), new Callable<MessageReply>() {
                @Override
                public MessageReply call() {
                    boardRegistry.markInTransit(uploadToBoardMessage.getOperationNumber(),
                            uploadToBoardMessage.getBoardName(), uploadToBoardMessage.getStepNumber());
                    boardRegistry.getBoard(uploadToBoardMessage.getBoardName())
                            .postMessageBlock(uploadToBoardMessage.getMessageBlock());

                    return new MessageReply(MessageReply.Type.OKAY, new DERUTF8String(nodeContext.getName()));
                }
            });
        case CLEAR_BACKUP_BOARD:
            final BoardMessage backupBoardMessage = BoardMessage.getInstance(message.getPayload());

            return boardExecutor.submitBackupTask(backupBoardMessage.getBoardName(),
                    new Callable<MessageReply>() {
                        @Override
                        public MessageReply call() {
                            // TODO: maybe backup the current backup locally?
                            boardRegistry.getBackupBoard(backupBoardMessage.getBoardName()).clear();
                            return new MessageReply(MessageReply.Type.OKAY,
                                    new DERUTF8String(nodeContext.getName()));
                        }
                    });
        case TRANSFER_TO_BACKUP_BOARD:
            final BoardUploadIndexedMessage uploadIndexedMessage = BoardUploadIndexedMessage
                    .getInstance(message.getPayload());

            return boardExecutor.submitBackupTask(uploadIndexedMessage.getBoardName(),
                    new Callable<MessageReply>() {
                        @Override
                        public MessageReply call() {
                            boardRegistry.getBackupBoard(uploadIndexedMessage.getBoardName())
                                    .postMessages(uploadIndexedMessage.getData());
                            return new MessageReply(MessageReply.Type.OKAY,
                                    new DERUTF8String(nodeContext.getName()));
                        }
                    });
        case TRANSFER_TO_BOARD_ENDED:
            final TransitBoardMessage transferToBoardEndedMessage = TransitBoardMessage
                    .getInstance(message.getPayload());

            return boardExecutor.submitTask(transferToBoardEndedMessage.getBoardName(),
                    new Callable<MessageReply>() {
                        public MessageReply call() {
                            boardRegistry.markCompleted(transferToBoardEndedMessage.getOperationNumber(),
                                    transferToBoardEndedMessage.getBoardName(),
                                    transferToBoardEndedMessage.getStepNumber());
                            return new MessageReply(MessageReply.Type.OKAY,
                                    new DERUTF8String(nodeContext.getName()));
                        }
                    });
        case DOWNLOAD_BOARD_CONTENTS:
            final BoardDownloadMessage downloadRequest = BoardDownloadMessage.getInstance(message.getPayload());

            return boardExecutor.submitTask(downloadRequest.getBoardName(), new Callable<MessageReply>() {
                @Override
                public MessageReply call() {
                    if (!boardRegistry.isDownloadLocked(downloadRequest.getBoardName())) {
                        return new MessageReply(MessageReply.Type.ERROR,
                                new BoardErrorStatusMessage(downloadRequest.getBoardName(),
                                        BoardErrorStatusMessage.Status.NOT_DOWNLOAD_LOCKED));
                    }

                    BulletinBoard board = boardRegistry.getBoard(downloadRequest.getBoardName());

                    PostedMessageBlock messages = board.removeMessages(
                            new PostedMessageBlock.Builder(downloadRequest.getMaxNumberOfMessages()));

                    return new MessageReply(MessageReply.Type.OKAY, messages);
                }
            });
        case DOWNLOAD_SHUFFLE_TRANSCRIPT:
            final TranscriptDownloadMessage transcriptDownloadMessage = TranscriptDownloadMessage
                    .getInstance(message.getPayload());
            final BulletinBoard transitBoard = boardRegistry.getTransitBoard(
                    transcriptDownloadMessage.getOperationNumber(), transcriptDownloadMessage.getStepNo());

            return boardExecutor.submitTask(transitBoard.getName(), new Callable<MessageReply>() {
                @Override
                public MessageReply call() throws Exception {
                    boolean isCopyBoard = isCopyBoard(transitBoard);
                    String challengerKey = getChallengerKey(transcriptDownloadMessage,
                            isCopyBoard || (transitBoard.size() == 1));

                    IndexNumberGenerator challenger = challengers.get(challengerKey);
                    if (challenger == null) {
                        if (transitBoard.size() == 1) {
                            challenger = new SerialChallenger(1, transcriptDownloadMessage.getStepNo(),
                                    transcriptDownloadMessage.getSeed());
                        } else if (TranscriptType.GENERAL == transcriptDownloadMessage.getType()) {
                            challenger = new SerialChallenger(
                                    transitBoard.transcriptSize(TranscriptType.GENERAL),
                                    transcriptDownloadMessage.getStepNo(), transcriptDownloadMessage.getSeed());
                        } else {
                            SHA512Digest seedDigest = new SHA512Digest();
                            byte[] challengeSeed = new byte[seedDigest.getDigestSize()];

                            if (transcriptDownloadMessage.getSeed() != null) {
                                byte[] originalSeed = transcriptDownloadMessage.getSeed();

                                nodeContext.getEventNotifier().notify(EventNotifier.Level.INFO,
                                        "Original seed: " + new String(Hex.encode(originalSeed)));

                                // we follow the formulation in "Randomized Partial Checking Revisited" where the seed is
                                // modified by the step number, the one difference being that in our case this will only take
                                // place at the start of a pairing, or on an individual step.
                                seedDigest.update(originalSeed, 0, originalSeed.length);

                                int stepNo = transcriptDownloadMessage.getStepNo();

                                seedDigest.update((byte) (stepNo >>> 24));
                                seedDigest.update((byte) (stepNo >>> 16));
                                seedDigest.update((byte) (stepNo >>> 8));
                                seedDigest.update((byte) stepNo);

                                seedDigest.doFinal(challengeSeed, 0);
                            }

                            nodeContext.getEventNotifier().notify(EventNotifier.Level.INFO,
                                    "Challenge seed: " + transcriptDownloadMessage.getStepNo() + " "
                                            + new String(Hex.encode(challengeSeed)));

                            try {
                                if (isCopyBoard) {
                                    challenger = new SerialChallenger(
                                            transitBoard.transcriptSize(transcriptDownloadMessage.getType()),
                                            transcriptDownloadMessage.getStepNo(), challengeSeed);
                                } else if (transcriptDownloadMessage.isWithPairing()) {
                                    // TODO: maybe configure
                                    int chunkSize = 100;
                                    IndexNumberGenerator sourceGenerator = new SerialChallenger(
                                            transitBoard.size(), 0, null);
                                    int[] indexes = new int[transitBoard.size()];
                                    int count = 0;
                                    while (sourceGenerator.hasNext()) {
                                        TranscriptBlock transcript = transitBoard.fetchTranscriptData(
                                                TranscriptType.WITNESSES, sourceGenerator,
                                                new TranscriptBlock.Builder(0, chunkSize));

                                        for (Enumeration en = transcript.getDetails().getObjects(); en
                                                .hasMoreElements();) {
                                            PostedData msg = PostedData.getInstance(en.nextElement());

                                            indexes[count++] = MessageCommitment.getInstance(msg.getData())
                                                    .getNewIndex();
                                        }
                                    }

                                    challenger = new PairedChallenger(indexes,
                                            transcriptDownloadMessage.getStepNo(),
                                            (IndexNumberGenerator) witnessChallengerConstructor.newInstance(
                                                    transitBoard.transcriptSize(
                                                            transcriptDownloadMessage.getType()),
                                                    transcriptDownloadMessage.getStepNo(), challengeSeed));
                                } else {
                                    challenger = (IndexNumberGenerator) witnessChallengerConstructor
                                            .newInstance(
                                                    transitBoard.transcriptSize(
                                                            transcriptDownloadMessage.getType()),
                                                    transcriptDownloadMessage.getStepNo(), challengeSeed);
                                }
                            } catch (Exception e) {
                                nodeContext.getEventNotifier().notify(EventNotifier.Level.ERROR, e);

                                return new MessageReply(MessageReply.Type.ERROR, new ErrorMessage(
                                        "Unable to create challenger on " + nodeContext.getName()));
                            }
                        }
                        challengers.put(challengerKey, challenger);
                    }

                    if (challenger instanceof PairedChallenger) {
                        ((PairedChallenger) challenger).setStepNo(transcriptDownloadMessage.getStepNo());
                    }

                    TranscriptBlock transcriptBlock = transitBoard.fetchTranscriptData(
                            transcriptDownloadMessage.getType(), challenger,
                            new TranscriptBlock.Builder(transcriptDownloadMessage.getStepNo(),
                                    transcriptDownloadMessage.getMaxNumberOfMessages()));

                    String generatorKey = getTranscriptGeneratorKey(transcriptDownloadMessage);
                    TranscriptGenerator transGen = transcriptGenerators.get(generatorKey);
                    if (transGen == null) {
                        transGen = new TranscriptGenerator();

                        transcriptGenerators.put(generatorKey, transGen);
                    }

                    if (transcriptBlock.size() != 0) {
                        for (Enumeration en = transcriptBlock.getDetails().getObjects(); en
                                .hasMoreElements();) {
                            transGen.writeFragment(((ASN1Object) en.nextElement()).getEncoded());
                        }

                        return new MessageReply(MessageReply.Type.OKAY, new TranscriptTransferMessage(
                                transcriptBlock.getStepNo(), transGen.getFragment()));
                    }

                    if (transGen.hasData()) {
                        transGen.finish();
                        return new MessageReply(MessageReply.Type.OKAY, new TranscriptTransferMessage(
                                transcriptBlock.getStepNo(), transGen.getFragment()));
                    }

                    // end of data
                    return new MessageReply(MessageReply.Type.OKAY,
                            new TranscriptTransferMessage(transcriptBlock.getStepNo()));
                }
            });
        case DOWNLOAD_SHUFFLE_TRANSCRIPT_STEPS:
            final TranscriptQueryMessage transcriptQueryMessage = TranscriptQueryMessage
                    .getInstance(message.getPayload());

            FutureTask<MessageReply> dstsTask = new FutureTask(new Callable<MessageReply>() {
                @Override
                public MessageReply call() throws Exception {
                    List<String> transitBoardNames = boardRegistry
                            .getTransitBoardNames(transcriptQueryMessage.getOperationNumber());
                    int[] stepNos = new int[transitBoardNames.size()];
                    String boardName = "";

                    for (int i = 0; i != stepNos.length; i++) {
                        String name = transitBoardNames.get(i);
                        boardName = name.substring(name.indexOf('.') + 1, name.lastIndexOf('.'));

                        stepNos[i] = Integer.parseInt(name.substring(name.lastIndexOf('.') + 1));
                    }

                    return new MessageReply(MessageReply.Type.OKAY,
                            new TranscriptQueryResponse(queryCounter.incrementAndGet(), boardName, stepNos));
                }
            });

            nodeContext.getExecutorService().submit(dstsTask);

            return dstsTask;
        default:
            FutureTask<MessageReply> eTask = new FutureTask(new Callable<MessageReply>() {
                @Override
                public MessageReply call() throws Exception {
                    return new MessageReply(MessageReply.Type.ERROR, new ErrorMessage("Unknown command"));
                }
            });

            nodeContext.getExecutorService().submit(eTask);

            return eTask;
        }
    } else {
        switch (((ClientMessage) message).getType()) {
        case UPLOAD_TO_BOARD:
            final BoardUploadMessage uploadMessage = BoardUploadMessage.getInstance(message.getPayload());

            return boardExecutor.submitTask(uploadMessage.getBoardName(), new Callable<MessageReply>() {
                @Override
                public MessageReply call() {
                    if (boardRegistry.isLocked(uploadMessage.getBoardName())) {
                        return new MessageReply(MessageReply.Type.ERROR, new BoardErrorStatusMessage(
                                uploadMessage.getBoardName(), BoardErrorStatusMessage.Status.SUSPENDED));
                    }

                    byte[][] messages = uploadMessage.getData();

                    if (messages.length == 1) {
                        boardRegistry.getBoard(uploadMessage.getBoardName()).postMessage(messages[0]);
                    } else {
                        boardRegistry.getBoard(uploadMessage.getBoardName()).postMessages(messages);
                    }

                    return new MessageReply(MessageReply.Type.OKAY, new DERUTF8String(nodeContext.getName()));
                }
            });
        default:
            FutureTask<MessageReply> eTask = new FutureTask(new Callable<MessageReply>() {
                @Override
                public MessageReply call() throws Exception {
                    return new MessageReply(MessageReply.Type.ERROR, new DERUTF8String("Unknown command"));
                }
            });

            nodeContext.getExecutorService().submit(eTask);

            return eTask;
        }
    }
}

From source file:org.jcryptool.visual.hashing.views.HashingView.java

License:Open Source License

private String computeHash(String hashName, String inputText, Text hashText) {
    hash = hash.getName(hashName);/*  w  ww  .  j a va2 s  .c o  m*/
    byte[] digest = null;
    switch (hash) {
    case MD2:
        MD2Digest md2 = new MD2Digest();
        md2.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[md2.getDigestSize()];
        md2.doFinal(digest, 0);

        break;
    case MD4:
        MD4Digest md4 = new MD4Digest();
        md4.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[md4.getDigestSize()];
        md4.doFinal(digest, 0);

        break;
    case MD5:
        MD5Digest md5 = new MD5Digest();
        md5.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[md5.getDigestSize()];
        md5.doFinal(digest, 0);

        break;
    case SHA1:
        SHA1Digest sha1 = new SHA1Digest();
        sha1.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha1.getDigestSize()];
        sha1.doFinal(digest, 0);

        break;
    case SHA256:
        SHA256Digest sha256 = new SHA256Digest();
        sha256.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha256.getDigestSize()];
        sha256.doFinal(digest, 0);

        break;
    case SHA512:
        SHA512Digest sha512 = new SHA512Digest();
        sha512.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha512.getDigestSize()];
        sha512.doFinal(digest, 0);

        break;
    case SHA3_224:
        SHA3.Digest224 sha3_224 = new SHA3.Digest224();
        sha3_224.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha3_224.getDigestLength()];
        digest = sha3_224.digest();

        break;
    case SHA3_256:
        SHA3.Digest256 sha3_256 = new SHA3.Digest256();
        sha3_256.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha3_256.getDigestLength()];
        digest = sha3_256.digest();

        break;
    case SHA3_384:
        SHA3.Digest384 sha3_384 = new SHA3.Digest384();
        sha3_384.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha3_384.getDigestLength()];
        digest = sha3_384.digest();

        break;
    case SHA3_512:
        SHA3.Digest512 sha3_512 = new SHA3.Digest512();
        sha3_512.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sha3_512.getDigestLength()];
        digest = sha3_512.digest();

        break;
    case SKEIN_256:
        Skein.Digest_256_256 skein_256 = new Skein.Digest_256_256();
        skein_256.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[skein_256.getDigestLength()];
        digest = skein_256.digest();

        break;
    case SKEIN_512:
        Skein.Digest_512_512 skein_512 = new Skein.Digest_512_512();
        skein_512.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[skein_512.getDigestLength()];
        digest = skein_512.digest();

        break;
    case SKEIN_1024:
        Skein.Digest_1024_1024 skein_1024 = new Skein.Digest_1024_1024();
        skein_1024.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[skein_1024.getDigestLength()];
        digest = skein_1024.digest();

        break;
    case RIPEMD160:
        RIPEMD160Digest ripemd160 = new RIPEMD160Digest();
        ripemd160.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[ripemd160.getDigestSize()];
        ripemd160.doFinal(digest, 0);

        break;
    case SM3:
        SM3Digest sm3 = new SM3Digest();
        sm3.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[sm3.getDigestSize()];
        sm3.doFinal(digest, 0);

        break;
    case TIGER:
        TigerDigest tiger = new TigerDigest();
        tiger.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[tiger.getDigestSize()];
        tiger.doFinal(digest, 0);

        break;
    case GOST3411:
        GOST3411Digest gost3411 = new GOST3411Digest();
        gost3411.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[gost3411.getDigestSize()];
        gost3411.doFinal(digest, 0);

        break;
    case WHIRLPOOL:
        WhirlpoolDigest whirlpool = new WhirlpoolDigest();
        whirlpool.update(inputText.getBytes(), 0, inputText.getBytes().length);
        digest = new byte[whirlpool.getDigestSize()];
        whirlpool.doFinal(digest, 0);

        break;
    default:
        break;
    }

    String hashHexValue = new String(Hex.encode(digest));
    if (btnHexadezimal.getSelection()) {
        String hashValueOutput = hashHexValue.toUpperCase().replaceAll(".{2}", "$0 "); //$NON-NLS-1$ //$NON-NLS-2$
        hashText.setText(hashValueOutput);
    } else if (btnDezimal.getSelection()) {
        String hashValue = hexToDecimal(hashHexValue);
        hashValue = hashValue.replaceAll(".{3}", "$0 "); //$NON-NLS-1$ //$NON-NLS-2$
        hashText.setText(hashValue);
    } else if (btnBinary.getSelection()) {
        String hashValue = hexToBinary(hashHexValue);
        hashValue = hashValue.replaceAll(".{8}", "$0#"); //$NON-NLS-1$ //$NON-NLS-2$
        hashText.setText(hashValue);
    }

    return hashHexValue;
}

From source file:org.ourfilesystem.security.SecurityTools.java

License:Open Source License

public static byte[] digestPublicKey(PublicKeySet k) {
    SHA512Digest dig = new SHA512Digest();
    DigestRSAPublicKey(dig, (RSAKeyParameters) k.getPublicEncryptionKey());
    DigestRSAPublicKey(dig, (RSAKeyParameters) k.getPublicSigningKey());
    byte sig[] = new byte[dig.getDigestSize()];
    dig.doFinal(sig, 0);/*from w  w  w.  j  ava  2 s  .co m*/
    return sig;
}

From source file:org.ourfilesystem.security.SecurityTools.java

License:Open Source License

public static BBytes digestFile(File f, long offset, long size) throws IOException {
    SHA512Digest d = new SHA512Digest();
    digestFile(d, f, offset, size);/*  ww  w.j  ava  2s  .c o m*/
    byte sig[] = new byte[d.getDigestSize()];
    d.doFinal(sig, 0);
    return new BBytes(sig);
}

From source file:org.ourfilesystem.security.SecurityTools.java

License:Open Source License

public static BBytes digestPeerLocation(Peer p) {
    SHA512Digest d = new SHA512Digest();
    digestString(d, p.getIntroduction());
    digestString(d, (String) p.getLocation());
    digestString(d, (String) p.getNickname());
    digestLong(d, p.getUpdateCount());//w  w  w. ja v a 2  s.  c o m
    digestDate(d, p.getRDate());
    byte id[] = p.getIdentity().getBytes();
    d.update(id, 0, id.length);
    byte sig[] = new byte[d.getDigestSize()];
    d.doFinal(sig, 0);
    return new BBytes(sig);
}

From source file:org.ourfilesystem.security.SecurityTools.java

License:Open Source License

public static BBytes digestPost(Post p, BBytes peerid) {
    SHA512Digest d = new SHA512Digest();
    digestBBytes(d, p.getFileReferenceDigest());
    digestBBytes(d, p.getNetworkId());//from   w  w  w .j av a 2  s .c  o  m
    digestLong(d, p.getPostNumber());
    if (p.getMessage() != null && p.getMessage() instanceof PostMessage) {
        PostMessage pm = (PostMessage) p.getMessage();
        digestPostMessage(d, pm);
    } else if (p.getMessage() != null && p.getMessage() instanceof PostTemplate) {
        PostTemplate pt = (PostTemplate) p.getMessage();
        digestPostTemplate(d, pt);
    } else if (p.getMessage() == null) {
        d.update((byte) 0);
    } else {
        throw new RuntimeException("Unknown message type!");
    }
    digestBoolean(d, p.isPosterHasFile());
    digestBBytes(d, peerid);
    digestDate(d, p.getRDate());
    byte sig[] = new byte[d.getDigestSize()];
    d.doFinal(sig, 0);
    return new BBytes(sig);
}

From source file:org.ourfilesystem.security.SecurityTools.java

License:Open Source License

public static BBytes digestPublicPost(PublicPost p, BBytes peerid) {
    SHA512Digest d = new SHA512Digest();
    digestBBytes(d, p.getNetworkId());/* w w w.j a v a2s  .c  o m*/
    digestLong(d, p.getPostNumber());
    digestBoolean(d, p.isEncrypted());
    if (p.getMessage() instanceof BBytes) {
        BBytes mb = (BBytes) p.getMessage();
        digestBBytes(d, mb);
    } else {
        String str = (String) p.getMessage();
        digestString(d, str);
    }
    digestBBytes(d, peerid);
    digestDate(d, p.getRDate());
    byte sig[] = new byte[d.getDigestSize()];
    d.doFinal(sig, 0);
    return new BBytes(sig);
}