Example usage for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME

List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME

Introduction

In this page you can find the example usage for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME.

Prototype

String PROVIDER_NAME

To view the source code for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME.

Click Source Link

Usage

From source file:br.gov.jfrj.siga.cd.service.impl.CdServiceImplTest.java

License:Open Source License

@Override
protected void setUp() throws Exception {
    this.bouncyCastleProvider = (BouncyCastleProvider) Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
    if (this.bouncyCastleProvider == null) {
        this.bouncyCastleProvider = new BouncyCastleProvider();
        Security.addProvider(this.bouncyCastleProvider);
    }//from  w w  w.ja v  a  2 s . c om
    super.setUp();
}

From source file:ca.trustpoint.m2m.ecqv.EcqvProvider.java

License:Apache License

/**
 * Create a new instance.// w ww  .j  av a 2  s . c  o m
 *
 * @param algorithm Required. Signature algorithm OID.
 * @param parameters Optional. Algorithm parameters. (not currently used)
 */
public EcqvProvider(SignatureAlgorithms algorithm, byte[] parameters) throws IllegalArgumentException,
        UnsupportedOperationException, NoSuchAlgorithmException, NoSuchProviderException {
    if (algorithm == null) {
        throw new IllegalArgumentException("Missing algorithm OID");
    } else if (!algorithm.isEcqv()) {
        throw new UnsupportedOperationException(
                "This provider can only be used with ECQV-based signature types");
    }

    X962Parameters x9params = new X962Parameters(new ASN1ObjectIdentifier(algorithm.getSecOid()));

    digest = MessageDigest.getInstance(algorithm.getDigestAlgorithm().getDigestName(),
            BouncyCastleProvider.PROVIDER_NAME);
    curveParameters = ECNamedCurveTable.getParameterSpec(algorithm.getCryptoAlgorithm().getAlgorithmName());
    algorithmId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, x9params.toASN1Primitive());
}

From source file:ca.trustpoint.m2m.ecqv.EcqvProvider.java

License:Apache License

/**
 * Generate reconstruction data for an implicit certificate In the terminology of sec4,
 * ephemeralPublicKey is referenced as Ru
 *
 * @param identifyingInfo the identity portion of the implicit certificate
 * @param ephemeralPublicKey the requesters ephemeral public key
 * @param issuerPrivateKey the issuers private key
 *
 * @return reconstruction data associated with the implicit certificate
 *
 * @throws NoSuchAlgorithmException From Bouncy Castle
 * @throws InvalidAlgorithmParameterException From Bouncy Castle
 * @throws NoSuchProviderException From Bouncy Castle
 * @throws IOException//from  ww w . j  a va  2  s . com
 */
public KeyReconstructionData genReconstructionData(byte[] identifyingInfo, PublicKey ephemeralPublicKey,
        PrivateKey issuerPrivateKey) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        NoSuchProviderException, IOException {
    // Reconstruction point, in point and byte format
    ECPoint p;
    byte[] reconstructionPoint;

    // CA's ephemeral key pair (k, kG)
    BCECPublicKey caEphemeralPublicKey;
    BCECPrivateKey caEphemeralPrivateKey;

    BigInteger n = curveParameters.getN(); // get the order of the curve group
    BigInteger r; // private key recovery data and CA ephemeral private key, respectively.
    BigInteger e; // Integer representation of H(Certu)
    BigInteger dCa = ((BCECPrivateKey) issuerPrivateKey).getD(); // Private key (point multiplier)
                                                                 // of the issuer.
    ECPoint infinity = curveParameters.getCurve().getInfinity(); // The identity point.

    do {
        // create ephemeral key pair (k, kG)
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);
        keyGen.initialize(curveParameters, random);

        KeyPair caEphemeralKeyPair = keyGen.generateKeyPair();
        caEphemeralPrivateKey = (BCECPrivateKey) caEphemeralKeyPair.getPrivate();
        caEphemeralPublicKey = (BCECPublicKey) caEphemeralKeyPair.getPublic();

        // Compute Pu = Ru + kG
        // this is the reconstruction point
        p = ((BCECPublicKey) ephemeralPublicKey).getQ().add(caEphemeralPublicKey.getQ());

        reconstructionPoint = p.getEncoded(true);

        // Update the digest with the implicit certificate Certu
        for (byte b : identifyingInfo) {
            digest.update(b);
        }

        // Update digest with reconstruction point data.
        for (byte b : reconstructionPoint) {
            digest.update(b);
        }

        // hash the implicit certificate Certu and compute the integer e from H(Certu)
        e = calculateE(n, digest.digest()).mod(n);

        // from sec4 S3.4
    } while (p.multiply(e).add(curveParameters.getG().multiply(dCa)).equals(infinity));

    // compute r = ek + dCA (mod n)
    r = e.multiply(caEphemeralPrivateKey.getD()).add(dCa).mod(n);

    return new KeyReconstructionData(reconstructionPoint, integerToOctetString(r, n));
}

From source file:ca.trustpoint.m2m.M2mCertificate.java

License:Apache License

@Override
public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException,
        NoSuchProviderException, SignatureException {
    verify(key, BouncyCastleProvider.PROVIDER_NAME);
}

From source file:ca.trustpoint.m2m.M2mCertificateFactoryTest.java

License:Apache License

/**
 * Test method for/*from   w ww.  j  a va  2 s . c o m*/
 * {@link com.trustpoint.m2m.M2MCertificateFactory#engineGenerateCertPath(
 * List<? extends Certificate>)}.
 */
@Test
public void testEngineGenerateCertPathListCertificate() throws CertificateException, NoSuchProviderException {
    M2mCertificateFactory factory;
    InputStream inStream;
    CertPath certPath;

    // Construct a list of M2M certificate
    // NOTE: engineGenerateCertificate() was tested in testEngineGenerateCertificateInputStream(),
    //       so it's okay to use it for generating certificate from certificate raw data here.
    List<M2mCertificate> certs = new ArrayList<M2mCertificate>();
    M2mCertificate cert;

    factory = new M2mCertificateFactory();

    inStream = new ByteArrayInputStream(signerData);
    cert = (M2mCertificate) factory.engineGenerateCertificate(inStream);
    certs.add(cert);

    inStream = new ByteArrayInputStream(issuerData);
    cert = (M2mCertificate) factory.engineGenerateCertificate(inStream);
    certs.add(cert);

    inStream = new ByteArrayInputStream(rootcaData);
    cert = (M2mCertificate) factory.engineGenerateCertificate(inStream);
    certs.add(cert);

    // list of M2MCertificate
    certPath = factory.engineGenerateCertPath(certs);
    verifyCertificateCollection(certPath.getCertificates());

    // list of X509Certificate
    CertificateFactory x509Factory = CertificateFactory.getInstance("X.509",
            BouncyCastleProvider.PROVIDER_NAME);

    byte[] x509CertData = Base64.decode("MIIBGzCBwaADAgECAgEBMAoGCCqGSM49BAMCMBYxFDASBgNVBAMMC2JsYWNrc2Vh"
            + "bGNhMCAXDTE1MDIxMjIyNTcyNVoYDzIxMDAwNjEyMjI1NzI1WjAWMRQwEgYDVQQD"
            + "DAtibGFja3NlYWxjYTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABLK1IMycJvcH"
            + "yo2gkGv/FjxVaOpYZM0iHnFKAD/62qG/mFXKekSoMlZqaUHEVG65/l+yzjj+JLQs"
            + "a23WhS22gUYwCgYIKoZIzj0EAwIDSQAwRgIhAJmaqh38kbajdX+rxQorfaLk30Kx"
            + "mqLpRQ8X68z/kb9PAiEAhETvquCbZQYnKUZCakOv02Dj9LlLApZSPU8NybOBXp4=");
    inStream = new ByteArrayInputStream(x509CertData);
    X509Certificate x509Cert = (X509Certificate) x509Factory.generateCertificate(inStream);

    List<X509Certificate> x509Certs = new ArrayList<X509Certificate>();
    x509Certs.add(x509Cert);

    boolean exceptionThrown = false;

    try {
        factory = new M2mCertificateFactory();
        factory.engineGenerateCertPath(x509Certs);
    } catch (CertificateException e) {
        System.out.println("Expected CertificateException: " + e.getMessage());
        exceptionThrown = true;
    }

    assertTrue(exceptionThrown);
}

From source file:ca.trustpoint.m2m.M2mCertificateTest.java

License:Apache License

/**
 * Test method for//from   www. j  av  a2 s.c o m
 * {@link ca.trustpoint.m2m.M2mCertificate#verify(java.security.PublicKey, java.lang.String)}.
 */
@Test
public void testVerifyPublicKeyString() throws Exception {
    boolean exceptionThrown = false;
    M2mCertificate certificate = new M2mCertificate();

    KeyAlgorithmDefinition caKeyDefinition = new KeyAlgorithmDefinition();
    caKeyDefinition.setAlgorithm(M2mSignatureAlgorithmOids.ECDSA_SHA512_SECP521R1);

    EntityName issuer = new EntityName();
    issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.CommonName, "blueline"));

    long secondsSinceEpoch = new BigInteger(Hex.decode("57AA2B20")).longValue() * 1000;
    Date validFrom = new Date(secondsSinceEpoch);

    int validDuration = new BigInteger(Hex.decode("01E13380")).intValue();

    EntityName subject = new EntityName();
    subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.CommonName, "C (P256 ECDSA)"));

    KeyAlgorithmDefinition publicKeyDefinition = new KeyAlgorithmDefinition();
    publicKeyDefinition.setAlgorithm(M2mSignatureAlgorithmOids.ECDSA_SHA256_SECP256R1);

    X962Parameters params = new X962Parameters(X9ObjectIdentifiers.prime256v1);
    AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey,
            params.toASN1Primitive());
    SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(algId,
            Hex.decode("040B7733A4ABF6024D9901C3EE26718E0F22AA6FD75CE4CACCE896689E39D629A005655E9088ADDE"
                    + "AC1DFC16EC26A722064C54F006EAF9A93763E16582DFA81937"));

    certificate.setSerialNumber(Hex.decode("0E"));
    certificate.setCaKeyDefinition(caKeyDefinition);
    certificate.setIssuer(issuer);
    certificate.setValidFrom(validFrom);
    certificate.setValidDuration(validDuration);
    certificate.setSubject(subject);
    certificate.setPublicKeyDefinition(publicKeyDefinition);
    certificate.setPublicKey(BouncyCastleProvider.getPublicKey(info));

    certificate.setCaCalcValue(
            Hex.decode("308188024200E6E20956572B988A8CD20F099ACB1758378B61F03C2EAABCA819D9CF59EFD427E5A71402"
                    + "C3890B76C2E900E860E55CCBCAB060971BD2ED066402D22DD3BC5C8D9C0242017492DFD4CDF1C0BF535D"
                    + "1E284E15F2357FD8C9FF688354A6B0597A1701414B571BEA82FB788094C41B407CADB4B421DBE56D1D68"
                    + "756B961FD702B02CC7C9FA9367"));

    params = new X962Parameters(SECObjectIdentifiers.secp521r1);
    algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params.toASN1Primitive());
    SubjectPublicKeyInfo caKeyInfo = new SubjectPublicKeyInfo(algId,
            Hex.decode("040043FF2A9FE4C5DDA97D82D43082AFEC8B26A925F833287C279DFA555CCB57DACF3119163470"
                    + "8FB7F02FFB5E1DF26E92E8D6617DA0134B2AA652622C725FA569795E016B2C5C7593CC381F61DD63"
                    + "B49DBB19ABA7D5C7FD8921F79DE0CABDF1D9D9728A360E51DFBA09F33787B31F97103B31AF057628"
                    + "F3E56B6C4F1089EA6F299604670E"));

    certificate.verify(BouncyCastleProvider.getPublicKey(caKeyInfo), BouncyCastleProvider.PROVIDER_NAME);

    certificate.setSerialNumber(Hex.decode("FF"));

    try {
        certificate.verify(BouncyCastleProvider.getPublicKey(caKeyInfo), BouncyCastleProvider.PROVIDER_NAME);
    } catch (Exception ex) {
        exceptionThrown = true;
    }

    assertTrue(exceptionThrown);
}

From source file:ca.trustpoint.m2m.M2mCertPathValidatorTest.java

License:Apache License

@BeforeClass
public static void initializeTests() throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    KeyAlgorithmDefinition caAlgorithm = new KeyAlgorithmDefinition();
    caAlgorithm.setAlgorithm(M2mSignatureAlgorithmOids.ECDSA_SHA512_SECP521R1);

    EntityName issuer = new EntityName();
    issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.CommonName, "blueline"));

    Date validFrom = new Date((new BigInteger(Hex.decode("5797C511"))).longValue() * 1000);
    int validDuration = (new BigInteger(Hex.decode("01E13380"))).intValue();

    EntityName subject = new EntityName();
    subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.CommonName, "blueline"));

    KeyAlgorithmDefinition pkAlgorithm = new KeyAlgorithmDefinition();
    pkAlgorithm.setAlgorithm(M2mSignatureAlgorithmOids.ECDSA_SHA512_SECP521R1);

    X962Parameters keyParams = new X962Parameters(SECObjectIdentifiers.secp521r1);
    AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey,
            keyParams.toASN1Primitive());
    SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo(algId,
            Hex.decode("040078EF059D605AB85B6A25A6EF31A1A73A632D3CB04DC606A8CA0B5823966168CFAF6131D8D9B5"
                    + "3F6BDF6B62946EC4B41D618FA3FF7F8BBFACBFD4F64FE3C33DA9D200A47AE528DC50B6F3876D7F5B"
                    + "A3C082D9927751E1A8C4F934D90942B35C57DFE311B2663E8D0187AD4EDE31BF9CD2AD8317107360"
                    + "522FDB6975AB2CD66DC029981F"));
    PublicKey publicKey = BouncyCastleProvider.getPublicKey(publicKeyInfo);

    byte[] signature = Hex
            .decode("3081880242014F15CAF8EF38626B2C7CFA85B9544E028668290CADB45F62E2153EAAF5A9D51AF5BF0D02"
                    + "F2C057D3856B5CBFB3529C25B8481405924039FA612D422AE9A1A85591024201868D3DFE5FC2BEDD2F74"
                    + "68B0B17ED2708E76CD0D37C44F4D0BB88693752046FCFC56D9818B32533B8992923C2C81499400AC44FB"
                    + "BECD6324D8AE1DD41EC73A0B2A");

    rootCertificate.setSerialNumber(new byte[] { 0x02 });
    rootCertificate.setCaKeyDefinition(caAlgorithm);
    rootCertificate.setIssuer(issuer);/*  w  w w .j a v a2 s . co m*/
    rootCertificate.setValidFrom(validFrom);
    rootCertificate.setValidDuration(validDuration);
    rootCertificate.setSubject(subject);
    rootCertificate.setPublicKeyDefinition(pkAlgorithm);
    rootCertificate.setPublicKey(publicKey);
    rootCertificate.setCaCalcValue(signature);

    caAlgorithm = new KeyAlgorithmDefinition();
    caAlgorithm.setAlgorithm(M2mSignatureAlgorithmOids.ECDSA_SHA512_SECP521R1);

    issuer = new EntityName();
    issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.CommonName, "blueline"));

    validFrom = new Date((new BigInteger(Hex.decode("57990E5F"))).longValue() * 1000);
    validDuration = (new BigInteger(Hex.decode("03C26700"))).intValue();

    subject = new EntityName();
    subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.CommonName, "MyIssuer"));

    pkAlgorithm = new KeyAlgorithmDefinition();
    pkAlgorithm.setAlgorithm(M2mSignatureAlgorithmOids.ECDSA_SHA256_SECP256R1);

    keyParams = new X962Parameters(SECObjectIdentifiers.secp256r1);
    algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, keyParams.toASN1Primitive());
    publicKeyInfo = new SubjectPublicKeyInfo(algId,
            Hex.decode("0461591E779EE482541CF63EF2A0709D3D04CEBE1F621D4764EFECC4FF374864305E3742DAB2690E"
                    + "889B84906A7D2EAB444B9E03B546393BFCF9B2B3B87658C6FA"));
    publicKey = BouncyCastleProvider.getPublicKey(publicKeyInfo);

    signature = Hex
            .decode("3081870242016A8F50899193BD85FF36965129F86F64290B64FAD40E755CA367D31B3484F2A5552DDAB0"
                    + "5B1246304CFC4164E29950D56DEA04BB4D9A3D489E07106D1D3F34669D0241631ED08CD7EEAFE6114189"
                    + "53C64F1A6097B45D1ABB5FB9390A3CEAEDAB3C47FF3E7A1A754E1E0D53B2C2FEE90EB14EBDA0B4F15260"
                    + "C375FFC1868A7569B505FF08");

    issuerCertificate.setSerialNumber(new byte[] { 0x65 });
    issuerCertificate.setCaKeyDefinition(caAlgorithm);
    issuerCertificate.setIssuer(issuer);
    issuerCertificate.setValidFrom(validFrom);
    issuerCertificate.setValidDuration(validDuration);
    issuerCertificate.setSubject(subject);
    issuerCertificate.setPublicKeyDefinition(pkAlgorithm);
    issuerCertificate.setPublicKey(publicKey);
    issuerCertificate.setCaCalcValue(signature);

    caAlgorithm = new KeyAlgorithmDefinition();
    caAlgorithm.setAlgorithm(M2mSignatureAlgorithmOids.ECDSA_SHA256_SECP256R1);

    issuer = new EntityName();
    issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.CommonName, "MyIssuer"));

    validFrom = new Date((new BigInteger(Hex.decode("57A26BCC"))).longValue() * 1000);
    validDuration = (new BigInteger(Hex.decode("03C26700"))).intValue();

    subject = new EntityName();
    subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.CommonName, "MySigner"));

    keyParams = new X962Parameters(SECObjectIdentifiers.secp256r1);
    algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, keyParams.toASN1Primitive());
    publicKeyInfo = new SubjectPublicKeyInfo(algId,
            Hex.decode("0463C779CFF44EB3C97D7CDF9AB3AD9A6ED0DCB6F3F1A3155DF674109A3AAD0A757FCAF2F01E53CD"
                    + "ED25707ADC38C2271E90BB554DB4ED47B65B25BB478E9E3BF8"));
    publicKey = BouncyCastleProvider.getPublicKey(publicKeyInfo);

    signature = Hex
            .decode("3045022100CBD969EEEB637A03D60B3271BD7320E7A3DDA1B1EF014E641F6C32BF897EEAC6022030FF7F"
                    + "FD3A59C9B16F2F335716B47402A3CFF3EE667767A89017D218203CD66E");

    signerCertificate.setSerialNumber(new byte[] { 0x68 });
    signerCertificate.setCaKeyDefinition(caAlgorithm);
    signerCertificate.setIssuer(issuer);
    signerCertificate.setValidFrom(validFrom);
    signerCertificate.setValidDuration(validDuration);
    signerCertificate.setSubject(subject);
    signerCertificate.setPublicKey(publicKey);
    signerCertificate.setCaCalcValue(signature);

    caAlgorithm = new KeyAlgorithmDefinition();
    caAlgorithm.setAlgorithm(NfcSignatureAlgorithmOids.RSA_SHA256_RSA);

    issuer = new EntityName();
    issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.Country, "US"));
    issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.Organization, "NFC Forum Test RSA CA"));

    validFrom = new Date((new BigInteger(Hex.decode("5418AEDA"))).longValue() * 1000);
    validDuration = (new BigInteger(Hex.decode("05A497A0"))).intValue();

    subject = new EntityName();
    subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.Country, "US"));
    subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.StateOrProvince, "UT"));
    subject.addAttribute(
            new EntityNameAttribute(EntityNameAttributeId.Organization, "NFC Forum RSA Test M2M EE 1"));

    algId = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, new DERSet(DERNull.INSTANCE));
    publicKeyInfo = new SubjectPublicKeyInfo(algId,
            Hex.decode("3082010A0282010100E93D3E174F587784C53A4B01C05D2F73CFEC22CCCD1FBCF1B1C5B49A118CE6"
                    + "B323640F28DFE1D5882FAFAEFDE9BB9A20347C44347D69F431AEEF5788D2EAE2131E49E3B9FD6A94"
                    + "BCE34AFCF88C603BAA8EADBC5E6BC558D1459064F9FF6F6157C472739E90B9A312A5DE67176A03FB"
                    + "A77981A6F89F1CA9C0733C67797ED6DB766FC99ABEE0C8D3641D69A9C6FD1E6F33CEE29344374146"
                    + "E9A8E3CB141163798FDD9217CF58D93E836EA735D5A7F642F203DE097C1623EB855AB72D81330014"
                    + "26163E671C747DB54629C0EAF37342CF16923FCAD53B5CAF2CECCB3876853CE003C3753FA72C1F39"
                    + "9A9B5FA7A232792FBE38C995B55B9D105F3C0AC536D841068B0203010001"));
    publicKey = BouncyCastleProvider.getPublicKey(publicKeyInfo);

    signature = Hex.decode("B6A683AF9B20715210CA38D0DAA647F48270DBF67EDF3E043BFBD02265A035540D50540F877179D6"
            + "1349B9F872AFA41646835F8353CF90049551941B89D79B3FC61B1AADE00E8BA474A4342BDAACA5CD"
            + "28AFC9DD7C505127857224D0278A6E5C9AC4344B3FA36B7FD6E5E54D4D92FBCD717AD4D2FE73C2E6"
            + "2219D6A097970BB4F956AAA948501E4083137992EEBCFA41308687F36DBE8CEC54579C76DE4DE54A"
            + "1D6E007AD22F83BEE86CDEF39A37B4BCCD71D5B0A364C258B94D0B953DC3DA5637874157C3AD7CEC"
            + "3367F3075FA1D8939B27F4062DFBE436F871AECDC6D2A3098793A1212ED192F6B128648FFE764C4D"
            + "3176D64E6594DB295400465395781A37");

    rsaTestCertificate.setSerialNumber(Hex.decode("034F3F184941B948A47F3D59EE625F09"));
    rsaTestCertificate.setCaKeyDefinition(caAlgorithm);
    rsaTestCertificate.setIssuer(issuer);
    rsaTestCertificate.setValidFrom(validFrom);
    rsaTestCertificate.setValidDuration(validDuration);
    rsaTestCertificate.setSubject(subject);
    rsaTestCertificate.setPublicKey(publicKey);
    rsaTestCertificate.setKeyUsage(new KeyUsage((byte) 0xA0));
    rsaTestCertificate.setExtendedKeyUsage("2.16.840.1.114513.29.37");
    rsaTestCertificate.setCrlDistributionPointUri(new URI("http://crl.nfctest.example.com/nfctestrsaca.crl"));
    rsaTestCertificate.setCaCalcValue(signature);

    CertificateFactory x509Factory = CertificateFactory.getInstance("X.509",
            BouncyCastleProvider.PROVIDER_NAME);

    FileInputStream fileInput = new FileInputStream("testdata/digicert_batch_2/NFC Forum Test RSA CA.cer");
    x509Ca = (X509Certificate) x509Factory.generateCertificate(fileInput);
    fileInput.close();
}

From source file:ca.trustpoint.m2m.M2mCertPathValidatorTest.java

License:Apache License

/**
 * Test method for/*from  w w w. ja v  a 2s  . c om*/
 * {@link ca.trustpoint.m2m.M2mCertPathValidator#
 *     engineValidate(java.security.cert.CertPath, java.security.cert.CertPathParameters)}.
 */
@Test
public void testEngineValidateCertPathCertPathParameters() throws Exception {
    boolean exceptionThrown = false;
    M2mCertPathValidator validator = new M2mCertPathValidator();
    M2mCertPathValidatorResult result;

    try {
        validator.engineValidate(null, null);
    } catch (InvalidAlgorithmParameterException ex) {
        exceptionThrown = true;
    }

    assertTrue(exceptionThrown);
    exceptionThrown = false;

    // list of X509Certificate
    byte[] x509CertData = Base64.decode("MIIBGzCBwaADAgECAgEBMAoGCCqGSM49BAMCMBYxFDASBgNVBAMMC2JsYWNrc2Vh"
            + "bGNhMCAXDTE1MDIxMjIyNTcyNVoYDzIxMDAwNjEyMjI1NzI1WjAWMRQwEgYDVQQD"
            + "DAtibGFja3NlYWxjYTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABLK1IMycJvcH"
            + "yo2gkGv/FjxVaOpYZM0iHnFKAD/62qG/mFXKekSoMlZqaUHEVG65/l+yzjj+JLQs"
            + "a23WhS22gUYwCgYIKoZIzj0EAwIDSQAwRgIhAJmaqh38kbajdX+rxQorfaLk30Kx"
            + "mqLpRQ8X68z/kb9PAiEAhETvquCbZQYnKUZCakOv02Dj9LlLApZSPU8NybOBXp4=");
    CertificateFactory x509Factory = CertificateFactory.getInstance("X.509",
            BouncyCastleProvider.PROVIDER_NAME);
    InputStream inStream = new ByteArrayInputStream(x509CertData);
    Certificate x509Cert = x509Factory.generateCertificate(inStream);
    List<Certificate> x509Certs = new ArrayList<Certificate>();
    x509Certs.add(x509Cert);
    CertPath x509Path = x509Factory.generateCertPath(x509Certs);

    try {
        validator.engineValidate(x509Path, null);
    } catch (InvalidAlgorithmParameterException ex) {
        exceptionThrown = true;
    }

    assertTrue(exceptionThrown);
    exceptionThrown = false;

    List<M2mCertificate> certificates = new ArrayList<M2mCertificate>();
    certificates.add(signerCertificate);
    certificates.add(issuerCertificate);
    certificates.add(rootCertificate);

    M2mCertPath path = new M2mCertPath(certificates);

    Set<TrustAnchor> pkixAnchors = new HashSet<TrustAnchor>();
    pkixAnchors.add(new TrustAnchor((X509Certificate) x509Cert, null));
    PKIXParameters pkixParams = new PKIXParameters(pkixAnchors);

    try {
        validator.engineValidate(path, pkixParams);
    } catch (InvalidAlgorithmParameterException ex) {
        exceptionThrown = true;
    }

    assertTrue(exceptionThrown);
    exceptionThrown = false;

    Calendar validityDate = new GregorianCalendar(2016, 7, 5);

    M2mCertPathParameters params = new M2mCertPathParameters(null, validityDate.getTime(), true);
    result = (M2mCertPathValidatorResult) validator.engineValidate(path, params);

    assertEquals(rootCertificate, result.getTrustAnchor().getCertificate());
    assertArrayEquals(signerCertificate.getPublicKey().getEncoded(), result.getPublicKey().getEncoded());

    params = new M2mCertPathParameters(null, validityDate.getTime(), false);

    try {
        result = (M2mCertPathValidatorResult) validator.engineValidate(path, params);
    } catch (CertPathValidatorException ex) {
        exceptionThrown = true;
    }

    assertTrue(exceptionThrown);
    exceptionThrown = false;

    certificates.remove(certificates.size() - 1);
    path = new M2mCertPath(certificates);

    try {
        result = (M2mCertPathValidatorResult) validator.engineValidate(path, params);
    } catch (CertPathValidatorException ex) {
        exceptionThrown = true;
    }

    assertTrue(exceptionThrown);
    exceptionThrown = false;

    List<M2mTrustAnchor> m2mAnchors = new ArrayList<M2mTrustAnchor>();
    m2mAnchors.add(new M2mTrustAnchor(rootCertificate));

    params = new M2mCertPathParameters(m2mAnchors, validityDate.getTime(), false);

    result = (M2mCertPathValidatorResult) validator.engineValidate(path, params);

    assertEquals(rootCertificate, result.getTrustAnchor().getCertificate());
    assertArrayEquals(signerCertificate.getPublicKey().getEncoded(), result.getPublicKey().getEncoded());
}

From source file:ca.trustpoint.m2m.M2mProvider.java

License:Apache License

/**
 * To add the provider at runtime use:/* w w  w .j av  a2  s  .  c  o  m*/
 * <pre>
 * import java.security.Security;
 * import com.trustpoint.m2m.M2MProvider;
 *
 * Security.addProvider(new M2MProvider());
 * </pre>
 * The provider can also be configured as part of your environment via static registration by
 * adding an entry to the java.security properties file (found in
 * $JAVA_HOME/jre/lib/security/java.security, where $JAVA_HOME is the location of your JDK/JRE
 * distribution). You'll find detailed instructions in the file but basically it comes down to
 * adding a line:
 * <pre>
 * <code>
 *    security.provider.&lt;n&gt;=com.trustpoint.m2m.M2MProvider
 * </code>
 * </pre>
 * Where &lt;n&gt; is the preference you want the provider at (1 being the most preferred).
 * <p>Note: JCE algorithm names should be upper-case only so the case insensitive test for
 * getInstance() works.
 */
public M2mProvider() {
    super(PROVIDER_NAME, VERSION, "M2M Certificate Handling Provider v1.0.");

    put("CertPathValidator.M2M", M2mCertPathValidator.class.getName());
    put("CertificateFactory.M2M", M2mCertificateFactory.class.getName());

    // Since this library is built on top of Bouncy Castle, make sure the Bouncy Castle provider is
    // registered.
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }
}

From source file:ca.trustpoint.m2m.util.KeyConversionUtils.java

License:Apache License

/**
 * Constructs a PublicKey object from raw EC public key data.
 *
 * @param rawKey Raw EC public key data.
 * @return A PublicKey object constructed from the raw EC public key data.
 *
 * @throws InvalidKeyException if key type or length is unrecognized.
 * @throws IOException if raw data reading error.
 *///from w w w.j  av  a 2 s  .co  m
public static PublicKey convertRawBytestoEcPublicKey(byte[] rawKey)
        throws IllegalArgumentException, InvalidKeyException, IOException {
    if (rawKey == null) {
        throw new IllegalArgumentException("rawKey cannot be null.");
    }

    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }

    boolean isCompressed = isCompressedEcPoint(rawKey);

    X962Parameters params = null;
    int keyCompressedLength = 0;

    // Obtain the length of the compressed public key
    if (isCompressed) {
        keyCompressedLength = rawKey.length;
    } else {
        keyCompressedLength = (rawKey.length - 1) / 2 + 1;
    }

    switch (keyCompressedLength) {
    case 25: // compressed 192 curve
        params = new X962Parameters(X9ObjectIdentifiers.prime192v1);
        break;
    case 29: // compressed 224 curve
        params = new X962Parameters(SECObjectIdentifiers.secp224r1);
        break;
    case 31: // compressed 233 curve
        params = new X962Parameters(SECObjectIdentifiers.sect233r1);
        break;
    case 33: // compressed 256 curve
        params = new X962Parameters(X9ObjectIdentifiers.prime256v1);
        break;
    case 49: // compressed 384 curve
        params = new X962Parameters(SECObjectIdentifiers.secp384r1);
        break;
    case 67: // compressed 521 curve
        params = new X962Parameters(SECObjectIdentifiers.secp521r1);
        break;
    default:
        throw new InvalidKeyException("unrecognized public key length: (" + keyCompressedLength + ")");
    }

    AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey,
            params.toASN1Primitive());
    SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(algId, rawKey);

    BCECPublicKey key = (BCECPublicKey) BouncyCastleProvider.getPublicKey(info);
    if (isCompressed) {
        key.setPointFormat("COMPRESSED");
    }

    return key;
}