Example usage for org.bouncycastle.util BigIntegers fromUnsignedByteArray

List of usage examples for org.bouncycastle.util BigIntegers fromUnsignedByteArray

Introduction

In this page you can find the example usage for org.bouncycastle.util BigIntegers fromUnsignedByteArray.

Prototype

public static BigInteger fromUnsignedByteArray(byte[] buf, int off, int length) 

Source Link

Usage

From source file:com.github.horrorho.inflatabledonkey.crypto.ec.ECPointsCompact.java

License:Open Source License

@Deprecated
public static ECPoint decodeFPPoint(ECCurve curve, byte[] data) {
    // Patched org.bouncycastle.math.ec.ECCurve#decodePoint code.
    int expectedLength = (curve.getFieldSize() + 7) / 8;
    if (expectedLength != data.length) {
        throw new IllegalArgumentException("incorrect data length for compact encoding");
    }/*www  . ja  v a 2s  .c o m*/

    BigInteger X = BigIntegers.fromUnsignedByteArray(data, 0, expectedLength);
    ECPoint p = decompressFPPoint(curve, X);

    if (!satisfiesCofactor(curve, p)) {
        throw new IllegalArgumentException("invalid point");
    }

    return p;
}

From source file:com.github.horrorho.inflatabledonkey.crypto.ec.key.imports.ECPrivateKeyImport.java

License:Open Source License

@Override
public Optional<ECPrivateKey> importKey(String curveName, byte[] data) {
    int fieldLength = ECAssistant.fieldLength(curveName);
    if (fieldLength(data.length) != fieldLength) {
        logger.warn("-- importKey() - bad data length: {} curve: {} data:0x{}", data.length, curveName,
                Hex.toHexString(data));/* ww  w  .  j  a v  a 2 s  .  co  m*/
    }

    BigInteger d = BigIntegers.fromUnsignedByteArray(data, 0, fieldLength);

    return ECKeyFactories.privateKeyFactory().createECPrivateKey(d, curveName);
}

From source file:com.github.horrorho.inflatabledonkey.crypto.ec.key.imports.ECPrivateKeyImportCompact.java

License:Open Source License

@Override
public Optional<ECPrivateKey> importKey(String curveName, byte[] data) {
    X9ECParameters x9ECParameters = ECAssistant.x9ECParameters(curveName);
    int fieldLength = ECAssistant.fieldLength(x9ECParameters);
    if (fieldLength(data.length) != fieldLength) {
        logger.warn("-- importKey() - bad data length: {} curve: {} data:0x{}", data.length, curveName,
                Hex.toHexString(data));/* www .  j  av a2s. co  m*/
    }

    BigInteger x = BigIntegers.fromUnsignedByteArray(data, 0, fieldLength);
    BigInteger y = ECPointsCompact.y(x9ECParameters.getCurve(), x);
    BigInteger d = BigIntegers.fromUnsignedByteArray(data, fieldLength, fieldLength);

    return ECKeyFactories.privateKeyFactory().createECPrivateKey(x, y, d, curveName);
}

From source file:com.github.horrorho.inflatabledonkey.crypto.ec.key.imports.ECPublicKeyImportX963.java

License:Open Source License

@Override
public Optional<ECPublicKey> importKey(String curveName, byte[] data) {
    int fieldLength = ECAssistant.fieldLength(curveName);
    if (fieldLength(data.length) != fieldLength) {
        logger.warn("-- importKey() - bad data length: {} curve: {} data:0x{}", data.length, curveName,
                Hex.toHexString(data));/* w  w  w  .ja  v a2  s. c  o  m*/
    }

    if (!checkType(data[0])) {
        logger.warn("-- importKey() - bad data type: 0x{}", Integer.toHexString(data[0]));
    }

    BigInteger x = BigIntegers.fromUnsignedByteArray(data, 1, fieldLength);
    BigInteger y = BigIntegers.fromUnsignedByteArray(data, 1 + fieldLength, fieldLength);

    return ECKeyFactories.publicKeyFactory().createECPublicKey(x, y, curveName);
}

From source file:com.github.horrorho.inflatabledonkey.crypto.eckey.imports.ECPrivateKeyImport.java

License:Open Source License

@Override
public ECPrivate importKey(String curveName, byte[] data) {
    X9ECParameters x9ECParameters = ECAssistant.x9ECParameters(curveName);
    int fieldLength = ECAssistant.fieldLength(x9ECParameters);

    ECKeyImportAssistant.checkDataLength(data, this::fieldLength, fieldLength);

    BigInteger d = BigIntegers.fromUnsignedByteArray(data, 0, fieldLength);

    return ECKeys.privateKeyFactory().createECPrivateKey(d, curveName, x9ECParameters);
}

From source file:com.github.horrorho.inflatabledonkey.crypto.eckey.imports.ECPrivateKeyImportCompact.java

License:Open Source License

@Override
public ECPrivate importKey(String curveName, byte[] data) {
    X9ECParameters x9ECParameters = ECAssistant.x9ECParameters(curveName);
    int fieldLength = ECAssistant.fieldLength(x9ECParameters);

    ECKeyImportAssistant.checkDataLength(data, this::fieldLength, fieldLength);

    BigInteger x = BigIntegers.fromUnsignedByteArray(data, 0, fieldLength);
    BigInteger y = ECPointsCompact.y(x9ECParameters.getCurve(), x);
    BigInteger d = BigIntegers.fromUnsignedByteArray(data, fieldLength, fieldLength);

    return ECKeys.privateKeyFactory().createECPrivateKey(x, y, d, curveName, x9ECParameters);
}

From source file:com.github.horrorho.inflatabledonkey.crypto.eckey.imports.ECPublicKeyImportX963.java

License:Open Source License

@Override
public ECPublic importKey(String curveName, byte[] data) {
    X9ECParameters x9ECParameters = ECAssistant.x9ECParameters(curveName);
    int fieldLength = ECAssistant.fieldLength(x9ECParameters);

    ECKeyImportAssistant.checkDataLength(data, this::fieldLength, fieldLength);
    checkType(data[0]);/*from ww  w . j  a v  a 2s  .c om*/

    BigInteger x = BigIntegers.fromUnsignedByteArray(data, 1, fieldLength);
    BigInteger y = BigIntegers.fromUnsignedByteArray(data, 1 + fieldLength, fieldLength);

    return ECKeys.publicKeyFactory().createECPublicKey(x, y, curveName, x9ECParameters);
}

From source file:com.sun.midp.pki.X509Certificate.java

License:Open Source License

/**
 * Creates a certificate by parsing the ASN.1 DER X.509 certificate
 * encoding in the specified buffer.<BR />
 * <B>NOTE:</B> In the standard edition, equivalent functionality
 * is provided by CertificateFactory.generateCertificate(InputStream).
 * <P />/*from w w  w .  j  ava  2 s .c  om*/
 * @param buf byte array to be read
 * @param off offset within the byte array
 * @param len number of bytes to be read
 * @return a certificate object corresponding to the DER encoding
 *         or null (in case of an encoding problem)
 * @exception IOException if there is a parsing error
 */
public static X509Certificate generateCertificate(byte[] buf, int off, int len) throws IOException {
    /*
     * force bad parameter errors now, so later we can consider any out of
     * bounds errors to be parsing errors
     */
    int test = buf[off] + buf[len - 1] + buf[off + len - 1];

    try {
        int start = 0;
        int size = 0;
        byte[] hash = new byte[16]; // for MD5 fingerprint
        X509Certificate res = null;
        int publicKeyLen;
        int publicKeyPos;
        int modulusPos;
        int modulusLen;
        int exponentPos;
        int exponentLen;

        // Compute the MD5 fingerprint
        MessageDigest md = MessageDigest.getInstance("MD5");

        md.update(buf, off, len);
        md.digest(hash, 0, hash.length);

        /*
         * Create a new certificate and fill its attributes by parsing 
         * the DER encoding
         */
        res = new X509Certificate();

        // Prepare to parse this certificate
        res.idx = 0;
        // Set the encoding
        res.enc = new byte[len];
        System.arraycopy(buf, off, res.enc, 0, len);
        // ... and the fingerprint
        res.fp = new byte[hash.length];
        System.arraycopy(hash, 0, res.fp, 0, hash.length);

        if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
            Logging.report(Logging.INFORMATION, LogChannels.LC_SECURITY, "-------- Begin Certificate -------");
        }

        /*
         * A Certificate is a sequence of a TBSCertificate, a signature
         * algorithm identifier and the signature
         */
        res.getLen(SEQUENCE_TYPE);
        // Now read the TBS certificate
        res.TBSStart = res.idx;
        size = res.getLen(SEQUENCE_TYPE);

        if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
            Logging.report(Logging.INFORMATION, LogChannels.LC_SECURITY,
                    "-------- Begin TBSCertificate -------");
        }

        int sigAlgIdx = res.idx + size;
        res.TBSLen = sigAlgIdx - res.TBSStart;
        // Now parse the version
        if ((res.enc[res.idx] & 0xf0) == 0xa0) {
            res.idx++;

            if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
                Logging.report(Logging.INFORMATION, LogChannels.LC_SECURITY,
                        "Version info: " + Utils.hexEncode(res.enc, (res.idx + 1), res.enc[res.idx]));
            }

            size = (res.enc[res.idx++] & 0xff);
            if (res.idx + size > res.enc.length) {
                throw new IOException("Version info too long");
            }

            // version 3 is encoded as 0x02
            res.version = (byte) (res.enc[res.idx + (size - 1)] + 1);
            res.idx += size;
        } else {
            res.version = 1; // No explicit version value
        }

        // Expect the serial number coded as an integer
        size = res.getLen(INTEGER_TYPE);
        res.serialNumber = Utils.hexEncode(res.enc, res.idx, size);
        res.serialNumberBytes = new byte[size];
        System.arraycopy(res.enc, res.idx, res.serialNumberBytes, 0, size);
        res.idx += size;

        // Expect the signature AlgorithmIdentifier
        byte id = res.getAlg();

        if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
            Logging.report(Logging.INFORMATION, LogChannels.LC_SECURITY, "Algorithm Id: " + id);
        }

        // Expect the issuer name
        start = res.idx;
        size = res.getLen(SEQUENCE_TYPE);
        int end = res.idx + size;

        try {
            res.issuer = res.getName(end);
            if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
                Logging.report(Logging.INFORMATION, LogChannels.LC_SECURITY, "Issuer: " + res.issuer);

            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new IOException("Could not parse issuer name");
        }

        // Validity is a sequence of two UTCTime values
        try {
            res.match(ValiditySeq);
            // get start time
            res.match(UTCSeq);
            res.from = getUTCTime(res.enc, res.idx);
            res.idx += UTC_LENGTH;
            // get end time
            res.match(UTCSeq);
            res.until = getUTCTime(res.enc, res.idx);
            res.idx += UTC_LENGTH;
        } catch (Exception e) {
            throw new IOException("Could not parse validity information" + "caught " + e);
        }

        // Expect the subject name
        start = res.idx;
        size = res.getLen(SEQUENCE_TYPE);
        end = res.idx + size;

        if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
            Logging.report(Logging.INFORMATION, LogChannels.LC_SECURITY,
                    "Subject: " + Utils.hexEncode(res.enc, start, size));
        }

        if (size != 0) {
            try {
                res.subject = res.getName(end);
                if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
                    Logging.report(Logging.INFORMATION, LogChannels.LC_SECURITY, "Subject: " + res.subject);
                }
            } catch (Exception e) {
                throw new IOException("Could not parse subject name");
            }
        } // NOTE: the subject can be null (empty sequence) if
          // subjectAltName is present

        // Parse the subject public key information
        if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
            Logging.report(Logging.INFORMATION, LogChannels.LC_SECURITY, "SubjectPublicKeyInfo follows");
        }

        publicKeyLen = res.getLen(SEQUENCE_TYPE);
        publicKeyPos = res.idx;

        // Match the algorithm Id
        id = res.getAlg();
        if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
            Logging.report(Logging.INFORMATION, LogChannels.LC_SECURITY, "Public Key Algorithm: " + id);
        }

        if (id != RSA_ENCRYPTION) {
            // skip the public key
            res.idx = publicKeyPos + publicKeyLen;
            res.pubKey = null;
        } else {
            // Get the bit string
            res.getLen(BITSTRING_TYPE);
            if (res.enc[res.idx++] != 0x00) {
                throw new IOException("Bitstring error while parsing public key information");
            }

            res.getLen(SEQUENCE_TYPE);
            size = res.getLen(INTEGER_TYPE);
            if (res.enc[res.idx] == (byte) 0x00) {
                // strip off the sign byte
                size--;
                res.idx++;
            }

            // Build the BouncyCastleRSAPublicKey
            modulusPos = res.idx;
            modulusLen = size;

            if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
                Logging.report(Logging.INFORMATION, LogChannels.LC_SECURITY,
                        "Modulus:  " + Utils.hexEncode(res.enc, modulusPos, modulusLen));
            }

            res.idx += size;

            size = res.getLen(INTEGER_TYPE);
            if (res.enc[res.idx] == (byte) 0x00) {
                // strip off the sign byte
                size--;
                res.idx++;
            }

            exponentPos = res.idx;
            exponentLen = size;

            res.pubKey = new BouncyCastleRSAPublicKey(
                    BigIntegers.fromUnsignedByteArray(res.enc, modulusPos, modulusLen),
                    BigIntegers.fromUnsignedByteArray(res.enc, exponentPos, exponentLen));

            if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
                Logging.report(Logging.INFORMATION, LogChannels.LC_SECURITY,
                        "Exponent: " + Utils.hexEncode(res.enc, exponentPos, exponentLen));
            }

            res.idx += size;
        }

        if (res.idx != sigAlgIdx) {
            if (res.version < 3) {
                throw new IOException("Unexpected extensions in old version cert" + res.version);
            } else {
                res.parseExtensions(sigAlgIdx);
            }
        }

        // get the signatureAlgorithm
        res.sigAlg = res.getAlg();

        if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
            Logging.report(Logging.INFORMATION, LogChannels.LC_SECURITY,
                    "Signature Algorithm: " + res.getSigAlgName());
        }

        /*
         * If this is a supported signature algorithm, compute and save
         * the hash of TBSCertificate. A null TBSCertHash indicates
         * the use of an unsupported signature algorithm (see verify())
         */
        md = null;
        if (res.sigAlg == MD2_RSA) {
            md = MessageDigest.getInstance("MD2");
        } else if (res.sigAlg == MD5_RSA) {
            md = MessageDigest.getInstance("MD5");
        } else if (res.sigAlg == SHA1_RSA) {
            md = MessageDigest.getInstance("SHA-1");
        } else if (res.sigAlg == SHA256_RSA) {
            md = MessageDigest.getInstance("SHA-256");
        }

        if (md != null) {
            res.TBSCertHash = new byte[md.getDigestLength()];
            md.update(buf, off + res.TBSStart, res.TBSLen);
            md.digest(res.TBSCertHash, 0, res.TBSCertHash.length);
        }

        // get the signature
        size = res.getLen(BITSTRING_TYPE);
        if (res.enc[res.idx++] != 0x00) {
            throw new IOException("Bitstring error in signature parsing");
        }

        /*
         * We pad the signature to a multiple of 8-bytes before storing
         * since we only support RSA modulus lengths that are multiples
         * of 8 bytes and the two should match for decryption to succeed.
         */
        int sigLen = (((size - 1) + 7) >>> 3) << 3;
        res.signature = new byte[sigLen];
        System.arraycopy(res.enc, res.idx, res.signature, (sigLen - (size - 1)), (size - 1));

        if (Logging.REPORT_LEVEL <= Logging.INFORMATION) {
            Logging.report(Logging.INFORMATION, LogChannels.LC_SECURITY,
                    sigLen + "-byte signature: " + Utils.hexEncode(res.signature));
        }
        return res;
    } catch (IndexOutOfBoundsException e) {
        throw new IOException("Bad length detected in cert DER");
    } catch (GeneralSecurityException e) {
        throw new IOException(e.toString());
    }
}