Search in sources :

Example 71 with AlgorithmIdentifier

use of org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier in project jruby-openssl by jruby.

the class PKCS10Request method resetSignedRequest.

private void resetSignedRequest() {
    if (signedRequest == null)
        return;
    CertificationRequest req = signedRequest.toASN1Structure();
    CertificationRequestInfo reqInfo = new CertificationRequestInfo(subject, publicKeyInfo, req.getCertificationRequestInfo().getAttributes());
    ASN1Sequence seq = (ASN1Sequence) req.toASN1Primitive();
    req = new CertificationRequest(reqInfo, (AlgorithmIdentifier) seq.getObjectAt(1), (DERBitString) seq.getObjectAt(2));
    // valid = true;
    signedRequest = new PKCS10CertificationRequest(req);
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DERBitString(org.bouncycastle.asn1.DERBitString) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) CertificationRequest(org.bouncycastle.asn1.pkcs.CertificationRequest) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 72 with AlgorithmIdentifier

use of org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier in project robovm by robovm.

the class PublicKeyFactory method createKey.

/**
     * Create a public key from the passed in SubjectPublicKeyInfo
     * 
     * @param keyInfo the SubjectPublicKeyInfo containing the key data
     * @return the appropriate key parameter
     * @throws IOException on an error decoding the key
     */
public static AsymmetricKeyParameter createKey(SubjectPublicKeyInfo keyInfo) throws IOException {
    AlgorithmIdentifier algId = keyInfo.getAlgorithm();
    if (algId.getAlgorithm().equals(PKCSObjectIdentifiers.rsaEncryption) || algId.getAlgorithm().equals(X509ObjectIdentifiers.id_ea_rsa)) {
        RSAPublicKey pubKey = RSAPublicKey.getInstance(keyInfo.parsePublicKey());
        return new RSAKeyParameters(false, pubKey.getModulus(), pubKey.getPublicExponent());
    } else if (algId.getAlgorithm().equals(X9ObjectIdentifiers.dhpublicnumber)) {
        DHPublicKey dhPublicKey = DHPublicKey.getInstance(keyInfo.parsePublicKey());
        BigInteger y = dhPublicKey.getY().getValue();
        DHDomainParameters dhParams = DHDomainParameters.getInstance(algId.getParameters());
        BigInteger p = dhParams.getP().getValue();
        BigInteger g = dhParams.getG().getValue();
        BigInteger q = dhParams.getQ().getValue();
        BigInteger j = null;
        if (dhParams.getJ() != null) {
            j = dhParams.getJ().getValue();
        }
        DHValidationParameters validation = null;
        DHValidationParms dhValidationParms = dhParams.getValidationParms();
        if (dhValidationParms != null) {
            byte[] seed = dhValidationParms.getSeed().getBytes();
            BigInteger pgenCounter = dhValidationParms.getPgenCounter().getValue();
            // TODO Check pgenCounter size?
            validation = new DHValidationParameters(seed, pgenCounter.intValue());
        }
        return new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation));
    } else if (algId.getAlgorithm().equals(PKCSObjectIdentifiers.dhKeyAgreement)) {
        DHParameter params = DHParameter.getInstance(algId.getParameters());
        ASN1Integer derY = (ASN1Integer) keyInfo.parsePublicKey();
        BigInteger lVal = params.getL();
        int l = lVal == null ? 0 : lVal.intValue();
        DHParameters dhParams = new DHParameters(params.getP(), params.getG(), null, l);
        return new DHPublicKeyParameters(derY.getValue(), dhParams);
    } else // END android-removed
    if (algId.getAlgorithm().equals(X9ObjectIdentifiers.id_dsa) || algId.getAlgorithm().equals(OIWObjectIdentifiers.dsaWithSHA1)) {
        ASN1Integer derY = (ASN1Integer) keyInfo.parsePublicKey();
        ASN1Encodable de = algId.getParameters();
        DSAParameters parameters = null;
        if (de != null) {
            DSAParameter params = DSAParameter.getInstance(de.toASN1Primitive());
            parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
        }
        return new DSAPublicKeyParameters(derY.getValue(), parameters);
    } else if (algId.getAlgorithm().equals(X9ObjectIdentifiers.id_ecPublicKey)) {
        X962Parameters params = new X962Parameters((ASN1Primitive) algId.getParameters());
        X9ECParameters x9;
        if (params.isNamedCurve()) {
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) params.getParameters();
            x9 = X962NamedCurves.getByOID(oid);
            if (x9 == null) {
                x9 = SECNamedCurves.getByOID(oid);
                if (x9 == null) {
                    x9 = NISTNamedCurves.getByOID(oid);
                // BEGIN android-removed
                // if (x9 == null)
                // {
                //     x9 = TeleTrusTNamedCurves.getByOID(oid);
                // }
                // END android-removed
                }
            }
        } else {
            x9 = X9ECParameters.getInstance(params.getParameters());
        }
        ASN1OctetString key = new DEROctetString(keyInfo.getPublicKeyData().getBytes());
        X9ECPoint derQ = new X9ECPoint(x9.getCurve(), key);
        // TODO We lose any named parameters here
        ECDomainParameters dParams = new ECDomainParameters(x9.getCurve(), x9.getG(), x9.getN(), x9.getH(), x9.getSeed());
        return new ECPublicKeyParameters(derQ.getPoint(), dParams);
    } else {
        throw new RuntimeException("algorithm identifier in key not recognised");
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DHPublicKeyParameters(org.bouncycastle.crypto.params.DHPublicKeyParameters) ECDomainParameters(org.bouncycastle.crypto.params.ECDomainParameters) DHPublicKey(org.bouncycastle.asn1.x9.DHPublicKey) X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) DHValidationParms(org.bouncycastle.asn1.x9.DHValidationParms) ECPublicKeyParameters(org.bouncycastle.crypto.params.ECPublicKeyParameters) RSAKeyParameters(org.bouncycastle.crypto.params.RSAKeyParameters) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) X962Parameters(org.bouncycastle.asn1.x9.X962Parameters) RSAPublicKey(org.bouncycastle.asn1.pkcs.RSAPublicKey) DHValidationParameters(org.bouncycastle.crypto.params.DHValidationParameters) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) DHParameter(org.bouncycastle.asn1.pkcs.DHParameter) DSAPublicKeyParameters(org.bouncycastle.crypto.params.DSAPublicKeyParameters) DHParameters(org.bouncycastle.crypto.params.DHParameters) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) X9ECPoint(org.bouncycastle.asn1.x9.X9ECPoint) X9ECPoint(org.bouncycastle.asn1.x9.X9ECPoint) BigInteger(java.math.BigInteger) DHDomainParameters(org.bouncycastle.asn1.x9.DHDomainParameters) DSAParameters(org.bouncycastle.crypto.params.DSAParameters) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 73 with AlgorithmIdentifier

use of org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier in project platform_frameworks_base by android.

the class AndroidKeyStoreKeyPairGeneratorSpi method generateSelfSignedCertificateWithFakeSignature.

@SuppressWarnings("deprecation")
private X509Certificate generateSelfSignedCertificateWithFakeSignature(PublicKey publicKey) throws IOException, CertificateParsingException {
    V3TBSCertificateGenerator tbsGenerator = new V3TBSCertificateGenerator();
    ASN1ObjectIdentifier sigAlgOid;
    AlgorithmIdentifier sigAlgId;
    byte[] signature;
    switch(mKeymasterAlgorithm) {
        case KeymasterDefs.KM_ALGORITHM_EC:
            sigAlgOid = X9ObjectIdentifiers.ecdsa_with_SHA256;
            sigAlgId = new AlgorithmIdentifier(sigAlgOid);
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERInteger(0));
            v.add(new DERInteger(0));
            signature = new DERSequence().getEncoded();
            break;
        case KeymasterDefs.KM_ALGORITHM_RSA:
            sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
            sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE);
            signature = new byte[1];
            break;
        default:
            throw new ProviderException("Unsupported key algorithm: " + mKeymasterAlgorithm);
    }
    try (ASN1InputStream publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded())) {
        tbsGenerator.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject()));
    }
    tbsGenerator.setSerialNumber(new ASN1Integer(mSpec.getCertificateSerialNumber()));
    X509Principal subject = new X509Principal(mSpec.getCertificateSubject().getEncoded());
    tbsGenerator.setSubject(subject);
    tbsGenerator.setIssuer(subject);
    tbsGenerator.setStartDate(new Time(mSpec.getCertificateNotBefore()));
    tbsGenerator.setEndDate(new Time(mSpec.getCertificateNotAfter()));
    tbsGenerator.setSignature(sigAlgId);
    TBSCertificate tbsCertificate = tbsGenerator.generateTBSCertificate();
    ASN1EncodableVector result = new ASN1EncodableVector();
    result.add(tbsCertificate);
    result.add(sigAlgId);
    result.add(new DERBitString(signature));
    return new X509CertificateObject(Certificate.getInstance(new DERSequence(result)));
}
Also used : ASN1InputStream(com.android.org.bouncycastle.asn1.ASN1InputStream) ProviderException(java.security.ProviderException) Time(com.android.org.bouncycastle.asn1.x509.Time) DERBitString(com.android.org.bouncycastle.asn1.DERBitString) ASN1Integer(com.android.org.bouncycastle.asn1.ASN1Integer) AlgorithmIdentifier(com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERInteger(com.android.org.bouncycastle.asn1.DERInteger) DERSequence(com.android.org.bouncycastle.asn1.DERSequence) X509CertificateObject(com.android.org.bouncycastle.jce.provider.X509CertificateObject) X509Principal(com.android.org.bouncycastle.jce.X509Principal) ASN1EncodableVector(com.android.org.bouncycastle.asn1.ASN1EncodableVector) V3TBSCertificateGenerator(com.android.org.bouncycastle.asn1.x509.V3TBSCertificateGenerator) TBSCertificate(com.android.org.bouncycastle.asn1.x509.TBSCertificate) ASN1ObjectIdentifier(com.android.org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 74 with AlgorithmIdentifier

use of org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier in project helios by spotify.

the class X509CertificateFactory method generate.

private CertificateAndPrivateKey generate(final AgentProxy agentProxy, final Identity identity, final String username) {
    final UUID uuid = new UUID();
    final Calendar calendar = Calendar.getInstance();
    final X500Name issuerdn = new X500Name("C=US,O=Spotify,CN=helios-client");
    final X500Name subjectdn = new X500NameBuilder().addRDN(BCStyle.UID, username).build();
    calendar.add(Calendar.MILLISECOND, -validBeforeMilliseconds);
    final Date notBefore = calendar.getTime();
    calendar.add(Calendar.MILLISECOND, validBeforeMilliseconds + validAfterMilliseconds);
    final Date notAfter = calendar.getTime();
    // Reuse the UUID time as a SN
    final BigInteger serialNumber = BigInteger.valueOf(uuid.getTime()).abs();
    try {
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
        keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();
        final SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));
        final X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuerdn, serialNumber, notBefore, notAfter, subjectdn, subjectPublicKeyInfo);
        final DigestCalculator digestCalculator = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        final X509ExtensionUtils utils = new X509ExtensionUtils(digestCalculator);
        final SubjectKeyIdentifier keyId = utils.createSubjectKeyIdentifier(subjectPublicKeyInfo);
        final String keyIdHex = KEY_ID_ENCODING.encode(keyId.getKeyIdentifier());
        log.info("generating an X509 certificate for {} with key ID={} and identity={}", username, keyIdHex, identity.getComment());
        builder.addExtension(Extension.subjectKeyIdentifier, false, keyId);
        builder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(subjectPublicKeyInfo));
        builder.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign));
        builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
        final X509CertificateHolder holder = builder.build(new SshAgentContentSigner(agentProxy, identity));
        final X509Certificate certificate = CERTIFICATE_CONVERTER.getCertificate(holder);
        log.debug("generated certificate:\n{}", asPemString(certificate));
        return new CertificateAndPrivateKey(certificate, keyPair.getPrivate());
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}
Also used : BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) KeyPair(java.security.KeyPair) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) Calendar(java.util.Calendar) DigestCalculator(org.bouncycastle.operator.DigestCalculator) SecureRandom(java.security.SecureRandom) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyPairGenerator(java.security.KeyPairGenerator) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) UUID(com.eaio.uuid.UUID) X509ExtensionUtils(org.bouncycastle.cert.X509ExtensionUtils) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 75 with AlgorithmIdentifier

use of org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier in project OpenAttestation by OpenAttestation.

the class X509AttrBuilder method build.

public byte[] build() {
    if (notBefore == null || notAfter == null) {
        // 1 day default
        expires(1, TimeUnit.DAYS);
    }
    if (serialNumber == null) {
        dateSerial();
    }
    if (subjectName == null) {
        fault("Subject name is missing");
    }
    if (issuerName == null) {
        fault("Issuer name is missing");
    }
    if (issuerPrivateKey == null) {
        fault("Issuer private key is missing");
    }
    if (attributes.isEmpty()) {
        fault("No attributes selected");
    }
    try {
        if (getFaults().isEmpty()) {
            AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
            AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
            ContentSigner authority = null;
            if (issuerPrivateKey != null)
                // create a bouncy castle content signer convert using our existing private key
                authority = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(PrivateKeyFactory.createKey(issuerPrivateKey.getEncoded()));
            // second, prepare the attribute certificate
            // which is expected to be a UUID  like this: 33766a63-5c55-4461-8a84-5936577df450
            AttributeCertificateHolder holder = new AttributeCertificateHolder(subjectName);
            AttributeCertificateIssuer issuer = new AttributeCertificateIssuer(issuerName);
            X509v2AttributeCertificateBuilder builder = new X509v2AttributeCertificateBuilder(holder, issuer, serialNumber, notBefore, notAfter);
            for (Attribute attribute : attributes) {
                builder.addAttribute(attribute.oid, attribute.value);
            }
            // fourth, sign the attribute certificate
            if (authority != null) {
                X509AttributeCertificateHolder cert;
                cert = builder.build(authority);
                //X509AttributeCertificate.valueOf(cert.getEncoded());            
                return cert.getEncoded();
            }
        }
        return null;
    } catch (IOException | OperatorCreationException e) {
        fault(e, "cannot sign certificate");
        return null;
    } finally {
        done();
    }
}
Also used : X509v2AttributeCertificateBuilder(org.bouncycastle.cert.X509v2AttributeCertificateBuilder) AttributeCertificateIssuer(org.bouncycastle.cert.AttributeCertificateIssuer) X509AttributeCertificateHolder(org.bouncycastle.cert.X509AttributeCertificateHolder) AttributeCertificateHolder(org.bouncycastle.cert.AttributeCertificateHolder) ContentSigner(org.bouncycastle.operator.ContentSigner) X509AttributeCertificateHolder(org.bouncycastle.cert.X509AttributeCertificateHolder) IOException(java.io.IOException) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Aggregations

AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)111 IOException (java.io.IOException)47 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)35 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)35 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)32 BigInteger (java.math.BigInteger)29 X509Certificate (java.security.cert.X509Certificate)27 X500Name (org.bouncycastle.asn1.x500.X500Name)27 DEROctetString (org.bouncycastle.asn1.DEROctetString)21 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)20 KeyPair (java.security.KeyPair)19 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)19 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)19 Date (java.util.Date)18 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)18 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)17 DERSequence (org.bouncycastle.asn1.DERSequence)16 KeyPairGenerator (java.security.KeyPairGenerator)15 PublicKey (java.security.PublicKey)14 InvalidKeyException (java.security.InvalidKeyException)13