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

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

Introduction

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

Prototype

public RIPEMD160Digest() 

Source Link

Document

Standard constructor

Usage

From source file:AmazonDynamoDBSample.java

License:Open Source License

private static void oneTimeAddCitations() {

    String jsonString = "";

    try {/* w w  w . j av a2s. c o  m*/
        jsonString = readFile("./json/citations.json", StandardCharsets.UTF_8);
    } catch (IOException e) {
        System.out.println(e);
    }

    try {
        JSONObject rootObject = new JSONObject(jsonString); // Parse the JSON to a JSONObject
        JSONArray rows = rootObject.getJSONArray("stuff"); // Get all JSONArray rows

        System.out.println("row lengths: " + rows.length());

        set1 = new HashSet<>();

        for (int j = 0; j < rows.length(); j++) { // Iterate each element in the elements array
            JSONObject element = rows.getJSONObject(j); // Get the element object

            int id = element.getInt("id");
            int citationNumber = element.getInt("citation_number");
            String citationDate = " ";
            Boolean isCitationDateNull = element.isNull("citation_date");
            if (!isCitationDateNull)
                citationDate = element.getString("citation_date");
            String firstName = element.getString("first_name");
            String lastName = element.getString("last_name");
            String firstLastName = firstName + lastName;
            firstLastName = firstLastName.toLowerCase();
            set1.add(firstLastName);

            //System.out.println(firstLastName);
            String dob = " ";
            Boolean isDobNull = element.isNull("date_of_birth");
            if (!isDobNull) {
                dob = element.getString("date_of_birth");
                dob = (dob.split(" "))[0];
            }

            // pick a ssn from list
            String ssn = ssnList.get(ssnCounter);
            ssnCounter--;
            ssnHashMap.put(firstLastName, ssn);

            System.out.println(firstLastName + " " + ssn);

            // compute salt
            final Random ran = new SecureRandom();
            byte[] salt = new byte[32];
            ran.nextBytes(salt);
            String saltString = Base64.encodeBase64String(salt);

            //System.out.println("saltstring: " + saltString);
            saltHashMap.put(firstLastName, saltString);

            // compute ripemd160 hash of ssn + salt
            String saltPlusSsn = saltString + ssn;
            //System.out.println("salt plus ssn: " + saltPlusSsn);

            String resultingHash = "";
            try {
                byte[] r = saltPlusSsn.getBytes("US-ASCII");
                RIPEMD160Digest d = new RIPEMD160Digest();
                d.update(r, 0, r.length);
                byte[] o = new byte[d.getDigestSize()];
                d.doFinal(o, 0);
                ByteArrayOutputStream baos = new ByteArrayOutputStream(40);
                Hex.encode(o, baos);
                resultingHash = new String(baos.toByteArray(), StandardCharsets.UTF_8);

                hashedssnHashMap.put(firstLastName, resultingHash);
            } catch (UnsupportedEncodingException e) {
                System.out.println(e);
            } catch (IOException i) {
                System.out.println(i);
            }

            String fldob = firstLastName + dob;
            String da = " ";
            Boolean isDaNull = element.isNull("defendant_address");
            if (!isDaNull)
                da = element.getString("defendant_address");
            String dc = " ";
            Boolean isDcNull = element.isNull("defendant_city");
            if (!isDcNull)
                dc = element.getString("defendant_city");
            String ds = " ";
            Boolean isDsNull = element.isNull("defendant_state");
            if (!isDsNull)
                ds = element.getString("defendant_state");
            String dln = " ";
            Boolean isDlnNull = element.isNull("drivers_license_number");
            if (!isDlnNull)
                dln = element.getString("drivers_license_number");
            String cd = " ";
            Boolean isCdNull = element.isNull("court_date");
            if (!isCdNull)
                cd = element.getString("court_date");
            String cl = " ";
            Boolean isClNull = element.isNull("court_location");
            if (!isClNull)
                cl = element.getString("court_location");
            String ca = " ";
            Boolean isCaNull = element.isNull("court_address");
            if (!isCaNull)
                ca = element.getString("court_address");
            /*
            Map<String, AttributeValue> item = newCitationItem(citationNumber, citationDate, firstName, lastName, firstLastName, dob, fldob, resultingHash, da, dc, ds, dln, cd, cl, ca);
            PutItemRequest putItemRequest = new PutItemRequest("citations-table", item);
            PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
            */
        }
    } catch (JSONException e) {
        // JSON Parsing error
        e.printStackTrace();
    }
}

From source file:AmazonDynamoDBSample.java

License:Open Source License

private static void oneTimeAddWarrants() {

    String jsonString = "";

    try {/*from ww w . java 2  s  .c  om*/
        jsonString = readFile("./json/warrants.json", StandardCharsets.UTF_8);
    } catch (IOException e) {
        System.out.println(e);
    }

    try {
        JSONObject rootObject = new JSONObject(jsonString); // Parse the JSON to a JSONObject
        JSONArray rows = rootObject.getJSONArray("stuff"); // Get all JSONArray rows

        //System.out.println("row lengths: " + rows.length());

        set2 = new HashSet<>();

        for (int j = 0; j < rows.length(); j++) { // Iterate each element in the elements array
            JSONObject element = rows.getJSONObject(j); // Get the element object

            String defendant = element.getString("Defendant");

            String strarr[] = defendant.split(" ");
            String temp = strarr[1];
            int len = strarr[0].length();
            strarr[0] = strarr[0].substring(0, len - 1);
            strarr[1] = strarr[0];
            strarr[0] = temp;

            String firstLast = strarr[0] + strarr[1];
            firstLast = firstLast.toLowerCase();

            set2.add(firstLast);
            //System.out.println(firstLast);

            int zipCode = 0;
            Boolean isZipCodeNull = element.isNull("ZIP Code");
            if (!isZipCodeNull)
                zipCode = element.getInt("ZIP Code");
            String dob = element.getString("Date of Birth");
            String caseNumber = element.getString("Case Number");

            String firstLastDOB = firstLast + dob;

            // pick a ssn from list
            String ssn = ssnList.get(ssnCounter);
            ssnCounter--;
            ssnHashMap.put(firstLast, ssn);

            // compute salt
            final Random ran = new SecureRandom();
            byte[] salt = new byte[32];
            ran.nextBytes(salt);
            String saltString = Base64.encodeBase64String(salt);

            //System.out.println("saltstring: " + saltString);
            saltHashMap.put(firstLast, saltString);

            // compute ripemd160 hash of ssn + salt
            String saltPlusSsn = saltString + ssn;
            //System.out.println("salt plus ssn: " + saltPlusSsn);

            String resultingHash = "";
            try {
                byte[] r = saltPlusSsn.getBytes("US-ASCII");
                RIPEMD160Digest d = new RIPEMD160Digest();
                d.update(r, 0, r.length);
                byte[] o = new byte[d.getDigestSize()];
                d.doFinal(o, 0);
                ByteArrayOutputStream baos = new ByteArrayOutputStream(40);
                Hex.encode(o, baos);
                resultingHash = new String(baos.toByteArray(), StandardCharsets.UTF_8);

                hashedssnHashMap.put(firstLast, resultingHash);
            } catch (UnsupportedEncodingException e) {
                System.out.println(e);
            } catch (IOException i) {
                System.out.println(i);
            }

            //compareNames();

            Map<String, AttributeValue> item = newWarrantItem(firstLast, firstLastDOB, resultingHash, defendant,
                    zipCode, dob, caseNumber);
            PutItemRequest putItemRequest = new PutItemRequest("warrants-table", item);
            PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);

        }
    } catch (JSONException e) {
        // JSON Parsing error
        e.printStackTrace();
    }
}

From source file:TxOutput.java

License:Open Source License

public String getAddress() {
    // P2PKH Address
    if (script[0] == 0x76) {
        byte[] hash160 = Arrays.copyOfRange(script, 3, 23);
        return Utils.base58Encode((byte) 0x00, hash160);
    }/*from  w  w w .  j  a v a2  s.  c  om*/
    // P2SH Address
    else if (Utils.getUnsignedByte(script[0]) == 0xa9) {
        byte[] hash160 = Arrays.copyOfRange(script, 2, 22);
        return Utils.base58Encode((byte) 0x05, hash160);
    }
    // P2PK Address Uncompressed
    else if (Utils.getUnsignedByte(script[0]) == 0x41 && Utils.getUnsignedByte(script[1]) == 0x04
            && Utils.getUnsignedByte(script[script.length - 1]) == 0xac) {
        byte[] pk = Arrays.copyOfRange(script, 1, 66);
        SHA256Digest sha256 = new SHA256Digest();
        sha256.update(pk, 0, pk.length);
        byte[] sha256out = new byte[32];
        sha256.doFinal(sha256out, 0);
        RIPEMD160Digest ripemd160 = new RIPEMD160Digest();
        ripemd160.update(sha256out, 0, sha256out.length);
        byte[] ripemd160out = new byte[20];
        ripemd160.doFinal(ripemd160out, 0);
        return Utils.base58Encode((byte) 0x00, ripemd160out);
    }
    // P2PK Address Compressed
    else if ((Utils.getUnsignedByte(script[1]) == 0x03 || Utils.getUnsignedByte(script[1]) == 0x02)
            && Utils.getUnsignedByte(script[0]) == 21
            && Utils.getUnsignedByte(script[script.length - 1]) == 0xac) {
        byte[] pk = Arrays.copyOfRange(script, 1, 34);
        SHA256Digest sha256 = new SHA256Digest();
        sha256.update(pk, 0, pk.length);
        byte[] sha256out = new byte[32];
        sha256.doFinal(sha256out, 0);
        RIPEMD160Digest ripemd160 = new RIPEMD160Digest();
        ripemd160.update(sha256out, 0, sha256out.length);
        byte[] ripemd160out = new byte[20];
        ripemd160.doFinal(ripemd160out, 0);
        return Utils.base58Encode((byte) 0x00, ripemd160out);
    }
    // Nonstandard
    else {
        return "Non Standard Output";
    }
}

From source file:bruteForcer.Utils.java

License:Apache License

/**
 * Calculates RIPEMD160(SHA256(input)). This is used in Address calculations.
 *///from www  . j  av a 2  s .  co  m
public static byte[] sha256hash160(byte[] input) {
    try {
        byte[] sha256 = MessageDigest.getInstance("SHA-256").digest(input);
        RIPEMD160Digest digest = new RIPEMD160Digest();
        digest.update(sha256, 0, sha256.length);
        byte[] out = new byte[20];
        digest.doFinal(out, 0);
        return out;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e); // Cannot happen.
    }
}

From source file:com.bitsofproof.supernode.api.Hash.java

License:Apache License

public static byte[] keyHash(byte[] key) {
    byte[] ph = new byte[20];
    try {/*w  ww.j a v a2 s .  co m*/
        byte[] sha256 = MessageDigest.getInstance("SHA-256").digest(key);
        RIPEMD160Digest digest = new RIPEMD160Digest();
        digest.update(sha256, 0, sha256.length);
        digest.doFinal(ph, 0);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    return ph;
}

From source file:com.bitsofproof.supernode.core.ScriptEvaluation.java

License:Apache License

@SuppressWarnings("incomplete-switch")
public boolean evaluateSingleScript(byte[] script) throws ValidationException {
    if (script.length > 10000) {
        return false;
    }//from  w w w  .j ava2  s .  c  o  m

    alt = new Stack<byte[]>();

    ScriptFormat.Tokenizer tokenizer = new ScriptFormat.Tokenizer(script);
    int codeseparator = 0;

    Stack<Boolean> ignoreStack = new Stack<Boolean>();
    ignoreStack.push(false);

    int ifdepth = 0;
    int opcodeCount = 0;
    while (tokenizer.hashMoreElements()) {
        ScriptFormat.Token token = null;
        try {
            token = tokenizer.nextToken();
            if (token.op.ordinal() > Opcode.OP_16.ordinal() && ++opcodeCount > 201) {
                return false;
            }
        } catch (ValidationException e) {
            if (ignoreStack.peek()) {
                continue;
            }
            throw e;
        }
        if (token.data != null) {
            if (!ignoreStack.peek()) {
                push(token.data);
            } else {
                if (token.data.length > 520) {
                    return false;
                }
            }
            continue;
        }
        switch (token.op) {
        case OP_CAT:
        case OP_SUBSTR:
        case OP_LEFT:
        case OP_RIGHT:
            return false;
        case OP_INVERT:
        case OP_AND:
        case OP_OR:
        case OP_XOR:
            return false;
        case OP_VERIF:
        case OP_VERNOTIF:
            return false;
        case OP_MUL:
        case OP_DIV:
        case OP_MOD:
        case OP_LSHIFT:
        case OP_RSHIFT:
            return false;
        case OP_2MUL:
        case OP_2DIV:
            return false;

        case OP_IF:
            ++ifdepth;
            if (!ignoreStack.peek() && popBoolean()) {
                ignoreStack.push(false);
            } else {
                ignoreStack.push(true);
            }
            break;
        case OP_NOTIF:
            ++ifdepth;
            if (!ignoreStack.peek() && !popBoolean()) {
                ignoreStack.push(false);
            } else {
                ignoreStack.push(true);
            }
            break;
        case OP_ENDIF:
            --ifdepth;
            ignoreStack.pop();
            break;
        case OP_ELSE:
            ignoreStack.push(!ignoreStack.pop() || ignoreStack.peek());
            break;
        }
        if (!ignoreStack.peek()) {
            switch (token.op) {
            case OP_VERIFY:
                if (!isTrue(stack.peek())) {
                    return false;
                } else {
                    stack.pop();
                }
                break;
            case OP_RETURN:
                return false;
            case OP_NOP:
                break;
            case OP_1NEGATE:
                pushInt(-1);
                break;
            case OP_FALSE:
                push(new byte[0]);
                break;
            case OP_1:
                pushInt(1);
                break;
            case OP_2:
                pushInt(2);
                break;
            case OP_3:
                pushInt(3);
                break;
            case OP_4:
                pushInt(4);
                break;
            case OP_5:
                pushInt(5);
                break;
            case OP_6:
                pushInt(6);
                break;
            case OP_7:
                pushInt(7);
                break;
            case OP_8:
                pushInt(8);
                break;
            case OP_9:
                pushInt(9);
                break;
            case OP_10:
                pushInt(10);
                break;
            case OP_11:
                pushInt(11);
                break;
            case OP_12:
                pushInt(12);
                break;
            case OP_13:
                pushInt(13);
                break;
            case OP_14:
                pushInt(14);
                break;
            case OP_15:
                pushInt(15);
                break;
            case OP_16:
                pushInt(16);
                break;
            case OP_TOALTSTACK:
                alt.push(stack.pop());
                break;
            case OP_FROMALTSTACK:
                push(alt.pop());
                break;
            case OP_2DROP:
                stack.pop();
                stack.pop();
                break;
            case OP_2DUP: {
                byte[] a1 = stack.pop();
                byte[] a2 = stack.pop();
                push(a2);
                push(a1);
                push(a2);
                push(a1);
            }
                break;
            case OP_3DUP: {
                byte[] a1 = stack.pop();
                byte[] a2 = stack.pop();
                byte[] a3 = stack.pop();
                push(a3);
                push(a2);
                push(a1);
                push(a3);
                push(a2);
                push(a1);
            }
                break;
            case OP_2OVER: {
                byte[] a1 = stack.pop();
                byte[] a2 = stack.pop();
                byte[] a3 = stack.pop();
                byte[] a4 = stack.pop();
                push(a4);
                push(a3);
                push(a2);
                push(a1);
                push(a4);
                push(a3);
            }
                break;
            case OP_2ROT: {
                byte[] a1 = stack.pop();
                byte[] a2 = stack.pop();
                byte[] a3 = stack.pop();
                byte[] a4 = stack.pop();
                byte[] a5 = stack.pop();
                byte[] a6 = stack.pop();
                push(a4);
                push(a3);
                push(a2);
                push(a1);
                push(a6);
                push(a5);
            }
                break;
            case OP_2SWAP: {
                byte[] a1 = stack.pop();
                byte[] a2 = stack.pop();
                byte[] a3 = stack.pop();
                byte[] a4 = stack.pop();
                push(a2);
                push(a1);
                push(a4);
                push(a3);
            }
                break;
            case OP_IFDUP:
                if (peekBoolean()) {
                    push(stack.peek());
                }
                break;
            case OP_DEPTH:
                pushInt(stack.size());
                break;
            case OP_DROP:
                stack.pop();
                break;
            case OP_DUP: {
                push(stack.peek());
            }
                break;
            case OP_NIP: {
                byte[] a1 = stack.pop();
                stack.pop();
                push(a1);
            }
                break;
            case OP_OVER: {
                byte[] a1 = stack.pop();
                byte[] a2 = stack.pop();
                push(a2);
                push(a1);
                push(a2);
            }
                break;
            case OP_PICK: {
                long n = popInt();
                push(stack.get(stack.size() - 1 - (int) n));
            }
                break;
            case OP_ROLL: {
                long n = popInt();
                byte[] a = stack.get(stack.size() - 1 - (int) n);
                stack.remove((int) (stack.size() - 1 - n));
                push(a);
            }
                break;
            case OP_ROT: {
                byte[] a = stack.get(stack.size() - 1 - 2);
                stack.remove(stack.size() - 1 - 2);
                push(a);
            }
                break;
            case OP_SWAP: {
                byte[] a = stack.pop();
                byte[] b = stack.pop();
                push(a);
                push(b);
            }
                break;
            case OP_TUCK: {
                byte[] a = stack.pop();
                byte[] b = stack.pop();
                push(a);
                push(b);
                push(a);
            }
                break;
            case OP_SIZE:
                pushInt(stack.peek().length);
                break;
            case OP_EQUAL:
            case OP_EQUALVERIFY: {
                pushInt(equals(stack.pop(), stack.pop()) == true ? 1 : 0);
                if (token.op == ScriptFormat.Opcode.OP_EQUALVERIFY) {
                    if (!isTrue(stack.peek())) {
                        return false;
                    } else {
                        stack.pop();
                    }
                }
            }
                break;
            case OP_VER:
            case OP_RESERVED:
            case OP_RESERVED1:
            case OP_RESERVED2:
                return false;
            case OP_1ADD:// 0x8b in out 1 is added to the input.
                pushInt(popOperand() + 1);
                break;
            case OP_1SUB:// 0x8c in out 1 is subtracted from the
                         // input.
                pushInt(popOperand() - 1);
                break;
            case OP_NEGATE:// 0x8f in out The sign of the input is
                           // flipped.
                pushInt(-popOperand());
                break;
            case OP_ABS:// 0x90 in out The input is made positive.
                pushInt(Math.abs(popOperand()));
                break;
            case OP_NOT: // 0x91 in out If the input is 0 or 1, it
                         // is
                         // flipped. Otherwise the output will be
                         // 0.
                pushInt(popOperand() == 0 ? 1 : 0);
                break;
            case OP_0NOTEQUAL:// 0x92 in out Returns 0 if the input
                              // is
                              // 0. 1 otherwise.
                pushInt(popOperand() == 0 ? 0 : 1);
                break;
            case OP_ADD:// 0x93 a b out a is added to b.
                pushInt(popOperand() + popOperand());
                break;
            case OP_SUB:// 0x94 a b out b is subtracted from a.
            {
                long a = popOperand();
                long b = popOperand();
                pushInt(b - a);
            }
                break;
            case OP_BOOLAND:// 0x9a a b out If both a and b are not
                // 0,
                // the output is 1. Otherwise 0.
                pushInt(popOperand() != 0 && popOperand() != 0 ? 1 : 0);
                break;
            case OP_BOOLOR:// 0x9b a b out If a or b is not 0, the
                           // output is 1. Otherwise 0.
            {
                long a = popOperand();
                long b = popOperand();
                pushInt(a != 0 || b != 0 ? 1 : 0);
            }
                break;
            case OP_NUMEQUAL:// 0x9c a b out Returns 1 if the
                             // numbers
                             // are equal, 0 otherwise.
                pushInt(popOperand() == popOperand() ? 1 : 0);
                break;
            case OP_NUMEQUALVERIFY:// 0x9d a b out Same as
                // OP_NUMEQUAL,
                // but runs OP_VERIFY afterward.
                if (popOperand() != popOperand()) {
                    return false;
                }
                break;
            case OP_NUMNOTEQUAL:// 0x9e a b out Returns 1 if the
                // numbers
                // are not equal, 0 otherwise.
                pushInt(popOperand() != popOperand() ? 1 : 0);
                break;

            case OP_LESSTHAN:// 0x9f a b out Returns 1 if a is less
                             // than
                             // b, 0 otherwise.
            {
                long a = popOperand();
                long b = popOperand();
                pushInt(b < a ? 1 : 0);
            }
                break;
            case OP_GREATERTHAN:// 0xa0 a b out Returns 1 if a is
            // greater than b, 0 otherwise.
            {
                long a = popOperand();
                long b = popOperand();
                pushInt(b > a ? 1 : 0);
            }
                break;
            case OP_LESSTHANOREQUAL:// 0xa1 a b out Returns 1 if a
            // is
            // less than or equal to b, 0
            // otherwise.
            {
                long a = popOperand();
                long b = popOperand();
                pushInt(b <= a ? 1 : 0);
            }
                break;
            case OP_GREATERTHANOREQUAL:// 0xa2 a b out Returns 1 if
            // a is
            // greater than or equal to
            // b, 0
            // otherwise.
            {
                long a = popOperand();
                long b = popOperand();
                pushInt(b >= a ? 1 : 0);
            }
                break;
            case OP_MIN:// 0xa3 a b out Returns the smaller of a and
                        // b.
                pushInt(Math.min(popOperand(), popOperand()));
                break;
            case OP_MAX:// 0xa4 a b out Returns the larger of a and
                        // b.
                pushInt(Math.max(popOperand(), popOperand()));
                break;
            case OP_WITHIN: // 0xa5 x min max out Returns 1 if x is
            // within the specified range
            // (left-inclusive), 0 otherwise.
            {
                long a = popOperand();
                long b = popOperand();
                long c = popOperand();
                pushInt(c >= b && c < a ? 1 : 0);
            }
                break;
            case OP_RIPEMD160: // 0xa6 in hash The input is hashed
            // using
            // RIPEMD-160.
            {
                RIPEMD160Digest digest = new RIPEMD160Digest();
                byte[] data = stack.pop();
                digest.update(data, 0, data.length);
                byte[] hash = new byte[20];
                digest.doFinal(hash, 0);
                push(hash);
            }
                break;
            case OP_SHA1: // 0xa7 in hash The input is hashed using
                          // SHA-1.
            {
                try {
                    MessageDigest a = MessageDigest.getInstance("SHA-1");
                    push(a.digest(stack.pop()));
                } catch (NoSuchAlgorithmException e) {
                    return false;
                }
            }
                break;
            case OP_SHA256: // 0xa8 in hash The input is hashed
            // using
            // SHA-256.
            {
                push(Hash.sha256(stack.pop()));
            }
                break;
            case OP_HASH160: // 0xa9 in hash The input is hashed
                             // twice:
                             // first with SHA-256 and then with
                             // RIPEMD-160.
            {
                push(Hash.keyHash(stack.pop()));
            }
                break;
            case OP_HASH256: // 0xaa in hash The input is hashed two
                             // times with SHA-256.
            {
                push(Hash.hash(stack.pop()));
            }
                break;
            case OP_CODESEPARATOR: // 0xab Nothing Nothing All of
                // the
                // signature checking words will
                // only match signatures to the
                // data
                // after the most
                // recently-executed
                // OP_CODESEPARATOR.
                codeseparator = tokenizer.getCursor();
                break;
            case OP_CHECKSIGVERIFY: // 0xad sig pubkey True / false
                // Same
                // as OP_CHECKSIG, but OP_VERIFY
                // is
                // executed afterward.
                // / no break;
            case OP_CHECKSIG: // 0xac sig pubkey True / false The
                              // entire
                              // transaction's outputs, inputs,
                              // and
                              // script (from the most
                              // recently-executed
                              // OP_CODESEPARATOR to
                              // the end) are hashed. The
                              // signature
                              // used by OP_CHECKSIG must be a
                              // valid
                              // signature for this hash and
                              // public
                              // key. If it is, 1 is returned, 0
                              // otherwise.
            {
                byte[] pubkey = stack.pop();
                byte[] sig = stack.pop();

                byte[] sts = scriptToSign(script, codeseparator);
                sts = ScriptFormat.deleteSignatureFromScript(sts, sig);

                pushInt(validateSignature(pubkey, sig, sts) ? 1 : 0);
                if (token.op == ScriptFormat.Opcode.OP_CHECKSIGVERIFY) {
                    if (!isTrue(stack.peek())) {
                        return false;
                    } else {
                        stack.pop();
                    }
                }
            }
                break;
            case OP_CHECKMULTISIG: // 0xae x sig1 sig2 ... <number
                // of
                // signatures> pub1 pub2 <number
                // of
                // public keys> True / False For
                // each signature and public key
                // pair, OP_CHECKSIG is
                // executed. If
                // more public keys than
                // signatures
                // are listed, some key/sig
                // pairs
                // can fail. All signatures need
                // to
                // match a public key. If all
                // signatures are valid, 1 is
                // returned, 0 otherwise. Due to
                // a
                // bug, one extra unused value
                // is
                // removed from the stack.
                // / no break;
            case OP_CHECKMULTISIGVERIFY:// 0xaf x sig1 sig2 ...
            // <number
            // of signatures> pub1 pub2
            // ...
            // <number of public keys>
            // True
            // / False Same as
            // OP_CHECKMULTISIG, but
            // OP_VERIFY is executed
            // afterward.
            {
                int nkeys = (int) popInt();
                if (nkeys <= 0 || nkeys > 20) {
                    return false;
                }
                byte[][] keys = new byte[nkeys][];
                for (int i = 0; i < nkeys; ++i) {
                    keys[i] = stack.pop();
                }
                int required = (int) popInt();
                if (required <= 0) {
                    return false;
                }

                byte[] sts = scriptToSign(script, codeseparator);

                int havesig = 0;
                byte[][] sigs = new byte[nkeys][];
                for (int i = 0; i < nkeys && stack.size() > 1; ++i) {
                    sigs[i] = stack.pop();
                    ++havesig;
                    sts = ScriptFormat.deleteSignatureFromScript(sts, sigs[i]);
                }
                stack.pop(); // reproduce Satoshi client bug
                int successCounter = 0;
                for (int i = 0; (required - successCounter) <= (nkeys - i) && i < nkeys; ++i) {
                    for (int j = 0; successCounter < required && j < havesig; ++j) {
                        try {
                            if (validateSignature(keys[i], sigs[j], sts)) {
                                ++successCounter;
                            }
                        } catch (Exception e) {
                            // attempt to validate other no matter if there are
                            // format error in this
                        }
                    }
                }
                pushInt(successCounter == required ? 1 : 0);
            }
                break;
            }
        }
    }
    if (ifdepth != 0) {
        return false;
    }
    return true;
}

From source file:com.google.bitcoin.script.Script.java

License:Apache License

private static void executeScript(Transaction txContainingThis, long index, Script script,
        LinkedList<byte[]> stack) throws ScriptException {
    int opCount = 0;
    int lastCodeSepLocation = 0;

    LinkedList<byte[]> altstack = new LinkedList<byte[]>();
    LinkedList<Boolean> ifStack = new LinkedList<Boolean>();

    for (ScriptChunk chunk : script.chunks) {
        boolean shouldExecute = !ifStack.contains(false);

        if (!chunk.isOpCode()) {
            if (chunk.data.length > MAX_SCRIPT_ELEMENT_SIZE)
                throw new ScriptException("Attempted to push a data string larger than 520 bytes");

            if (!shouldExecute)
                continue;

            stack.add(chunk.data);/*from   w  ww  .j a v a  2  s . co  m*/
        } else {
            int opcode = 0xFF & chunk.data[0];
            if (opcode > OP_16) {
                opCount++;
                if (opCount > 201)
                    throw new ScriptException("More script operations than is allowed");
            }

            if (opcode == OP_VERIF || opcode == OP_VERNOTIF)
                throw new ScriptException("Script included OP_VERIF or OP_VERNOTIF");

            if (opcode == OP_CAT || opcode == OP_SUBSTR || opcode == OP_LEFT || opcode == OP_RIGHT
                    || opcode == OP_INVERT || opcode == OP_AND || opcode == OP_OR || opcode == OP_XOR
                    || opcode == OP_2MUL || opcode == OP_2DIV || opcode == OP_MUL || opcode == OP_DIV
                    || opcode == OP_MOD || opcode == OP_LSHIFT || opcode == OP_RSHIFT)
                throw new ScriptException("Script included a disabled Script Op.");

            switch (opcode) {
            case OP_IF:
                if (!shouldExecute) {
                    ifStack.add(false);
                    continue;
                }
                if (stack.size() < 1)
                    throw new ScriptException("Attempted OP_IF on an empty stack");
                ifStack.add(castToBool(stack.pollLast()));
                continue;
            case OP_NOTIF:
                if (!shouldExecute) {
                    ifStack.add(false);
                    continue;
                }
                if (stack.size() < 1)
                    throw new ScriptException("Attempted OP_NOTIF on an empty stack");
                ifStack.add(!castToBool(stack.pollLast()));
                continue;
            case OP_ELSE:
                if (ifStack.isEmpty())
                    throw new ScriptException("Attempted OP_ELSE without OP_IF/NOTIF");
                ifStack.add(!ifStack.pollLast());
                continue;
            case OP_ENDIF:
                if (ifStack.isEmpty())
                    throw new ScriptException("Attempted OP_ENDIF without OP_IF/NOTIF");
                ifStack.pollLast();
                continue;
            }

            if (!shouldExecute)
                continue;

            switch (opcode) {
            // OP_0 is no opcode
            case OP_1NEGATE:
                stack.add(Utils.reverseBytes(Utils.encodeMPI(BigInteger.ONE.negate(), false)));
                break;
            case OP_1:
            case OP_2:
            case OP_3:
            case OP_4:
            case OP_5:
            case OP_6:
            case OP_7:
            case OP_8:
            case OP_9:
            case OP_10:
            case OP_11:
            case OP_12:
            case OP_13:
            case OP_14:
            case OP_15:
            case OP_16:
                stack.add(
                        Utils.reverseBytes(Utils.encodeMPI(BigInteger.valueOf(decodeFromOpN(opcode)), false)));
                break;
            case OP_NOP:
                break;
            case OP_VERIFY:
                if (stack.size() < 1)
                    throw new ScriptException("Attempted OP_VERIFY on an empty stack");
                if (!castToBool(stack.pollLast()))
                    throw new ScriptException("OP_VERIFY failed");
                break;
            case OP_RETURN:
                throw new ScriptException("Script called OP_RETURN");
            case OP_TOALTSTACK:
                if (stack.size() < 1)
                    throw new ScriptException("Attempted OP_TOALTSTACK on an empty stack");
                altstack.add(stack.pollLast());
                break;
            case OP_FROMALTSTACK:
                if (altstack.size() < 1)
                    throw new ScriptException("Attempted OP_TOALTSTACK on an empty altstack");
                stack.add(altstack.pollLast());
                break;
            case OP_2DROP:
                if (stack.size() < 2)
                    throw new ScriptException("Attempted OP_2DROP on a stack with size < 2");
                stack.pollLast();
                stack.pollLast();
                break;
            case OP_2DUP:
                if (stack.size() < 2)
                    throw new ScriptException("Attempted OP_2DUP on a stack with size < 2");
                Iterator<byte[]> it2DUP = stack.descendingIterator();
                byte[] OP2DUPtmpChunk2 = it2DUP.next();
                stack.add(it2DUP.next());
                stack.add(OP2DUPtmpChunk2);
                break;
            case OP_3DUP:
                if (stack.size() < 3)
                    throw new ScriptException("Attempted OP_3DUP on a stack with size < 3");
                Iterator<byte[]> it3DUP = stack.descendingIterator();
                byte[] OP3DUPtmpChunk3 = it3DUP.next();
                byte[] OP3DUPtmpChunk2 = it3DUP.next();
                stack.add(it3DUP.next());
                stack.add(OP3DUPtmpChunk2);
                stack.add(OP3DUPtmpChunk3);
                break;
            case OP_2OVER:
                if (stack.size() < 4)
                    throw new ScriptException("Attempted OP_2OVER on a stack with size < 4");
                Iterator<byte[]> it2OVER = stack.descendingIterator();
                it2OVER.next();
                it2OVER.next();
                byte[] OP2OVERtmpChunk2 = it2OVER.next();
                stack.add(it2OVER.next());
                stack.add(OP2OVERtmpChunk2);
                break;
            case OP_2ROT:
                if (stack.size() < 6)
                    throw new ScriptException("Attempted OP_2ROT on a stack with size < 6");
                byte[] OP2ROTtmpChunk6 = stack.pollLast();
                byte[] OP2ROTtmpChunk5 = stack.pollLast();
                byte[] OP2ROTtmpChunk4 = stack.pollLast();
                byte[] OP2ROTtmpChunk3 = stack.pollLast();
                byte[] OP2ROTtmpChunk2 = stack.pollLast();
                byte[] OP2ROTtmpChunk1 = stack.pollLast();
                stack.add(OP2ROTtmpChunk3);
                stack.add(OP2ROTtmpChunk4);
                stack.add(OP2ROTtmpChunk5);
                stack.add(OP2ROTtmpChunk6);
                stack.add(OP2ROTtmpChunk1);
                stack.add(OP2ROTtmpChunk2);
                break;
            case OP_2SWAP:
                if (stack.size() < 4)
                    throw new ScriptException("Attempted OP_2SWAP on a stack with size < 4");
                byte[] OP2SWAPtmpChunk4 = stack.pollLast();
                byte[] OP2SWAPtmpChunk3 = stack.pollLast();
                byte[] OP2SWAPtmpChunk2 = stack.pollLast();
                byte[] OP2SWAPtmpChunk1 = stack.pollLast();
                stack.add(OP2SWAPtmpChunk3);
                stack.add(OP2SWAPtmpChunk4);
                stack.add(OP2SWAPtmpChunk1);
                stack.add(OP2SWAPtmpChunk2);
                break;
            case OP_IFDUP:
                if (stack.size() < 1)
                    throw new ScriptException("Attempted OP_IFDUP on an empty stack");
                if (castToBool(stack.getLast()))
                    stack.add(stack.getLast());
                break;
            case OP_DEPTH:
                stack.add(Utils.reverseBytes(Utils.encodeMPI(BigInteger.valueOf(stack.size()), false)));
                break;
            case OP_DROP:
                if (stack.size() < 1)
                    throw new ScriptException("Attempted OP_DROP on an empty stack");
                stack.pollLast();
                break;
            case OP_DUP:
                if (stack.size() < 1)
                    throw new ScriptException("Attempted OP_DUP on an empty stack");
                stack.add(stack.getLast());
                break;
            case OP_NIP:
                if (stack.size() < 2)
                    throw new ScriptException("Attempted OP_NIP on a stack with size < 2");
                byte[] OPNIPtmpChunk = stack.pollLast();
                stack.pollLast();
                stack.add(OPNIPtmpChunk);
                break;
            case OP_OVER:
                if (stack.size() < 2)
                    throw new ScriptException("Attempted OP_OVER on a stack with size < 2");
                Iterator<byte[]> itOVER = stack.descendingIterator();
                itOVER.next();
                stack.add(itOVER.next());
                break;
            case OP_PICK:
            case OP_ROLL:
                if (stack.size() < 1)
                    throw new ScriptException("Attempted OP_PICK/OP_ROLL on an empty stack");
                long val = castToBigInteger(stack.pollLast()).longValue();
                if (val < 0 || val >= stack.size())
                    throw new ScriptException("OP_PICK/OP_ROLL attempted to get data deeper than stack size");
                Iterator<byte[]> itPICK = stack.descendingIterator();
                for (long i = 0; i < val; i++)
                    itPICK.next();
                byte[] OPROLLtmpChunk = itPICK.next();
                if (opcode == OP_ROLL)
                    itPICK.remove();
                stack.add(OPROLLtmpChunk);
                break;
            case OP_ROT:
                if (stack.size() < 3)
                    throw new ScriptException("Attempted OP_ROT on a stack with size < 3");
                byte[] OPROTtmpChunk3 = stack.pollLast();
                byte[] OPROTtmpChunk2 = stack.pollLast();
                byte[] OPROTtmpChunk1 = stack.pollLast();
                stack.add(OPROTtmpChunk2);
                stack.add(OPROTtmpChunk3);
                stack.add(OPROTtmpChunk1);
                break;
            case OP_SWAP:
            case OP_TUCK:
                if (stack.size() < 2)
                    throw new ScriptException("Attempted OP_SWAP on a stack with size < 2");
                byte[] OPSWAPtmpChunk2 = stack.pollLast();
                byte[] OPSWAPtmpChunk1 = stack.pollLast();
                stack.add(OPSWAPtmpChunk2);
                stack.add(OPSWAPtmpChunk1);
                if (opcode == OP_TUCK)
                    stack.add(OPSWAPtmpChunk2);
                break;
            case OP_CAT:
            case OP_SUBSTR:
            case OP_LEFT:
            case OP_RIGHT:
                throw new ScriptException("Attempted to use disabled Script Op.");
            case OP_SIZE:
                if (stack.size() < 1)
                    throw new ScriptException("Attempted OP_SIZE on an empty stack");
                stack.add(
                        Utils.reverseBytes(Utils.encodeMPI(BigInteger.valueOf(stack.getLast().length), false)));
                break;
            case OP_INVERT:
            case OP_AND:
            case OP_OR:
            case OP_XOR:
                throw new ScriptException("Attempted to use disabled Script Op.");
            case OP_EQUAL:
                if (stack.size() < 2)
                    throw new ScriptException("Attempted OP_EQUALVERIFY on a stack with size < 2");
                stack.add(Arrays.equals(stack.pollLast(), stack.pollLast()) ? new byte[] { 1 }
                        : new byte[] { 0 });
                break;
            case OP_EQUALVERIFY:
                if (stack.size() < 2)
                    throw new ScriptException("Attempted OP_EQUALVERIFY on a stack with size < 2");
                if (!Arrays.equals(stack.pollLast(), stack.pollLast()))
                    throw new ScriptException("OP_EQUALVERIFY: non-equal data");
                break;
            case OP_1ADD:
            case OP_1SUB:
            case OP_NEGATE:
            case OP_ABS:
            case OP_NOT:
            case OP_0NOTEQUAL:
                if (stack.size() < 1)
                    throw new ScriptException("Attempted a numeric op on an empty stack");
                BigInteger numericOPnum = castToBigInteger(stack.pollLast());

                switch (opcode) {
                case OP_1ADD:
                    numericOPnum = numericOPnum.add(BigInteger.ONE);
                    break;
                case OP_1SUB:
                    numericOPnum = numericOPnum.subtract(BigInteger.ONE);
                    break;
                case OP_NEGATE:
                    numericOPnum = numericOPnum.negate();
                    break;
                case OP_ABS:
                    if (numericOPnum.compareTo(BigInteger.ZERO) < 0)
                        numericOPnum = numericOPnum.negate();
                    break;
                case OP_NOT:
                    if (numericOPnum.equals(BigInteger.ZERO))
                        numericOPnum = BigInteger.ONE;
                    else
                        numericOPnum = BigInteger.ZERO;
                    break;
                case OP_0NOTEQUAL:
                    if (numericOPnum.equals(BigInteger.ZERO))
                        numericOPnum = BigInteger.ZERO;
                    else
                        numericOPnum = BigInteger.ONE;
                    break;
                default:
                    throw new AssertionError("Unreachable");
                }

                stack.add(Utils.reverseBytes(Utils.encodeMPI(numericOPnum, false)));
                break;
            case OP_2MUL:
            case OP_2DIV:
                throw new ScriptException("Attempted to use disabled Script Op.");
            case OP_ADD:
            case OP_SUB:
            case OP_BOOLAND:
            case OP_BOOLOR:
            case OP_NUMEQUAL:
            case OP_NUMNOTEQUAL:
            case OP_LESSTHAN:
            case OP_GREATERTHAN:
            case OP_LESSTHANOREQUAL:
            case OP_GREATERTHANOREQUAL:
            case OP_MIN:
            case OP_MAX:
                if (stack.size() < 2)
                    throw new ScriptException("Attempted a numeric op on a stack with size < 2");
                BigInteger numericOPnum2 = castToBigInteger(stack.pollLast());
                BigInteger numericOPnum1 = castToBigInteger(stack.pollLast());

                BigInteger numericOPresult;
                switch (opcode) {
                case OP_ADD:
                    numericOPresult = numericOPnum1.add(numericOPnum2);
                    break;
                case OP_SUB:
                    numericOPresult = numericOPnum1.subtract(numericOPnum2);
                    break;
                case OP_BOOLAND:
                    if (!numericOPnum1.equals(BigInteger.ZERO) && !numericOPnum2.equals(BigInteger.ZERO))
                        numericOPresult = BigInteger.ONE;
                    else
                        numericOPresult = BigInteger.ZERO;
                    break;
                case OP_BOOLOR:
                    if (!numericOPnum1.equals(BigInteger.ZERO) || !numericOPnum2.equals(BigInteger.ZERO))
                        numericOPresult = BigInteger.ONE;
                    else
                        numericOPresult = BigInteger.ZERO;
                    break;
                case OP_NUMEQUAL:
                    if (numericOPnum1.equals(numericOPnum2))
                        numericOPresult = BigInteger.ONE;
                    else
                        numericOPresult = BigInteger.ZERO;
                    break;
                case OP_NUMNOTEQUAL:
                    if (!numericOPnum1.equals(numericOPnum2))
                        numericOPresult = BigInteger.ONE;
                    else
                        numericOPresult = BigInteger.ZERO;
                    break;
                case OP_LESSTHAN:
                    if (numericOPnum1.compareTo(numericOPnum2) < 0)
                        numericOPresult = BigInteger.ONE;
                    else
                        numericOPresult = BigInteger.ZERO;
                    break;
                case OP_GREATERTHAN:
                    if (numericOPnum1.compareTo(numericOPnum2) > 0)
                        numericOPresult = BigInteger.ONE;
                    else
                        numericOPresult = BigInteger.ZERO;
                    break;
                case OP_LESSTHANOREQUAL:
                    if (numericOPnum1.compareTo(numericOPnum2) <= 0)
                        numericOPresult = BigInteger.ONE;
                    else
                        numericOPresult = BigInteger.ZERO;
                    break;
                case OP_GREATERTHANOREQUAL:
                    if (numericOPnum1.compareTo(numericOPnum2) >= 0)
                        numericOPresult = BigInteger.ONE;
                    else
                        numericOPresult = BigInteger.ZERO;
                    break;
                case OP_MIN:
                    if (numericOPnum1.compareTo(numericOPnum2) < 0)
                        numericOPresult = numericOPnum1;
                    else
                        numericOPresult = numericOPnum2;
                    break;
                case OP_MAX:
                    if (numericOPnum1.compareTo(numericOPnum2) > 0)
                        numericOPresult = numericOPnum1;
                    else
                        numericOPresult = numericOPnum2;
                    break;
                default:
                    throw new RuntimeException("Opcode switched at runtime?");
                }

                stack.add(Utils.reverseBytes(Utils.encodeMPI(numericOPresult, false)));
                break;
            case OP_MUL:
            case OP_DIV:
            case OP_MOD:
            case OP_LSHIFT:
            case OP_RSHIFT:
                throw new ScriptException("Attempted to use disabled Script Op.");
            case OP_NUMEQUALVERIFY:
                if (stack.size() < 2)
                    throw new ScriptException("Attempted OP_NUMEQUALVERIFY on a stack with size < 2");
                BigInteger OPNUMEQUALVERIFYnum2 = castToBigInteger(stack.pollLast());
                BigInteger OPNUMEQUALVERIFYnum1 = castToBigInteger(stack.pollLast());

                if (!OPNUMEQUALVERIFYnum1.equals(OPNUMEQUALVERIFYnum2))
                    throw new ScriptException("OP_NUMEQUALVERIFY failed");
                break;
            case OP_WITHIN:
                if (stack.size() < 3)
                    throw new ScriptException("Attempted OP_WITHIN on a stack with size < 3");
                BigInteger OPWITHINnum3 = castToBigInteger(stack.pollLast());
                BigInteger OPWITHINnum2 = castToBigInteger(stack.pollLast());
                BigInteger OPWITHINnum1 = castToBigInteger(stack.pollLast());
                if (OPWITHINnum2.compareTo(OPWITHINnum1) <= 0 && OPWITHINnum1.compareTo(OPWITHINnum3) < 0)
                    stack.add(Utils.reverseBytes(Utils.encodeMPI(BigInteger.ONE, false)));
                else
                    stack.add(Utils.reverseBytes(Utils.encodeMPI(BigInteger.ZERO, false)));
                break;
            case OP_RIPEMD160:
                if (stack.size() < 1)
                    throw new ScriptException("Attempted OP_RIPEMD160 on an empty stack");
                RIPEMD160Digest digest = new RIPEMD160Digest();
                byte[] dataToHash = stack.pollLast();
                digest.update(dataToHash, 0, dataToHash.length);
                byte[] ripmemdHash = new byte[20];
                digest.doFinal(ripmemdHash, 0);
                stack.add(ripmemdHash);
                break;
            case OP_SHA1:
                if (stack.size() < 1)
                    throw new ScriptException("Attempted OP_SHA1 on an empty stack");
                try {
                    stack.add(MessageDigest.getInstance("SHA-1").digest(stack.pollLast()));
                } catch (NoSuchAlgorithmException e) {
                    throw new RuntimeException(e); // Cannot happen.
                }
                break;
            case OP_SHA256:
                if (stack.size() < 1)
                    throw new ScriptException("Attempted OP_SHA256 on an empty stack");
                try {
                    stack.add(MessageDigest.getInstance("SHA-256").digest(stack.pollLast()));
                } catch (NoSuchAlgorithmException e) {
                    throw new RuntimeException(e); // Cannot happen.
                }
                break;
            case OP_HASH160:
                if (stack.size() < 1)
                    throw new ScriptException("Attempted OP_HASH160 on an empty stack");
                stack.add(Utils.sha256hash160(stack.pollLast()));
                break;
            case OP_HASH256:
                if (stack.size() < 1)
                    throw new ScriptException("Attempted OP_SHA256 on an empty stack");
                stack.add(Utils.doubleDigest(stack.pollLast()));
                break;
            case OP_CODESEPARATOR:
                lastCodeSepLocation = chunk.getStartLocationInProgram() + 1;
                break;
            case OP_CHECKSIG:
            case OP_CHECKSIGVERIFY:
                executeCheckSig(txContainingThis, (int) index, script, stack, lastCodeSepLocation, opcode);
                break;
            case OP_CHECKMULTISIG:
            case OP_CHECKMULTISIGVERIFY:
                opCount = executeMultiSig(txContainingThis, (int) index, script, stack, opCount,
                        lastCodeSepLocation, opcode);
                break;
            case OP_NOP1:
            case OP_NOP2:
            case OP_NOP3:
            case OP_NOP4:
            case OP_NOP5:
            case OP_NOP6:
            case OP_NOP7:
            case OP_NOP8:
            case OP_NOP9:
            case OP_NOP10:
                break;

            default:
                throw new ScriptException("Script used a reserved opcode " + opcode);
            }
        }

        if (stack.size() + altstack.size() > 1000 || stack.size() + altstack.size() < 0)
            throw new ScriptException("Stack size exceeded range");
    }

    if (!ifStack.isEmpty())
        throw new ScriptException("OP_IF/OP_NOTIF without OP_ENDIF");
}

From source file:com.gpfcomics.android.cryptnos.CryptnosApplication.java

License:Open Source License

@Override
public void onCreate() {
    // Do whatever the super needs to do:
    super.onCreate();
    // Open the database using the DB adaptor so we can access the
    // database://from  w  ww.  j a  va 2 s .  c  o  m
    DBHelper = new ParamsDbAdapter(this);
    DBHelper.open();
    // Set the root for all import/export activites.  For now, we'll
    // hard code this to the root directory of the external storage
    // device, usually an SD card.  We may change this in the future.
    importExportRoot = Environment.getExternalStorageDirectory();
    // Get the shared preferences:
    prefs = getSharedPreferences("CryptnosPrefs", Context.MODE_PRIVATE);
    // Set the text encoding.  Ideally, we will get this from the shared
    // preferences, but if it doesn't exist, try to get the default value.
    // We'll try to get the system "file.encoding" value if we can, but
    // fall back on UTF-8 as a last resort.  The try/catch is because
    // System.getProperty() can technically crash on us, but it's probably
    // not very likely.  Note that whatever we get from wherever we get
    // it, we'll write it back to the preferences; this is so the
    // preference gets written at least on the first instance.
    try {
        textEncoding = prefs.getString(PREFS_TEXT_ENCODING,
                System.getProperty("file.encoding", TEXT_ENCODING_UTF8));
    } catch (Exception e) {
        textEncoding = prefs.getString(PREFS_TEXT_ENCODING, TEXT_ENCODING_UTF8);
    }
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(PREFS_TEXT_ENCODING, textEncoding);
    editor.commit();
    // Generate the parameter salt:
    refreshParameterSalt();
    // Get our boolean preferences: copy to clipboard, show master passwords, and
    // clear passwords on focus loss.
    copyPasswordsToClipboard = prefs.getBoolean(PREFS_COPY_TO_CLIPBOARD, true);
    showMasterPassword = prefs.getBoolean(PREFS_SHOW_MASTER_PASSWD, false);
    clearPasswordsOnFocusLoss = prefs.getBoolean(PREFS_CLEAR_PASSWDS_ON_FOCUS_LOSS, false);
    // Now build our hash table of hash algorithms to lengths:
    try {
        // Get the list of hashes from the string resources:
        String[] hashes = getResources().getStringArray(R.array.hashList);
        // Declare our hash table and initialize its size to the same size
        // as the string array of hash names:
        hashLengths = new Hashtable<String, Integer>(hashes.length);
        // We're using two different hashing engines, the internal one and the
        // Bouncy Castle one, so we'll need a reference to both:
        MessageDigest internalHasher = null;
        Digest bcHasher = null;
        // Declare integers to hold the raw byte length and the Base64-encoded
        // length of each digest:
        int byteLength = 0;
        int b64Length = 0;
        // Loop through the hash name list:
        for (int i = 0; i < hashes.length; i++) {
            // If we're using an internal hasher, get the a copy of the
            // engine and find out its byte length:
            if (hashes[i].compareTo("MD5") == 0 || hashes[i].compareTo("SHA-1") == 0
                    || hashes[i].compareTo("SHA-256") == 0 || hashes[i].compareTo("SHA-384") == 0
                    || hashes[i].compareTo("SHA-512") == 0) {
                internalHasher = MessageDigest.getInstance(hashes[i]);
                byteLength = internalHasher.getDigestLength();
            }
            // For the Bouncy Castle engines, we'll need to declare each
            // individual object and then get its byte length:
            else if (hashes[i].compareTo("RIPEMD-160") == 0) {
                bcHasher = new RIPEMD160Digest();
                byteLength = bcHasher.getDigestSize();
            } else if (hashes[i].compareTo("Tiger") == 0) {
                bcHasher = new TigerDigest();
                byteLength = bcHasher.getDigestSize();
            } else if (hashes[i].compareTo("Whirlpool") == 0) {
                bcHasher = new WhirlpoolDigest();
                byteLength = bcHasher.getDigestSize();
            }
            // Now calculate the Base64-encoded length.  This formula comes
            // from the Base64 Wikipedia article:
            // https://secure.wikimedia.org/wikipedia/en/wiki/Base64
            b64Length = (byteLength + 2 - ((byteLength + 2) % 3)) / 3 * 4;
            // Now store the hash name and length into the hash table:
            hashLengths.put(hashes[i], Integer.valueOf(b64Length));
        }
        // If anything blows up, set the hash table to null, which we'll catch
        // as an error later:
    } catch (Exception e1) {
        hashLengths = null;
    }
}

From source file:com.gpfcomics.android.cryptnos.SiteParameters.java

License:Open Source License

/**
 * Given the user's secret passphrase, combine it with all the other
 * site parameters saved within to produce the generated password and
 * return it to the theApp./*from   ww  w.  j a va 2s .  c o m*/
 * @param secret The user's secret passphrase, which is never stored.
 * @param handler If not null, this handler will be notified of the
 * progress of the generation process, for the purpose of updating a
 * progress dialog, for example.
 * @return A pseudo-random password generated from the site parameters.
 * @throws Exception Thrown when any error occurs.
 */
public String generatePassword(String secret, Handler handler) throws Exception {
    Message msg = null;
    Bundle b = null;
    ;

    // Asbestos underpants:
    try {
        // The character limit must be zero or greater, while the
        // iteration count must be one or greater:
        if (charLimit >= 0 && iterations > 0) {
            // Concatenate the site and passphrase values, then
            // convert the string to a byte array for hashing:
            byte[] result = site.concat(secret).getBytes(theApp.getTextEncoding());
            // We will use one of two hashing engines.  Internally,
            // Java supports MD5, SHA-1, and a trio of SHA-2 methods.
            // We'll assume that since these are built-in, they must
            // be optimized compared to external definitions.  If
            // the selected hash is one of these, we'll use the
            // internal engine.
            MessageDigest internalHasher = null;
            Digest bcHasher = null;
            if (hash.compareTo("MD5") == 0 || hash.compareTo("SHA-1") == 0 || hash.compareTo("SHA-256") == 0
                    || hash.compareTo("SHA-384") == 0 || hash.compareTo("SHA-512") == 0) {
                internalHasher = MessageDigest.getInstance(hash);
            }
            // If it is any other engine, we'll fall back to the
            // Bouncy Castle implementations.  We may add more later,
            // but for now we'll only use the same ones supported by
            // the .NET version of Cryptnos.  There, we actually
            // re-implemented their code to fit with the .NET hashing
            // class structure; here, we'll using Bouncy Castle out
            // of the box, so it's trivial to implement them all.
            else if (hash.compareTo("RIPEMD-160") == 0) {
                bcHasher = new RIPEMD160Digest();
            } else if (hash.compareTo("Tiger") == 0) {
                bcHasher = new TigerDigest();
            } else if (hash.compareTo("Whirlpool") == 0) {
                bcHasher = new WhirlpoolDigest();
            }
            // If we're using the internal hashing engine, we've
            // got things easy.  The most complex part is feeding the
            // hash back into the engine for multiple iterations.
            if (internalHasher != null) {
                for (int i = 0; i < iterations; i++) {
                    result = internalHasher.digest(result);
                    if (handler != null) {
                        msg = handler.obtainMessage();
                        b = new Bundle();
                        b.putInt("iteration", i);
                        b.putString("password", null);
                        msg.setData(b);
                        handler.sendMessage(msg);

                    }
                }
            }
            // If we're using the Bouncy Castle stuff, we'll need to
            // do a bit more work.  Declare the result, feed it to
            // the engine, and get back the hash.  Note that we redeclare
            // the result byte array after the update so each iteration
            // puts the result hash into the array.  Also note that we
            // make sure to reset the engine after each iteration, which
            // apparently the built-in engines do automagically.
            else if (bcHasher != null) {
                for (int i = 0; i < iterations; i++) {
                    bcHasher.update(result, 0, result.length);
                    result = new byte[bcHasher.getDigestSize()];
                    bcHasher.doFinal(result, 0);
                    bcHasher.reset();
                    if (handler != null) {
                        msg = handler.obtainMessage();
                        b = new Bundle();
                        b.putInt("iteration", i);
                        b.putString("password", null);
                        msg.setData(b);
                        handler.sendMessage(msg);

                    }
                }
            }
            // By now, we *should* have the intermediate hash in hand.
            // We'll double check with a null check here, just in case.
            if (result != null) {
                // Get the raw hash as a Base64 string:
                String b64hash = base64String(result);
                // Now that we've got the hash string, we need to apply
                // our modifications.  First, the character type
                // restriction.  Based on the user's choice in the
                // drop-down, run the hash through some regular
                // expressions to chop out unwanted characters:
                Pattern p = null;
                switch (charTypes) {
                // Alphanumerics, change others to underscores
                case 1:
                    p = Pattern.compile("\\W");
                    b64hash = p.matcher(b64hash).replaceAll("_");
                    break;
                // Alphanumerics only
                case 2:
                    p = Pattern.compile("[^a-zA-Z0-9]");
                    b64hash = p.matcher(b64hash).replaceAll("");
                    break;
                // Alphabetic characters only
                case 3:
                    p = Pattern.compile("[^a-zA-Z]");
                    b64hash = p.matcher(b64hash).replaceAll("");
                    break;
                // Numbers only
                case 4:
                    p = Pattern.compile("\\D");
                    b64hash = p.matcher(b64hash).replaceAll("");
                    break;
                // By default, use all generated characters
                default:
                    break;
                }
                // Next, apply the character limit.  If it's any-
                // thing greater than zero, get only the first so
                // many characters:
                if (charLimit > 0 && b64hash.length() > charLimit)
                    b64hash = b64hash.substring(0, charLimit);
                // Now we have our final value.  Display it back
                // to the user and get ready to save it to the
                // database.
                if (handler != null) {
                    msg = handler.obtainMessage();
                    b = new Bundle();
                    b.putInt("iteration", -100);
                    b.putString("password", b64hash);
                    msg.setData(b);
                    handler.sendMessage(msg);
                }
                return b64hash;
            }
            // If for some reason something failed, the result could
            // be null.  Warn the user as such:
            else {
                throw new Exception(theApp.getResources().getString(R.string.error_null_hash));
            }
        }
        // If the iterations or character limit parsing didn't
        // come up roses, show error messages.  Note that there's
        // also a generic "unknown" one here, just in case, but
        // it's probably irrelevant.
        else {
            if (iterations <= 0)
                throw new Exception(theApp.getResources().getString(R.string.error_bad_iterations));
            else if (charLimit < 0)
                throw new Exception(theApp.getResources().getString(R.string.error_bad_charlimit));
            else
                throw new Exception(theApp.getResources().getString(R.string.error_unknown));
        }
    }
    // This should probably be more robust, but for now just throw back
    // out any exception we caught:
    catch (Exception e) {
        throw e;
    }
}

From source file:com.licel.jcardsim.crypto.AsymmetricSignatureImpl.java

License:Apache License

public AsymmetricSignatureImpl(byte algorithm) {
    this.algorithm = algorithm;
    isRecovery = false;//from   w  ww  .  j  av  a2s . co  m
    switch (algorithm) {
    case ALG_RSA_SHA_ISO9796:
        engine = new ISO9796d2Signer(new RSAEngine(), new SHA1Digest());
        break;
    case ALG_RSA_SHA_ISO9796_MR:
        engine = new ISO9796d2Signer(new RSAEngine(), new SHA1Digest());
        isRecovery = true;
        break;
    case ALG_RSA_SHA_PKCS1:
        engine = new RSADigestSigner(new SHA1Digest());
        break;
    case ALG_RSA_MD5_PKCS1:
        engine = new RSADigestSigner(new MD5Digest());
        break;
    case ALG_RSA_RIPEMD160_ISO9796:
        engine = new ISO9796d2Signer(new RSAEngine(), new RIPEMD160Digest());
        break;
    case ALG_RSA_RIPEMD160_PKCS1:
        engine = new RSADigestSigner(new RIPEMD160Digest());
        break;
    case ALG_ECDSA_SHA:
        engine = new DSADigestSigner(new ECDSASigner(), new SHA1Digest());
        break;
    }
}