Example usage for java.math BigInteger BigInteger

List of usage examples for java.math BigInteger BigInteger

Introduction

In this page you can find the example usage for java.math BigInteger BigInteger.

Prototype

private BigInteger(long val) 

Source Link

Document

Constructs a BigInteger with the specified value, which may not be zero.

Usage

From source file:com.netscape.cmstools.OCSPClient.java

public static void main(String args[]) throws Exception {

    Options options = createOptions();/*w w  w  . j a  v  a2s  . c o  m*/
    CommandLine cmd = null;

    try {
        CommandLineParser parser = new PosixParser();
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        printError(e);
        System.exit(1);
    }

    if (cmd.hasOption("help")) {
        printHelp();
        System.exit(0);
    }

    boolean verbose = cmd.hasOption("v");

    String databaseDir = cmd.getOptionValue("d", ".");
    String hostname = cmd.getOptionValue("h", InetAddress.getLocalHost().getCanonicalHostName());
    int port = Integer.parseInt(cmd.getOptionValue("p", "8080"));
    String path = cmd.getOptionValue("t", "/ocsp/ee/ocsp");
    String caNickname = cmd.getOptionValue("c", "CA Signing Certificate");
    int times = Integer.parseInt(cmd.getOptionValue("n", "1"));

    String input = cmd.getOptionValue("input");
    String serial = cmd.getOptionValue("serial");
    String output = cmd.getOptionValue("output");

    if (times < 1) {
        printError("Invalid number of submissions");
        System.exit(1);
    }

    try {
        if (verbose)
            System.out.println("Initializing security database");
        CryptoManager.initialize(databaseDir);

        String url = "http://" + hostname + ":" + port + path;

        OCSPProcessor processor = new OCSPProcessor();
        processor.setVerbose(verbose);

        OCSPRequest request;
        if (serial != null) {
            if (verbose)
                System.out.println("Creating request for serial number " + serial);

            BigInteger serialNumber = new BigInteger(serial);
            request = processor.createRequest(caNickname, serialNumber);

        } else if (input != null) {
            if (verbose)
                System.out.println("Loading request from " + input);

            try (FileInputStream in = new FileInputStream(input)) {
                byte[] data = new byte[in.available()];
                in.read(data);
                request = processor.createRequest(data);
            }

        } else {
            throw new Exception("Missing serial number or input file.");
        }

        OCSPResponse response = null;
        for (int i = 0; i < times; i++) {

            if (verbose)
                System.out.println("Submitting OCSP request");
            response = processor.submitRequest(url, request);

            ResponseBytes bytes = response.getResponseBytes();
            BasicOCSPResponse basic = (BasicOCSPResponse) BasicOCSPResponse.getTemplate()
                    .decode(new ByteArrayInputStream(bytes.getResponse().toByteArray()));

            ResponseData rd = basic.getResponseData();
            for (int j = 0; j < rd.getResponseCount(); j++) {
                SingleResponse sr = rd.getResponseAt(j);

                if (sr == null) {
                    throw new Exception("No OCSP Response data.");
                }

                System.out.println("CertID.serialNumber=" + sr.getCertID().getSerialNumber());

                CertStatus status = sr.getCertStatus();
                if (status instanceof GoodInfo) {
                    System.out.println("CertStatus=Good");

                } else if (status instanceof UnknownInfo) {
                    System.out.println("CertStatus=Unknown");

                } else if (status instanceof RevokedInfo) {
                    System.out.println("CertStatus=Revoked");
                }
            }
        }

        if (output != null) {
            if (verbose)
                System.out.println("Storing response into " + output);

            try (FileOutputStream out = new FileOutputStream(output)) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                response.encode(os);
                out.write(os.toByteArray());
            }

            System.out.println("Success: Output " + output);
        }

    } catch (Exception e) {
        if (verbose)
            e.printStackTrace();
        printError(e);
        System.exit(1);
    }
}

From source file:ch.bfh.evoting.verifier.Verifier.java

/**
 * This program is a verifier for MobiVote application with HKRS12 protocol
 * You have to indicate the XML file exported from the application as argument for this program.
 * You can also indicate the files of different participants. In this case, there will be checked if all files contain the same values.
 * @param args the file(s) containing the values of the protocol
 *///w w  w  .j a va2 s. c  o  m
public static void main(String[] args) {

    /*
     * Reading files given as parameters
     */
    if (args.length < 1) {
        //Not enough arguments
        System.out.println(
                "You must indicate the location of the XML file containing the data to verify! You can also indicate the files of different participants.");
        return;
    } else if (args.length > 1) {
        //Make a digest of all files and compare them
        List<byte[]> digests = new ArrayList<byte[]>();
        for (String s : args) {
            try {
                MessageDigest md = MessageDigest.getInstance("SHA-256");

                InputStream is = Files.newInputStream(Paths.get(s));
                DigestInputStream dis = new DigestInputStream(is, md);
                @SuppressWarnings("unused")
                int numBytes = -1;
                while ((numBytes = dis.read()) != -1) {
                    dis.read();
                }

                byte[] digest = md.digest();
                digests.add(digest);

            } catch (IOException e) {
                System.out.println("One of the given files does not exists!");
                return;
            } catch (NoSuchAlgorithmException e1) {
                System.out.println("Unable to compute the digest of the file!");
                return;
            }
        }
        System.out.print("Checking the similarity of the files...");
        for (byte[] b : digests) {
            for (byte[] b2 : digests) {
                if (!Arrays.equals(b, b2)) {
                    System.out.print("\t\t\t\t\t\t\t\t\t\tWRONG\n");
                    System.out.println(
                            "The given files are not all identical! This means the content received by the participants was not the same.");
                    return;
                }
            }
        }
        System.out.print("\t\t\t\t\t\t\t\t\t\tOK\n\n");
    } else if (args.length == 1) {
        //Print a warning
        System.out.println(
                "BE CAREFUL: checking only one file ensure that the cryptographic values of the protocol are correct.\n"
                        + "But, it does NOT ensure that all users have the same result. This could happen when a participant missed some messages.\n"
                        + "This case is only covered by this verifier by giving multiple files as argument.\n");
    }

    Serializer serializer = new Persister();
    File source = new File(args[0]);

    poll = null;
    System.out.print("Reading file...");
    try {
        poll = serializer.read(XMLPoll.class, source);
        System.out.print("\t\t\t\t\t\t\t\t\t\t\t\t\tOK\n");
    } catch (Exception e) {
        System.out.print("\t\t\t\t\t\t\t\t\t\t\t\t\tFAILED\n");
        e.printStackTrace();
        return;
    }

    /*
     * Create the initializations needed by the protocol
     */
    G_q = GStarModSafePrime.getInstance(new BigInteger(poll.getP()));
    Z_q = G_q.getZModOrder();
    Zgroup = Z.getInstance();
    generator = poll.getGenerator().getValue(G_q);

    representations = new Element[poll.getOptions().size()];
    int i = 0;
    for (XMLOption op : poll.getOptions()) {
        representations[i] = op.getRepresentation().getValue(Z_q);
        i++;
    }

    System.out.println();
    System.out.println("Verifying vote: \"" + poll.getQuestion() + "\"");

    /*
     * Verify the dependence between cryptographic values and the vote properties
     */
    //Not used anymore, implicitly done with otherInputs of proofs
    //verifyDependencyTextCrypto();

    /*
     * Verify the proofs for the user
     */
    System.out.println();
    System.out.println("Verifying the proof for the participants...");
    a = new Element[poll.getParticipants().size()];
    b = new Element[poll.getParticipants().size()];
    h = new Element[poll.getParticipants().size()];
    hHat = new Element[poll.getParticipants().size()];
    hHatPowX = new Element[poll.getParticipants().size()];
    proofForX = new Element[poll.getParticipants().size()];
    validityProof = new Element[poll.getParticipants().size()];
    equalityProof = new Element[poll.getParticipants().size()];
    Tuple pollTuple = preparePollOtherInput(poll, representations, generator);

    int k = 0;
    for (XMLParticipant p : poll.getParticipants()) {
        System.out.println("\tParticipant " + p.getIdentification() + " (" + p.getUniqueId() + ")");

        if (p.getAi() != null) {
            a[k] = p.getAi().getValue(G_q);
            if (DEBUG)
                System.out.println("Value a: " + a[k]);
        }
        if (p.getHi() != null) {
            h[k] = p.getHi().getValue(G_q);
            if (DEBUG)
                System.out.println("Value h: " + h[k]);
        }
        if (p.getBi() != null) {
            b[k] = p.getBi().getValue(G_q);
            if (DEBUG)
                System.out.println("Value b: " + b[k]);
        }
        if (p.getHiHat() != null) {
            hHat[k] = p.getHiHat().getValue(G_q);
            if (DEBUG)
                System.out.println("Value h hat: " + hHat[k]);
        }
        if (p.getHiHatPowXi() != null) {
            hHatPowX[k] = p.getHiHatPowXi().getValue(G_q);
            if (DEBUG)
                System.out.println("Value h hat ^ x: " + hHatPowX[k]);
        }

        if (p.getProofForXi() != null) {
            ProductGroup group = ProductGroup.getInstance(G_q, Zgroup, Z_q);

            proofForX[k] = p.getProofForXi().getValue(group);
        }

        if (p.getProofValidVote() != null) {

            Group[] tripleElement1Groups = new Group[poll.getOptions().size()];
            Group[] tripleElement2Groups = new Group[poll.getOptions().size()];
            Group[] tripleElement3Groups = new Group[poll.getOptions().size()];
            for (i = 0; i < poll.getOptions().size(); i++) {
                tripleElement1Groups[i] = ProductGroup.getInstance(G_q, G_q);
                tripleElement2Groups[i] = Zgroup;
                tripleElement3Groups[i] = Z_q;
            }
            ProductGroup tripleElement1 = ProductGroup.getInstance(tripleElement1Groups);
            ProductGroup tripleElement2 = ProductGroup.getInstance(tripleElement2Groups);
            ProductGroup tripleElement3 = ProductGroup.getInstance(tripleElement3Groups);
            ProductGroup group = ProductGroup.getInstance(tripleElement1, tripleElement2, tripleElement3);

            validityProof[k] = p.getProofValidVote().getValue(group);

            if (DEBUG)
                System.out.println("Proof of validity: " + validityProof[k]);
        }

        if (p.getProofForHiHat() != null) {
            recoveryNeeded = true;
            ProductGroup group = ProductGroup.getInstance(ProductGroup.getInstance(G_q, G_q), Zgroup, Z_q);

            equalityProof[k] = p.getProofForHiHat().getValue(group);
        }

        Tuple participantTuple = prepareParticipantOtherInput(p);
        otherInput = Tuple.getInstance(participantTuple, pollTuple);

        /*
         * Verify proof of knowledge 
         */
        System.out.print("\t\tVerifying proof of knowledge of x value...");
        verifyProofOfKnowledgeOfX(k);

        /*
         * Verify proof of validity 
         */
        if (validityProof[k] != null) {
            System.out.print("\t\tVerifying proof of valid vote...");
            verifyValidityProof(k);
        }

        /*
         * Verify proof of equality 
         */
        if (equalityProof[k] != null) {
            System.out.print("\t\tVerifying proof of equality between discrete logarithm g^x and h_hat^x...");
            verifyEqualityProof(k);
        }
        k++;
    }

    /**
     * Computing the result
     */
    System.out.println();
    System.out.print("Computing the result...");
    computeResult();

}

From source file:com.github.chrbayer84.keybits.KeyBits.java

/**
 * @param args//from w ww.  j  a  v a  2 s .  com
 */
public static void main(String[] args) throws Exception {
    int number_of_addresses = 1;
    int depth = 1;

    String usage = "java -jar KeyBits.jar [options]";
    // create parameters which can be chosen
    Option help = new Option("h", "print this message");
    Option verbose = new Option("v", "verbose");
    Option exprt = new Option("e", "export public key to blockchain");
    Option imprt = OptionBuilder.withArgName("string").hasArg()
            .withDescription("import public key from blockchain").create("i");

    Option blockchain_address = OptionBuilder.withArgName("string").hasArg().withDescription("bitcoin address")
            .create("a");
    Option create_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("create wallet")
            .create("c");
    Option update_wallet = OptionBuilder.withArgName("file name").hasArg().withDescription("update wallet")
            .create("u");
    Option balance_wallet = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("return balance of wallet").create("b");
    Option show_wallet = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("show content of wallet").create("w");
    Option send_coins = OptionBuilder.withArgName("file name").hasArg().withDescription("send satoshis")
            .create("s");
    Option monitor_pending = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("monitor pending transactions of wallet").create("p");
    Option monitor_depth = OptionBuilder.withArgName("file name").hasArg()
            .withDescription("monitor transaction depths of wallet").create("d");
    Option number = OptionBuilder.withArgName("integer").hasArg()
            .withDescription("in combination with -c, -d, -r or -s").create("n");
    Option reset = OptionBuilder.withArgName("file name").hasArg().withDescription("reset wallet").create("r");

    Options options = new Options();

    options.addOption(help);
    options.addOption(verbose);
    options.addOption(imprt);
    options.addOption(exprt);

    options.addOption(blockchain_address);
    options.addOption(create_wallet);
    options.addOption(update_wallet);
    options.addOption(balance_wallet);
    options.addOption(show_wallet);
    options.addOption(send_coins);
    options.addOption(monitor_pending);
    options.addOption(monitor_depth);
    options.addOption(number);
    options.addOption(reset);

    BasicParser parser = new BasicParser();
    CommandLine cmd = null;

    String header = "This is KeyBits v0.01b.1412953962" + System.getProperty("line.separator");
    // show help if wrong usage
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        printHelp(usage, options, header);
    }

    if (cmd.getOptions().length == 0)
        printHelp(usage, options, header);

    if (cmd.hasOption("h"))
        printHelp(usage, options, header);

    if (cmd.hasOption("v"))
        System.out.println(header);

    if (cmd.hasOption("c") && cmd.hasOption("n"))
        number_of_addresses = new Integer(cmd.getOptionValue("n")).intValue();

    if (cmd.hasOption("d") && cmd.hasOption("n"))
        depth = new Integer(cmd.getOptionValue("n")).intValue();

    String checkpoints_file_name = "checkpoints";
    if (!new File(checkpoints_file_name).exists())
        checkpoints_file_name = null;

    // ---------------------------------------------------------------------

    if (cmd.hasOption("c")) {
        String wallet_file_name = cmd.getOptionValue("c");

        String passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name);
        if (!new File(wallet_file_name).exists()) {
            String passphrase_ = HelpfulStuff.reInsertPassphrase("enter password for " + wallet_file_name);

            if (!passphrase.equals(passphrase_)) {
                System.out.println("passwords do not match");
                System.exit(0);
            }
        }

        MyWallet.createWallet(wallet_file_name, wallet_file_name + ".chain", number_of_addresses, passphrase);
        System.exit(0);
    }

    if (cmd.hasOption("u")) {
        String wallet_file_name = cmd.getOptionValue("u");
        MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name);
        System.exit(0);
    }

    if (cmd.hasOption("b")) {
        String wallet_file_name = cmd.getOptionValue("b");
        System.out.println(
                MyWallet.getBalanceOfWallet(wallet_file_name, wallet_file_name + ".chain").longValue());
        System.exit(0);
    }

    if (cmd.hasOption("w")) {
        String wallet_file_name = cmd.getOptionValue("w");
        System.out.println(MyWallet.showContentOfWallet(wallet_file_name, wallet_file_name + ".chain"));
        System.exit(0);
    }

    if (cmd.hasOption("p")) {
        System.out.println("monitoring of pending transactions ... ");
        String wallet_file_name = cmd.getOptionValue("p");
        MyWallet.monitorPendingTransactions(wallet_file_name, wallet_file_name + ".chain",
                checkpoints_file_name);
        System.exit(0);
    }

    if (cmd.hasOption("d")) {
        System.out.println("monitoring of transaction depth ... ");
        String wallet_file_name = cmd.getOptionValue("d");
        MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name,
                depth);
        System.exit(0);
    }

    if (cmd.hasOption("r") && cmd.hasOption("n")) {
        long epoch = new Long(cmd.getOptionValue("n"));
        System.out.println("resetting wallet ... ");
        String wallet_file_name = cmd.getOptionValue("r");

        File chain_file = (new File(wallet_file_name + ".chain"));
        if (chain_file.exists())
            chain_file.delete();

        MyWallet.setCreationTime(wallet_file_name, epoch);
        MyWallet.updateWallet(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name);

        System.exit(0);
    }

    if (cmd.hasOption("s") && cmd.hasOption("a") && cmd.hasOption("n")) {
        String wallet_file_name = cmd.getOptionValue("s");
        String address = cmd.getOptionValue("a");
        Integer amount = new Integer(cmd.getOptionValue("n"));

        String wallet_passphrase = HelpfulStuff.insertPassphrase("enter password for " + wallet_file_name);
        MyWallet.sendCoins(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name, address,
                new BigInteger(amount + ""), wallet_passphrase);

        System.out.println("waiting ...");
        Thread.sleep(10000);
        System.out.println("monitoring of transaction depth ... ");
        MyWallet.monitorTransactionDepth(wallet_file_name, wallet_file_name + ".chain", checkpoints_file_name,
                1);
        System.out.println("transaction fixed in blockchain with depth " + depth);
        System.exit(0);
    }

    // ----------------------------------------------------------------------------------------
    //                                  creates public key
    // ----------------------------------------------------------------------------------------

    GnuPGP gpg = new GnuPGP();

    if (cmd.hasOption("e")) {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        StringBuffer sb = new StringBuffer();
        while ((line = input.readLine()) != null)
            sb.append(line + "\n");

        PGPPublicKeyRing public_key_ring = gpg.getDearmored(sb.toString());
        //System.out.println(gpg.showPublicKeys(public_key_ring));

        byte[] public_key_ring_encoded = gpg.getEncoded(public_key_ring);

        String[] addresses = (new Encoding()).encodePublicKey(public_key_ring_encoded);
        //         System.out.println(gpg.showPublicKey(gpg.getDecoded(encoding.decodePublicKey(addresses))));

        // file names for message
        String public_key_file_name = Long.toHexString(public_key_ring.getPublicKey().getKeyID()) + ".wallet";
        String public_key_wallet_file_name = public_key_file_name;
        String public_key_chain_file_name = public_key_wallet_file_name + ".chain";

        // hier muss dass passwort noch nach encodeAddresses weitergeleitet werden da sonst zweimal abfrage
        String public_key_wallet_passphrase = HelpfulStuff
                .insertPassphrase("enter password for " + public_key_wallet_file_name);
        if (!new File(public_key_wallet_file_name).exists()) {
            String public_key_wallet_passphrase_ = HelpfulStuff
                    .reInsertPassphrase("enter password for " + public_key_wallet_file_name);

            if (!public_key_wallet_passphrase.equals(public_key_wallet_passphrase_)) {
                System.out.println("passwords do not match");
                System.exit(0);
            }
        }

        MyWallet.createWallet(public_key_wallet_file_name, public_key_chain_file_name, 1,
                public_key_wallet_passphrase);
        MyWallet.updateWallet(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name);
        String public_key_address = MyWallet.getAddress(public_key_wallet_file_name, public_key_chain_file_name,
                0);
        System.out.println("address of public key: " + public_key_address);

        // 10000 additional satoshis for sending transaction to address of recipient of message and 10000 for fees
        KeyBits.encodeAddresses(public_key_wallet_file_name, public_key_chain_file_name, checkpoints_file_name,
                addresses, 2 * SendRequest.DEFAULT_FEE_PER_KB.intValue(), depth, public_key_wallet_passphrase);
    }

    if (cmd.hasOption("i")) {
        String location = cmd.getOptionValue("i");

        String[] addresses = null;
        if (location.indexOf(",") > -1) {
            String[] locations = location.split(",");
            addresses = MyWallet.getAddressesFromBlockAndTransaction("main.wallet", "main.wallet.chain",
                    checkpoints_file_name, locations[0], locations[1]);
        } else {
            addresses = BlockchainDotInfo.getKeys(location);
        }

        byte[] encoded = (new Encoding()).decodePublicKey(addresses);
        PGPPublicKeyRing public_key_ring = gpg.getDecoded(encoded);

        System.out.println(gpg.getArmored(public_key_ring));

        System.exit(0);
    }
}

From source file:com.amazonaws.services.kinesis.clientlibrary.proxies.util.KinesisLocalFileDataCreator.java

/** Creates a new temp file populated with fake Kinesis data records.
 * @param args Expects 5 args: numShards, shardPrefix, numRecordsPerShard, startingSequenceNumber, fileNamePrefix
 *///from   w  w  w  . ja va  2s .  c o m
// CHECKSTYLE:OFF MagicNumber
// CHECKSTYLE:IGNORE UncommentedMain FOR NEXT 2 LINES
public static void main(String[] args) {
    int numShards = 1;
    String shardIdPrefix = "shardId";
    int numRecordsPerShard = 17;
    BigInteger startingSequenceNumber = new BigInteger("99");
    String fileNamePrefix = "kinesisFakeRecords";

    try {
        if ((args.length != 0) && (args.length != 5)) {
            // Temporary util code, so not providing detailed usage feedback.
            System.out.println("Unexpected number of arguments.");
            System.exit(0);
        }

        if (args.length == 5) {
            numShards = Integer.parseInt(args[0]);
            shardIdPrefix = args[1];
            numRecordsPerShard = Integer.parseInt(args[2]);
            startingSequenceNumber = new BigInteger(args[3]);
            fileNamePrefix = args[4];
        }

        File file = KinesisLocalFileDataCreator.generateTempDataFile(numShards, shardIdPrefix,
                numRecordsPerShard, startingSequenceNumber, fileNamePrefix);
        System.out.println("Created fake kinesis records in file: " + file.getAbsolutePath());
    } catch (Exception e) {
        // CHECKSTYLE:IGNORE IllegalCatch FOR NEXT -1 LINES
        System.out.println("Caught Exception: " + e);
    }

}

From source file:Main.java

public static void main() {
    BigInteger bi1 = new BigInteger("123");
    BigInteger bi2 = new BigInteger("-123");

    // assign difference of bi1 and bi2 to bi3
    BigInteger bi3 = bi1.subtract(bi2);

    System.out.println(bi3);//from   w  w  w. j  a v a  2s.  c o  m
}

From source file:Main.java

public static int bytesToInt(byte[] bytes) {
    return new BigInteger(bytes).intValue();
}

From source file:Main.java

public static long bytesToLong(byte[] bytes) {
    return new BigInteger(bytes).longValue();
}

From source file:Main.java

public static int bytes2int(byte[] bytes) {
    final int i = new BigInteger(bytes).intValue();
    // System.out.println("byte2int"+i);

    return i;/* ww  w .  j av  a  2  s .  c  o m*/
}

From source file:Main.java

public static BigInteger sumRights(int[] rights) {
    BigInteger num = new BigInteger("0");
    for (int i = 0; i < rights.length; i++) {
        num = num.setBit(rights[i]);/*from  w  ww  . j a  va  2s.c om*/
    }
    return num;
}

From source file:Main.java

public static int byteArrayToInt(byte[] bytes) {
    return new BigInteger(bytes).intValue();
}