Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

List of usage examples for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream.

Prototype

public ASN1InputStream(byte[] input) 

Source Link

Document

Create an ASN1InputStream based on the input byte array.

Usage

From source file:org.cesecore.util.CertTools.java

License:Open Source License

private static ASN1Primitive getDerObjectFromByteArray(byte[] bytes) {
    if (bytes == null) {
        return null;
    }//from  w  w w  .j a  v  a 2  s.  c om
    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes));
    try {
        ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
        aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
        return aIn.readObject();
    } catch (IOException e) {
        throw new RuntimeException("Caught an unexected IOException", e);
    }
}

From source file:org.cesecore.util.PKIXCertRevocationStatusChecker.java

License:Open Source License

/**
 * Sends an OCSP request, gets a response and verifies the response as much as possible before returning it to the caller.
 * /* w w  w  .ja  va  2s  .c om*/
 * @return The OCSP response, or null of no correct response could be obtained.
 */
private SingleResp getOCSPResponse(final String ocspurl, final OCSPReq ocspRequest, final Certificate cert,
        final byte[] nonce, int expectedOcspRespCode, int expectedHttpRespCode) {
    if (log.isDebugEnabled()) {
        log.debug("Sending OCSP request to " + ocspurl + " regarding certificate with SubjectDN: "
                + CertTools.getSubjectDN(cert) + " - IssuerDN: " + CertTools.getIssuerDN(cert));
    }

    //----------------------- Open connection and send the request --------------//
    OCSPResp response = null;
    HttpURLConnection con = null;
    try {
        final URL url = new URL(ocspurl);
        con = (HttpURLConnection) url.openConnection();
        // we are going to do a POST
        con.setDoOutput(true);
        con.setRequestMethod("POST");

        // POST it
        con.setRequestProperty("Content-Type", "application/ocsp-request");
        OutputStream os = con.getOutputStream();
        os.write(ocspRequest.getEncoded());
        os.close();

        final int httpRespCode = ((HttpURLConnection) con).getResponseCode();
        if (httpRespCode != expectedHttpRespCode) {
            log.info("HTTP response from OCSP request was " + httpRespCode + ". Expected "
                    + expectedHttpRespCode);
            handleContentOfErrorStream(con.getErrorStream());
            return null; // if it is an http error code we don't need to test any more
        }

        InputStream is = con.getInputStream();
        response = new OCSPResp(IOUtils.toByteArray(is));
        is.close();

    } catch (IOException e) {
        log.info("Unable to get an OCSP response. " + e.getLocalizedMessage());
        if (con != null) {
            handleContentOfErrorStream(con.getErrorStream());
        }
        return null;
    }

    // ------------ Verify the response signature --------------//
    BasicOCSPResp brep = null;
    try {
        brep = (BasicOCSPResp) response.getResponseObject();

        if ((expectedOcspRespCode != OCSPRespBuilder.SUCCESSFUL) && (brep != null)) {
            log.warn("According to RFC 2560, responseBytes are not set on error, but we got some.");
            return null; // it messes up testing of invalid signatures... but is needed for the unsuccessful responses
        }

        if (brep == null) {
            log.warn("Cannot extract OCSP response object. OCSP response status: " + response.getStatus());
            return null;
        }

        X509CertificateHolder[] chain = brep.getCerts();
        boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(chain[0]));
        if (!verify) {
            log.warn("OCSP response signature was not valid");
            return null;
        }
    } catch (OCSPException | OperatorCreationException | CertificateException e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to obtain or verify OCSP response. " + e.getLocalizedMessage());
        }
        return null;
    }

    // ------------- Verify the nonce ---------------//
    byte[] noncerep;
    try {
        noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue().getEncoded();
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to read extension from OCSP response. " + e.getLocalizedMessage());
        }
        return null;
    }
    if (noncerep == null) {
        log.warn("Sent an OCSP request containing a nonce, but the OCSP response does not contain a nonce");
        return null;
    }

    try {
        ASN1InputStream ain = new ASN1InputStream(noncerep);
        ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject());
        ain.close();
        if (!Arrays.equals(nonce, oct.getOctets())) {
            log.warn("The nonce in the OCSP request and the OCSP response do not match");
            return null;
        }
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to read extension from OCSP response. " + e.getLocalizedMessage());
        }
        return null;
    }

    // ------------ Extract the single response and verify that it concerns a cert with the right serialnumber ----//
    SingleResp[] singleResps = brep.getResponses();
    if ((singleResps == null) || (singleResps.length == 0)) {
        if (log.isDebugEnabled()) {
            log.debug("The OCSP response object contained no responses.");
        }
        return null;
    }

    SingleResp singleResponse = singleResps[0];
    CertificateID certId = singleResponse.getCertID();
    if (!certId.getSerialNumber().equals(CertTools.getSerialNumber(cert))) {
        if (log.isDebugEnabled()) {
            log.debug(
                    "Certificate serialnumber in response does not match certificate serialnumber in request.");
        }
        return null;
    }

    // ------------ Return the single response ---------------//
    return singleResponse;
}

From source file:org.codice.ddf.condition.SignerCondition.java

License:Open Source License

private String getIdentifyFromBytes(byte[] itemBytes) {
    try (ASN1InputStream decoder = new ASN1InputStream(itemBytes)) {
        ASN1Encodable encoded = decoder.readObject();
        encoded = ((DERSequence) encoded).getObjectAt(1);
        encoded = ((DERTaggedObject) encoded).getObject();
        encoded = ((DERTaggedObject) encoded).getObject();
        return ((DERUTF8String) encoded).getString();
    } catch (IOException e) {
        return "";
    }//from   www  . jav a 2 s  .  c o  m
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

License:Open Source License

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data,
        String type, String fileName, String path, String storepass, KeyStore store)
        throws KeystoreEditorException {
    OutputStream fos = null;/*from  w  w w.  ja  va  2 s . co  m*/
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }
        Path storeFile = Paths.get(path);
        //check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            //priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            //java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();

            //we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();

                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }

            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //need to parse der separately from pem, der has the same mime type but is binary hence checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory
                    .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(
                                jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }

                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
                    Certificate certificate = certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate)
                            .getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(),
                                    keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(),
                                    chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.info(
                                    "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.",
                                    e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.info("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

/**
 * Test the basic certification request message
 *
 * @throws OperatorCreationException//  w  ww  .ja  va2 s  .c o  m
 * @throws CertificateEncodingException
 * @throws IOException
 * @throws CRMFException
 * @throws CMPException
 * @throws CMSException
 */
@Test
public void testCertification() throws OperatorCreationException, CertificateEncodingException, IOException,
        CRMFException, CMPException, CMSException, ParseException, PKICMPMessageException,
        NoSuchProviderException, NoSuchAlgorithmException, NoSuchFieldException, IllegalAccessException {
    String distinguishedName = pki.getTestUser1Cert().getSubjectX500Principal().getName();

    KeyPair keyPair = new KeyPair(pki.getTestUser1Cert().getPublicKey(), pki.getTestUser1CertPrivateKey());

    PKICMPMessages pkiMessages = new PKICMPMessages();
    pkiMessages.setPkiKeyStore(pkiKeyStoreRA);
    byte[] result = pkiMessages.createCertificateMessageWithLocalKey(distinguishedName, keyPair);

    ASN1InputStream asn1InputStream = new ASN1InputStream(result);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive);

    // Header verification
    Assert.assertEquals(pkiMessage.getHeader().getPvno().getValue(), BigInteger.valueOf(2));
    Assert.assertEquals(pkiKeyStoreRA.getRecipientCertificate().getSubjectDN().getName(),
            pkiMessage.getHeader().getRecipient().getName().toString());
    Assert.assertEquals(pkiKeyStoreRA.getSenderCertificate().getSubjectDN().getName(),
            pkiMessage.getHeader().getSender().getName().toString());
    Assert.assertNotNull(pkiMessage.getHeader().getSenderNonce());
    Assert.assertNotNull(pkiMessage.getHeader().getTransactionID());
    Assert.assertNotNull(pkiMessage.getHeader().getMessageTime().getDate());
    // check the body
    // Check the tests in Bouncycastle for decoding cert request
    Assert.assertEquals(PKIBody.TYPE_CERT_REQ, pkiMessage.getBody().getType());
    CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent())
            .toCertReqMsgArray();
    Assert.assertEquals(BigInteger.ZERO.toString(), certReqMsgs[0].getCertReq().getCertReqId().toString());
    Assert.assertEquals(distinguishedName,
            certReqMsgs[0].getCertReq().getCertTemplate().getSubject().toString());
    Assert.assertArrayEquals(keyPair.getPublic().getEncoded(),
            certReqMsgs[0].getCertReq().getCertTemplate().getPublicKey().getEncoded());
    AttributeTypeAndValue[] attributeTypeAndValue = certReqMsgs[0].getCertReq().getControls()
            .toAttributeTypeAndValueArray();
    Assert.assertEquals(CRMFObjectIdentifiers.id_regCtrl_pkiArchiveOptions, attributeTypeAndValue[0].getType());
    // Check the signature
    GeneralPKIMessage generalPKIMessage = new GeneralPKIMessage(result);
    Assert.assertTrue(generalPKIMessage.hasProtection());
    ProtectedPKIMessage pkiMsg = new ProtectedPKIMessage(generalPKIMessage);
    ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder()
            .setProvider(pkiKeyStoreRA.getProvider())
            .build(pkiKeyStoreRA.getSenderCertificate().getPublicKey());

    Assert.assertTrue(pkiMsg.verify(verifierProvider));
}

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

/**
 * Test the basic certification request message
 *
 * @throws OperatorCreationException//w ww.  ja  v a 2s.  c  o  m
 * @throws CertificateEncodingException
 * @throws IOException
 * @throws CRMFException
 * @throws CMPException
 * @throws CMSException
 */
@Test
public void testInitialization() throws OperatorCreationException, CertificateEncodingException, IOException,
        CRMFException, CMPException, CMSException, ParseException, PKICMPMessageException,
        NoSuchProviderException, NoSuchAlgorithmException, NoSuchFieldException, IllegalAccessException {
    String distinguishedName = pki.getTestUser1Cert().getSubjectX500Principal().getName();

    KeyPair keyPair = new KeyPair(pki.getTestUser1Cert().getPublicKey(), pki.getTestUser1CertPrivateKey());

    PKICMPMessages pkiMessages = new PKICMPMessages();
    pkiMessages.setPkiKeyStore(pkiKeyStoreRA);
    byte[] result = pkiMessages.createInitializationMessage(distinguishedName, keyPair);

    ASN1InputStream asn1InputStream = new ASN1InputStream(result);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive);

    // check the body
    // Check the tests in Bouncycastle for decoding cert request
    Assert.assertEquals(PKIBody.TYPE_INIT_REQ, pkiMessage.getBody().getType());
}

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

/**
 * Check the extensions in the certification request
 *
 * @throws OperatorCreationException//from w  w w. j  av a2s.c  o m
 * @throws PKICMPMessageException
 * @throws CertificateEncodingException
 * @throws IOException
 * @throws CRMFException
 * @throws CMPException
 * @throws CMSException
 */
@Test
public void testCertificationWithExtensions()
        throws OperatorCreationException, PKICMPMessageException, CertificateEncodingException, IOException,
        CRMFException, CMPException, CMSException, NoSuchFieldException, IllegalAccessException {
    String distinguishedName = pki.getTestUser1Cert().getSubjectX500Principal().getName();

    KeyPair keyPair = new KeyPair(pki.getTestUser1Cert().getPublicKey(), pki.getTestUser1CertPrivateKey());

    List<Extension> extensionList = new ArrayList<Extension>();
    // KeyUsage
    extensionList.add(new Extension(X509Extension.keyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation).getEncoded()));
    // Extended keyUsage
    List<KeyPurposeId> keyPurposeIds = new ArrayList<KeyPurposeId>();
    keyPurposeIds.add(KeyPurposeId.getInstance(KeyPurposeId.id_kp_clientAuth));
    keyPurposeIds.add(KeyPurposeId.getInstance(KeyPurposeId.id_kp_emailProtection));
    extensionList.add(new Extension(X509Extension.extendedKeyUsage, false,
            new ExtendedKeyUsage(keyPurposeIds.toArray(new KeyPurposeId[keyPurposeIds.size()])).getEncoded()));
    // Subject alternative names
    List<GeneralName> generalNames = new ArrayList<GeneralName>();
    generalNames.add(new GeneralName(GeneralName.dNSName, "www1.cryptable.org"));
    generalNames.add(new GeneralName(GeneralName.dNSName, "www2.cryptable.org"));
    GeneralNames subjectAlternativeName = new GeneralNames(
            generalNames.toArray(new GeneralName[generalNames.size()]));
    extensionList.add(
            new Extension(X509Extension.subjectAlternativeName, false, subjectAlternativeName.getEncoded()));

    PKICMPMessages pkiMessages = new PKICMPMessages();
    pkiMessages.setPkiKeyStore(pkiKeyStoreRA);
    pkiMessages.setExtensions(extensionList.toArray(new Extension[extensionList.size()]));
    byte[] result = pkiMessages.createCertificateMessageWithLocalKey(distinguishedName, keyPair);

    ASN1InputStream asn1InputStream = new ASN1InputStream(result);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive);

    CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent())
            .toCertReqMsgArray();
    // KeyUsage
    KeyUsage verifyKeyUsage = KeyUsage.getInstance(certReqMsgs[0].getCertReq().getCertTemplate().getExtensions()
            .getExtensionParsedValue(Extension.keyUsage));
    Assert.assertEquals(KeyUsage.digitalSignature | KeyUsage.nonRepudiation,
            verifyKeyUsage.getBytes()[0] & 0xFF);
    // Extended KeyUsage
    ExtendedKeyUsage verifyExtendedKeyUsage = ExtendedKeyUsage
            .fromExtensions(certReqMsgs[0].getCertReq().getCertTemplate().getExtensions());
    Assert.assertTrue(verifyExtendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth));
    Assert.assertTrue(verifyExtendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_emailProtection));
    // Subject Alternative Name
    GeneralNames verifyGeneralNames = GeneralNames.fromExtensions(
            certReqMsgs[0].getCertReq().getCertTemplate().getExtensions(), Extension.subjectAlternativeName);
    Assert.assertTrue(generalNames.contains(verifyGeneralNames.getNames()[0]));
    Assert.assertTrue(generalNames.contains(verifyGeneralNames.getNames()[1]));
}

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

/**
 * Check the extensions in the certification request
 *
 * @throws OperatorCreationException/*from   ww w .ja  va  2  s .  com*/
 * @throws PKICMPMessageException
 * @throws CertificateEncodingException
 * @throws IOException
 * @throws CRMFException
 * @throws CMPException
 * @throws CMSException
 */
@Test
public void testCertificationWithValidity()
        throws OperatorCreationException, PKICMPMessageException, CertificateEncodingException, IOException,
        CRMFException, CMPException, CMSException, NoSuchFieldException, IllegalAccessException {
    String distinguishedName = pki.getTestUser1Cert().getSubjectX500Principal().getName();

    KeyPair keyPair = new KeyPair(pki.getTestUser1Cert().getPublicKey(), pki.getTestUser1CertPrivateKey());

    Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30);
    Date notAfter = new Date(System.currentTimeMillis() + 1000L * 60 * 60 * 24 * 30);

    PKICMPMessages pkiMessages = new PKICMPMessages();
    pkiMessages.setPkiKeyStore(pkiKeyStoreRA);
    pkiMessages.setValidity(notBefore, notAfter);
    byte[] result = pkiMessages.createCertificateMessageWithLocalKey(distinguishedName, keyPair);

    ASN1InputStream asn1InputStream = new ASN1InputStream(result);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive);

    CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent())
            .toCertReqMsgArray();
    Assert.assertEquals(notBefore.toString(),
            certReqMsgs[0].getCertReq().getCertTemplate().getValidity().getNotBefore().getDate().toString());
    Assert.assertEquals(notAfter.toString(),
            certReqMsgs[0].getCertReq().getCertTemplate().getValidity().getNotAfter().getDate().toString());
}

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

/**
 * Check the private key archive control in the certification request
 *
 * @throws OperatorCreationException/*w w w  .j  a  va  2  s. co m*/
 * @throws PKICMPMessageException
 * @throws CertificateEncodingException
 * @throws IOException
 * @throws CRMFException
 * @throws CMPException
 * @throws CMSException
 */
@Test
public void testCertificationWithPrivateKeyControl()
        throws OperatorCreationException, PKICMPMessageException, CertificateException, IOException,
        CRMFException, CMPException, CMSException, InvalidKeySpecException, NoSuchAlgorithmException,
        NoSuchProviderException, NoSuchFieldException, IllegalAccessException, CRLException {
    String distinguishedName = pki.getTestUser1Cert().getSubjectX500Principal().getName();

    KeyPair keyPair = new KeyPair(pki.getTestUser1Cert().getPublicKey(), pki.getTestUser1CertPrivateKey());

    PKICMPMessages pkiMessages = new PKICMPMessages();
    pkiMessages.setPkiKeyStore(pkiKeyStoreRA);
    byte[] result = pkiMessages.createCertificateMessageWithLocalKey(distinguishedName, keyPair);

    ASN1InputStream asn1InputStream = new ASN1InputStream(result);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive);

    CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent())
            .toCertReqMsgArray();
    AttributeTypeAndValue[] attributeTypeAndValues = certReqMsgs[0].getCertReq().getControls()
            .toAttributeTypeAndValueArray();
    GeneratePKI genPKI = new GeneratePKI();
    genPKI.createPKI();

    boolean bFound = false;
    for (AttributeTypeAndValue attributeTypeAndValue : attributeTypeAndValues) {
        if (attributeTypeAndValue.getType().equals(CRMFObjectIdentifiers.id_regCtrl_pkiArchiveOptions)) {
            PKIArchiveControl pkiArchiveControl = new PKIArchiveControl(
                    PKIArchiveOptions.getInstance(attributeTypeAndValue.getValue()));

            // Decrypt data
            CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser(
                    pkiArchiveControl.getEnvelopedData().getEncoded());
            RecipientInformationStore recipients = cmsEnvelopedDataParser.getRecipientInfos();
            Collection c = recipients.getRecipients();
            Iterator it = c.iterator();

            if (it.hasNext()) {
                RecipientInformation recipient = (RecipientInformation) it.next();
                byte[] recdata = recipient
                        .getContent(new JceKeyTransEnvelopedRecipient(genPKI.getSubCACertPrivateKey())
                                .setProvider(pkiKeyStoreRA.getProvider()));
                ASN1InputStream tstAsn1InputStream = new ASN1InputStream(recdata);
                ASN1Primitive tstAsn1Primitive = tstAsn1InputStream.readObject();
                EncKeyWithID encKeyWithID = EncKeyWithID.getInstance(tstAsn1Primitive);
                Assert.assertArrayEquals(keyPair.getPrivate().getEncoded(),
                        encKeyWithID.getPrivateKey().getEncoded());
                Assert.assertTrue(encKeyWithID.hasIdentifier());
                GeneralName identifier = GeneralName.getInstance(encKeyWithID.getIdentifier());
                Assert.assertEquals(genPKI.getTestUser1Cert().getSubjectDN().getName(),
                        identifier.getName().toString());
                bFound = true;
            }
        }
    }

    Assert.assertTrue(bFound);

}

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

/**
 * Test a certification request without sending the private key
 *
 * @throws OperatorCreationException// w  ww. j ava 2s. c o m
 * @throws PKICMPMessageException
 * @throws CertificateException
 * @throws IOException
 * @throws CRMFException
 * @throws CMPException
 * @throws CMSException
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
@Test
public void testCertificationWithWithoutPrivateKey() throws OperatorCreationException, PKICMPMessageException,
        CertificateException, IOException, CRMFException, CMPException, CMSException, InvalidKeySpecException,
        NoSuchAlgorithmException, NoSuchProviderException, NoSuchFieldException, IllegalAccessException {
    String distinguishedName = pki.getTestUser1Cert().getSubjectX500Principal().getName();

    KeyPair keyPair = new KeyPair(pki.getTestUser1Cert().getPublicKey(), null);

    PKICMPMessages pkiMessages = new PKICMPMessages();
    pkiMessages.setPkiKeyStore(pkiKeyStoreRA);
    byte[] result = pkiMessages.createCertificateMessageWithLocalKey(distinguishedName, keyPair);

    ASN1InputStream asn1InputStream = new ASN1InputStream(result);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive);

    boolean bFound = false;
    CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent())
            .toCertReqMsgArray();
    Controls controls = certReqMsgs[0].getCertReq().getControls();

    Assert.assertNull(controls);
}