Example usage for org.bouncycastle.asn1.x500 X500Name X500Name

List of usage examples for org.bouncycastle.asn1.x500 X500Name X500Name

Introduction

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

Prototype

public X500Name(String dirName) 

Source Link

Usage

From source file:dk.itst.oiosaml.sp.IntegrationTests.java

License:Mozilla Public License

private File generateCRL(X509Certificate cert) throws CRLException, NoSuchAlgorithmException,
        SignatureException, InvalidKeyException, IOException, OperatorCreationException {
    X500Name issuer = new X500Name("CN=ca");
    Date thisUpdate = new Date();
    X509v2CRLBuilder gen = new X509v2CRLBuilder(issuer, thisUpdate);
    gen.setNextUpdate(new Date(System.currentTimeMillis() + 60000));

    if (cert != null) {
        gen.addCRLEntry(cert.getSerialNumber(), new Date(System.currentTimeMillis() - 1000),
                CRLReason.keyCompromise);
    }//from w  ww. j a  va2 s . co m

    ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC")
            .build(credential.getPrivateKey());
    X509CRLHolder crl = gen.build(sigGen);

    final File crlFile = File.createTempFile("test", "test");
    crlFile.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(crlFile);
    IOUtils.write(crl.getEncoded(), fos);
    fos.close();
    return crlFile;
}

From source file:dorkbox.build.util.jar.JarSigner.java

License:Apache License

/**
 * the actual JAR signing method/*from   w  ww  . j av  a  2s  .co m*/
 * @param createDebugVersion
 */
private static ByteArrayOutputStream signJar(File jarFile, String name) throws IOException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException, GeneralSecurityException {

    // proper "jar signing" does not allow for ECC signatures to be used. RSA/DSA and that's it.
    // so this "self signed" cert is just that. wimpy.
    // the magic is in the uber-strong ECC key that is used internally, and also has AES keys mixed in.
    DSAKeyParameters[] wimpyKeys = getWimpyKeys();
    DSAPublicKeyParameters wimpyPublicKey = (DSAPublicKeyParameters) wimpyKeys[0];
    DSAPrivateKeyParameters wimpyPrivateKey = (DSAPrivateKeyParameters) wimpyKeys[1];

    // create the certificate
    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.YEAR, 2);

    Date startDate = new Date(); // time from which certificate is valid
    Date expiryDate = expiry.getTime(); // time after which certificate is not valid
    BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis()); // serial number for certificate

    X509CertificateHolder wimpyX509CertificateHolder = CryptoX509.DSA.createCertHolder(startDate, expiryDate,
            new X500Name("ST=Lunar Base Alpha, O=Dorkbox, CN=Dorkbox Server, emailaddress=admin@dorkbox.com"),
            new X500Name("ST=Earth, O=Dorkbox, CN=Dorkbox Client, emailaddress=admin@dorkbox.com"),
            serialNumber, wimpyPrivateKey, wimpyPublicKey);

    JarFile jar = new JarFile(jarFile.getCanonicalPath());

    // UNFORTUNATELY, with java6, we CANNOT do anything higher. As such, a CUSTOM signing tool will be developed,
    // which the launcher will verify on it's own.
    // FORTUNATELY, this is will produce the exact same output as if using the command line.
    String digestName = CryptoX509.Util.getDigestNameFromCert(wimpyX509CertificateHolder);
    MessageDigest messageDigest = MessageDigest.getInstance(digestName);

    // get the manifest out of the jar.
    Manifest manifest = JarUtil.getManifestFile(jar);

    // it ONLY exists if it's an "executable" jar
    if (manifest == null) {
        manifest = new Manifest();

        // have to add basic entries.
        Attributes mainAttributes = manifest.getMainAttributes();
        mainAttributes.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
    } else {
        // clear out all entries in the manifest
        Map<String, Attributes> entries = manifest.getEntries();
        if (entries.size() > 0) {
            entries.clear();
        }
    }

    // create the message digest and start updating the
    // the attributes in the manifest to contain the SHA digests
    JarSignatureUtil.updateManifestHashes(manifest, jar, messageDigest);

    byte manifestBytes[] = JarSignatureUtil.serialiseManifest(manifest);

    // create a NEW signature file manifest based on the supplied message digest and manifest.
    Manifest signatureFileManifest = JarSignatureUtil.createSignatureFileManifest(messageDigest, manifest,
            manifestBytes);
    byte signatureFileManifestBytes[] = JarSignatureUtil.serialiseManifest(signatureFileManifest);

    byte signatureBlockBytes[] = CryptoX509.createSignature(signatureFileManifestBytes,
            wimpyX509CertificateHolder, wimpyPrivateKey);

    ByteArrayOutputStream byteArrayOutputStream = JarUtil.createNewJar(jar, name, manifestBytes,
            signatureFileManifestBytes, signatureBlockBytes);

    // close the JAR file that we have been using
    jar.close();
    return byteArrayOutputStream;
}

From source file:dorkbox.util.crypto.x509Test.java

License:Apache License

@Test
public void EcdsaCertificate() throws IOException {
    // create the certificate
    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, 360);

    Date startDate = new Date(); // time from which certificate is valid
    Date expiryDate = expiry.getTime(); // time after which certificate is not valid
    BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis()); // serial number for certificate

    AsymmetricCipherKeyPair generateKeyPair = CryptoECC.generateKeyPair(CryptoECC.p521_curve,
            new SecureRandom()); // key name from Crypto class
    ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) generateKeyPair.getPrivate();
    ECPublicKeyParameters publicKey = (ECPublicKeyParameters) generateKeyPair.getPublic();

    X509CertificateHolder ECDSAx509Certificate = CryptoX509.ECDSA.createCertHolder("SHA384", startDate,
            expiryDate, new X500Name("CN=Test"), new X500Name("CN=Test"), serialNumber, privateKey, publicKey);
    // make sure it's a valid cert.
    if (ECDSAx509Certificate != null) {
        boolean valid = CryptoX509.ECDSA.validate(ECDSAx509Certificate);

        if (!valid) {
            fail("Unable to verify a x509 certificate.");
        }/*from   w w  w .  ja va2 s .  co  m*/
    } else {
        fail("Unable to create a x509 certificate.");
    }

    // now sign something, then verify the signature.
    byte[] data = "My keyboard is awesome".getBytes();
    byte[] signatureBlock = CryptoX509.createSignature(data, ECDSAx509Certificate, privateKey);

    boolean verifySignature = CryptoX509.ECDSA.verifySignature(signatureBlock, publicKey);

    if (!verifySignature) {
        fail("Unable to verify a x509 certificate signature.");
    }
}

From source file:dorkbox.util.crypto.x509Test.java

License:Apache License

@Test
public void DsaCertificate() throws IOException {
    // create the certificate
    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, 360);

    Date startDate = new Date(); // time from which certificate is valid
    Date expiryDate = expiry.getTime(); // time after which certificate is not valid
    BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis()); // serial number for certificate

    @SuppressWarnings("deprecation")
    AsymmetricCipherKeyPair generateKeyPair = CryptoDSA
            .generateKeyPair(new SecureRandom(entropySeed.getBytes()), 1024);

    DSAPrivateKeyParameters privateKey = (DSAPrivateKeyParameters) generateKeyPair.getPrivate();
    DSAPublicKeyParameters publicKey = (DSAPublicKeyParameters) generateKeyPair.getPublic();

    X509CertificateHolder DSAx509Certificate = CryptoX509.DSA.createCertHolder(startDate, expiryDate,
            new X500Name("CN=Test"), new X500Name("CN=Test"), serialNumber, privateKey, publicKey);
    // make sure it's a valid cert.
    if (DSAx509Certificate != null) {
        boolean valid = CryptoX509.DSA.validate(DSAx509Certificate);

        if (!valid) {
            fail("Unable to verify a x509 certificate.");
        }//from  w ww .  j  a v a2 s.  c  o m
    } else {
        fail("Unable to create a x509 certificate.");
    }

    // now sign something, then verify the signature.
    byte[] data = "My keyboard is awesome".getBytes();
    byte[] signatureBlock = CryptoX509.createSignature(data, DSAx509Certificate, privateKey);

    boolean verifySignature = CryptoX509.DSA.verifySignature(signatureBlock, publicKey);

    if (!verifySignature) {
        fail("Unable to verify a x509 certificate signature.");
    }
}

From source file:dorkbox.util.crypto.x509Test.java

License:Apache License

@Test
public void RsaCertificate() throws IOException {
    // create the certificate
    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, 360);

    Date startDate = new Date(); // time from which certificate is valid
    Date expiryDate = expiry.getTime(); // time after which certificate is not valid
    BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis()); // serial number for certificate

    @SuppressWarnings("deprecation")
    AsymmetricCipherKeyPair generateKeyPair = CryptoRSA
            .generateKeyPair(new SecureRandom(entropySeed.getBytes()), 1024);
    RSAPrivateCrtKeyParameters privateKey = (RSAPrivateCrtKeyParameters) generateKeyPair.getPrivate();
    RSAKeyParameters publicKey = (RSAKeyParameters) generateKeyPair.getPublic();

    X509CertificateHolder RSAx509Certificate = CryptoX509.RSA.createCertHolder(startDate, expiryDate,
            new X500Name("CN=Test"), new X500Name("CN=Test"), serialNumber, privateKey, publicKey);
    // make sure it's a valid cert.
    if (RSAx509Certificate != null) {
        boolean valid = CryptoX509.RSA.validate(RSAx509Certificate);

        if (!valid) {
            fail("Unable to verify a x509 certificate.");
        }//from   w ww  .j a  va2  s  . c  o  m
    } else {
        fail("Unable to create a x509 certificate.");
    }

    // now sign something, then verify the signature.
    byte[] data = "My keyboard is awesome".getBytes();
    byte[] signatureBlock = CryptoX509.createSignature(data, RSAx509Certificate, privateKey);

    boolean verifySignature = CryptoX509.RSA.verifySignature(signatureBlock, publicKey);

    if (!verifySignature) {
        fail("Unable to verify a x509 certificate signature.");
    }
}

From source file:edu.vt.alerts.android.library.tasks.RegistrationTask.java

License:Apache License

private PKCS10CertificationRequest generateCSR(KeyPair keyPair) throws Exception {
    JcaPKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(
            new X500Name("CN=edu.vt.alerts.mobile.android"), keyPair.getPublic());

    ContentSigner signer = new JcaContentSignerBuilder(CSR_SIGNER_ALGORITHM).setProvider(CSR_SIGNER_PROVIDER)
            .build(keyPair.getPrivate());

    return builder.build(signer);
}

From source file:ee.ria.xroad.common.OcspTestUtils.java

License:Open Source License

/**
 * Creates an OCSP response for the subject's certificate with the given status.
 * @param subject the subject certificate
 * @param issuer certificate of the subject certificate issuer
 * @param signer certificate of the OCSP response signer
 * @param signerKey key of the OCSP response signer
 * @param certStatus OCSP response status
 * @param thisUpdate date this response was valid on
 * @param nextUpdate date when next update should be requested
 * @return OCSPResp//from  w  w w.j av  a 2 s  .  c  o  m
 * @throws Exception in case of any errors
 */
public static OCSPResp createOCSPResponse(X509Certificate subject, X509Certificate issuer,
        X509Certificate signer, PrivateKey signerKey, CertificateStatus certStatus, Date thisUpdate,
        Date nextUpdate) throws Exception {
    BasicOCSPRespBuilder builder = new BasicOCSPRespBuilder(
            new RespID(new X500Name(signer.getSubjectX500Principal().getName())));
    CertificateID cid = CryptoUtils.createCertId(subject, issuer);

    if (thisUpdate != null) {
        builder.addResponse(cid, certStatus, thisUpdate, nextUpdate, null);
    } else {
        builder.addResponse(cid, certStatus);
    }

    ContentSigner contentSigner = CryptoUtils.createContentSigner(subject.getSigAlgName(), signerKey);

    Object responseObject = builder.build(contentSigner, null, new Date());

    OCSPResp resp = new OCSPRespBuilder().build(OCSPRespBuilder.SUCCESSFUL, responseObject);
    return resp;
}

From source file:ee.ria.xroad.common.util.CertUtils.java

License:Open Source License

/**
 * @param cert certificate for which to get the subject common name
 * @return short name of the certificate subject.
 * Short name is used in messages and access checking.
 *//*from ww  w .  j  av a  2  s .  c  o  m*/
public static String getSubjectCommonName(X509Certificate cert) {
    X500Principal principal = cert.getSubjectX500Principal();
    X500Name x500name = new X500Name(principal.getName());

    String cn = getRDNValue(x500name, BCStyle.CN);

    if (cn == null) {
        throw new CodedException(ErrorCodes.X_INCORRECT_CERTIFICATE,
                "Certificate subject name does not contain common name");
    }

    return cn;
}

From source file:ee.ria.xroad.common.util.CertUtils.java

License:Open Source License

/**
 * @param cert certificate from which to get the subject serial number
 * @return the SerialNumber component of the Subject field.
 *//* www  .j  a v  a  2s .  com*/
public static String getSubjectSerialNumber(X509Certificate cert) {
    X500Principal principal = cert.getSubjectX500Principal();
    X500Name x500name = new X500Name(principal.getName());

    return getRDNValue(x500name, BCStyle.SERIALNUMBER);
}

From source file:ee.ria.xroad.common.util.CertUtils.java

License:Open Source License

/**
 * @param cert certificate from which to construct the client ID
 * @return a fully constructed Client identifier from DN of the certificate.
 *///from w ww. j  a v a 2  s .co  m
public static ClientId getSubjectClientId(X509Certificate cert) {
    X500Principal principal = cert.getSubjectX500Principal();
    X500Name x500name = new X500Name(principal.getName());

    String c = getRDNValue(x500name, BCStyle.C);

    if (c == null) {
        throw new CodedException(ErrorCodes.X_INCORRECT_CERTIFICATE,
                "Certificate subject name does not contain country code");
    }

    String o = getRDNValue(x500name, BCStyle.O);

    if (o == null) {
        throw new CodedException(ErrorCodes.X_INCORRECT_CERTIFICATE,
                "Certificate subject name does not contain organization");
    }

    String cn = getRDNValue(x500name, BCStyle.CN);

    if (cn == null) {
        throw new CodedException(ErrorCodes.X_INCORRECT_CERTIFICATE,
                "Certificate subject name does not contain common name");
    }

    return ClientId.create(c, o, cn);
}