Search in sources :

Example 1 with ASN1Sequence

use of org.bouncycastle.asn1.ASN1Sequence in project Openfire by igniterealtime.

the class CertificateManager method createX509V3Certificate.

/**
     * Creates an X509 version3 certificate.
     *
     * @param kp           KeyPair that keeps the public and private keys for the new certificate.
     * @param days       time to live
     * @param issuerBuilder     IssuerDN builder
     * @param subjectBuilder    SubjectDN builder
     * @param domain       Domain of the server.
     * @param signAlgoritm Signature algorithm. This can be either a name or an OID.
     * @return X509 V3 Certificate
     * @throws GeneralSecurityException
     * @throws IOException
     */
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();
    X500Name issuerDN = issuerBuilder.build();
    X500Name subjectDN = subjectBuilder.build();
    // builder
    JcaX509v3CertificateBuilder certBuilder = new //
    JcaX509v3CertificateBuilder(//
    issuerDN, //
    serial, //
    new Date(), //
    new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
    subjectDN, //
    pubKey);
    // add subjectAlternativeName extension
    boolean critical = subjectDN.getRDNs().length == 0;
    ASN1Sequence othernameSequence = new DERSequence(new ASN1Encodable[] { new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERUTF8String(domain) });
    GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
    certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAltNames);
    // add keyIdentifiers extensions
    JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
    certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
    certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
    try {
        // build the certificate
        ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
        X509CertificateHolder cert = certBuilder.build(signer);
        // verify the validity
        if (!cert.isValidOn(new Date())) {
            throw new GeneralSecurityException("Certificate validity not valid");
        }
        // verify the signature (self-signed)
        ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
        if (!cert.isSignatureValid(verifierProvider)) {
            throw new GeneralSecurityException("Certificate signature not valid");
        }
        return new JcaX509CertificateConverter().getCertificate(cert);
    } catch (OperatorCreationException | CertException e) {
        throw new GeneralSecurityException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertException(org.bouncycastle.cert.CertException) Date(java.util.Date) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Example 2 with ASN1Sequence

use of org.bouncycastle.asn1.ASN1Sequence in project XobotOS by xamarin.

the class JCEDHPublicKey method isPKCSParam.

private boolean isPKCSParam(ASN1Sequence seq) {
    if (seq.size() == 2) {
        return true;
    }
    if (seq.size() > 3) {
        return false;
    }
    DERInteger l = DERInteger.getInstance(seq.getObjectAt(2));
    DERInteger p = DERInteger.getInstance(seq.getObjectAt(0));
    if (l.getValue().compareTo(BigInteger.valueOf(p.getValue().bitLength())) > 0) {
        return false;
    }
    return true;
}
Also used : DERInteger(org.bouncycastle.asn1.DERInteger)

Example 3 with ASN1Sequence

use of org.bouncycastle.asn1.ASN1Sequence in project XobotOS by xamarin.

the class JCEECPublicKey method populateFromPubKeyInfo.

private void populateFromPubKeyInfo(SubjectPublicKeyInfo info) {
    // BEGIN android-removed
    // if (info.getAlgorithmId().getObjectId().equals(CryptoProObjectIdentifiers.gostR3410_2001))
    // {
    //     DERBitString bits = info.getPublicKeyData();
    //     ASN1OctetString key;
    //     this.algorithm = "ECGOST3410";
    //
    //     try
    //     {
    //         key = (ASN1OctetString) ASN1Object.fromByteArray(bits.getBytes());
    //     }
    //     catch (IOException ex)
    //     {
    //         throw new IllegalArgumentException("error recovering public key");
    //     }
    //
    //     byte[]          keyEnc = key.getOctets();
    //     byte[]          x = new byte[32];
    //     byte[]          y = new byte[32];
    //
    //     for (int i = 0; i != x.length; i++)
    //     {
    //         x[i] = keyEnc[32 - 1 - i];
    //     }
    //
    //     for (int i = 0; i != y.length; i++)
    //     {
    //         y[i] = keyEnc[64 - 1 - i];
    //     }
    //
    //     gostParams = new GOST3410PublicKeyAlgParameters((ASN1Sequence)info.getAlgorithmId().getParameters());
    //
    //     ECNamedCurveParameterSpec spec = ECGOST3410NamedCurveTable.getParameterSpec(ECGOST3410NamedCurves.getName(gostParams.getPublicKeyParamSet()));
    //
    //     ECCurve curve = spec.getCurve();
    //     EllipticCurve ellipticCurve = EC5Util.convertCurve(curve, spec.getSeed());
    //
    //     this.q = curve.createPoint(new BigInteger(1, x), new BigInteger(1, y), false);
    //
    //     ecSpec = new ECNamedCurveSpec(
    //             ECGOST3410NamedCurves.getName(gostParams.getPublicKeyParamSet()),
    //             ellipticCurve,
    //             new ECPoint(
    //                     spec.getG().getX().toBigInteger(),
    //                     spec.getG().getY().toBigInteger()),
    //                     spec.getN(), spec.getH());
    //
    // }
    // else
    // END android-removed
    {
        X962Parameters params = new X962Parameters((DERObject) info.getAlgorithmId().getParameters());
        ECCurve curve;
        EllipticCurve ellipticCurve;
        if (params.isNamedCurve()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) params.getParameters();
            X9ECParameters ecP = ECUtil.getNamedCurveByOid(oid);
            curve = ecP.getCurve();
            ellipticCurve = EC5Util.convertCurve(curve, ecP.getSeed());
            ecSpec = new ECNamedCurveSpec(ECUtil.getCurveName(oid), ellipticCurve, new ECPoint(ecP.getG().getX().toBigInteger(), ecP.getG().getY().toBigInteger()), ecP.getN(), ecP.getH());
        } else if (params.isImplicitlyCA()) {
            ecSpec = null;
            curve = ProviderUtil.getEcImplicitlyCa().getCurve();
        } else {
            X9ECParameters ecP = new X9ECParameters((ASN1Sequence) params.getParameters());
            curve = ecP.getCurve();
            ellipticCurve = EC5Util.convertCurve(curve, ecP.getSeed());
            this.ecSpec = new ECParameterSpec(ellipticCurve, new ECPoint(ecP.getG().getX().toBigInteger(), ecP.getG().getY().toBigInteger()), ecP.getN(), ecP.getH().intValue());
        }
        DERBitString bits = info.getPublicKeyData();
        byte[] data = bits.getBytes();
        ASN1OctetString key = new DEROctetString(data);
        //
        if (data[0] == 0x04 && data[1] == data.length - 2 && (data[2] == 0x02 || data[2] == 0x03)) {
            int qLength = new X9IntegerConverter().getByteLength(curve);
            if (qLength >= data.length - 3) {
                try {
                    key = (ASN1OctetString) ASN1Object.fromByteArray(data);
                } catch (IOException ex) {
                    throw new IllegalArgumentException("error recovering public key");
                }
            }
        }
        X9ECPoint derQ = new X9ECPoint(curve, key);
        this.q = derQ.getPoint();
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) X9IntegerConverter(org.bouncycastle.asn1.x9.X9IntegerConverter) DERBitString(org.bouncycastle.asn1.DERBitString) IOException(java.io.IOException) X9ECPoint(org.bouncycastle.asn1.x9.X9ECPoint) ECPoint(java.security.spec.ECPoint) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) DEROctetString(org.bouncycastle.asn1.DEROctetString) X962Parameters(org.bouncycastle.asn1.x9.X962Parameters) DERObject(org.bouncycastle.asn1.DERObject) EllipticCurve(java.security.spec.EllipticCurve) ECParameterSpec(java.security.spec.ECParameterSpec) X9ECPoint(org.bouncycastle.asn1.x9.X9ECPoint) ECCurve(org.bouncycastle.math.ec.ECCurve) ECNamedCurveSpec(org.bouncycastle.jce.spec.ECNamedCurveSpec)

Example 4 with ASN1Sequence

use of org.bouncycastle.asn1.ASN1Sequence in project XobotOS by xamarin.

the class PKIXNameConstraintValidator method unionDN.

private Set unionDN(Set excluded, ASN1Sequence dn) {
    if (excluded.isEmpty()) {
        if (dn == null) {
            return excluded;
        }
        excluded.add(dn);
        return excluded;
    } else {
        Set intersect = new HashSet();
        Iterator it = excluded.iterator();
        while (it.hasNext()) {
            ASN1Sequence subtree = (ASN1Sequence) it.next();
            if (withinDNSubtree(dn, subtree)) {
                intersect.add(subtree);
            } else if (withinDNSubtree(subtree, dn)) {
                intersect.add(dn);
            } else {
                intersect.add(subtree);
                intersect.add(dn);
            }
        }
        return intersect;
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) Iterator(java.util.Iterator) HashSet(java.util.HashSet)

Example 5 with ASN1Sequence

use of org.bouncycastle.asn1.ASN1Sequence in project XobotOS by xamarin.

the class JDKPKCS12KeyStore method unwrapKey.

protected PrivateKey unwrapKey(AlgorithmIdentifier algId, byte[] data, char[] password, boolean wrongPKCS12Zero) throws IOException {
    String algorithm = algId.getObjectId().getId();
    PKCS12PBEParams pbeParams = new PKCS12PBEParams((ASN1Sequence) algId.getParameters());
    PBEKeySpec pbeSpec = new PBEKeySpec(password);
    PrivateKey out;
    try {
        SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm, bcProvider);
        PBEParameterSpec defParams = new PBEParameterSpec(pbeParams.getIV(), pbeParams.getIterations().intValue());
        SecretKey k = keyFact.generateSecret(pbeSpec);
        ((JCEPBEKey) k).setTryWrongPKCS12Zero(wrongPKCS12Zero);
        Cipher cipher = Cipher.getInstance(algorithm, bcProvider);
        cipher.init(Cipher.UNWRAP_MODE, k, defParams);
        // we pass "" as the key algorithm type as it is unknown at this point
        out = (PrivateKey) cipher.unwrap(data, "", Cipher.PRIVATE_KEY);
    } catch (Exception e) {
        throw new IOException("exception unwrapping private key - " + e.toString());
    }
    return out;
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) PrivateKey(java.security.PrivateKey) PKCS12PBEParams(org.bouncycastle.asn1.pkcs.PKCS12PBEParams) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) BERConstructedOctetString(org.bouncycastle.asn1.BERConstructedOctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) Cipher(javax.crypto.Cipher) IOException(java.io.IOException) SecretKeyFactory(javax.crypto.SecretKeyFactory) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException)

Aggregations

ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)200 IOException (java.io.IOException)82 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)61 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)59 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)52 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)45 DEROctetString (org.bouncycastle.asn1.DEROctetString)40 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)40 ArrayList (java.util.ArrayList)39 BigInteger (java.math.BigInteger)38 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)37 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)37 DERIA5String (org.bouncycastle.asn1.DERIA5String)37 DERSequence (org.bouncycastle.asn1.DERSequence)37 Enumeration (java.util.Enumeration)36 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)36 X509Certificate (java.security.cert.X509Certificate)34 ASN1Primitive (org.bouncycastle.asn1.ASN1Primitive)32 IssuingDistributionPoint (org.bouncycastle.asn1.x509.IssuingDistributionPoint)32 DERPrintableString (org.bouncycastle.asn1.DERPrintableString)29