Search in sources :

Example 96 with AlgorithmIdentifier

use of com.android.apksig.internal.pkcs7.AlgorithmIdentifier in project signer by demoiselle.

the class RevocationRefs method makeCrlValidatedID.

/**
 * @param crl CrlValidatedID from X509CRL
 * @return a CrlValidatedID
 * @throws NoSuchAlgorithmException
 * @throws CRLException
 */
private CrlValidatedID makeCrlValidatedID(X509CRL crl) throws CRLException {
    Digest digest = DigestFactory.getInstance().factoryDefault();
    digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
    OtherHashAlgAndValue otherHashAlgAndValue = new OtherHashAlgAndValue(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256), new DEROctetString(digest.digest(crl.getEncoded())));
    OtherHash hash = new OtherHash(otherHashAlgAndValue);
    BigInteger crlnumber;
    CrlIdentifier crlid;
    if (crl.getExtensionValue("2.5.29.20") != null) {
        ASN1Integer varASN1Integer = new ASN1Integer(crl.getExtensionValue("2.5.29.20"));
        crlnumber = varASN1Integer.getPositiveValue();
        crlid = new CrlIdentifier(new X500Name(crl.getIssuerX500Principal().getName()), new DERUTCTime(crl.getThisUpdate()), crlnumber);
    } else {
        crlid = new CrlIdentifier(new X500Name(crl.getIssuerX500Principal().getName()), new DERUTCTime(crl.getThisUpdate()));
    }
    CrlValidatedID crlvid = new CrlValidatedID(hash, crlid);
    return crlvid;
}
Also used : CrlValidatedID(org.bouncycastle.asn1.esf.CrlValidatedID) Digest(org.demoiselle.signer.cryptography.Digest) DERUTCTime(org.bouncycastle.asn1.DERUTCTime) BigInteger(java.math.BigInteger) CrlIdentifier(org.bouncycastle.asn1.esf.CrlIdentifier) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) X500Name(org.bouncycastle.asn1.x500.X500Name) OtherHashAlgAndValue(org.bouncycastle.asn1.esf.OtherHashAlgAndValue) DEROctetString(org.bouncycastle.asn1.DEROctetString) OtherHash(org.bouncycastle.asn1.esf.OtherHash) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 97 with AlgorithmIdentifier

use of com.android.apksig.internal.pkcs7.AlgorithmIdentifier in project android by nextcloud.

the class CsrHelper method generateCSR.

/**
 * Create the certificate signing request (CSR) from private and public keys
 *
 * @param keyPair the KeyPair with private and public keys
 * @param userId userId of CSR owner
 * @return PKCS10CertificationRequest with the certificate signing request (CSR) data
 * @throws IOException thrown if key cannot be created
 * @throws OperatorCreationException thrown if contentSigner cannot be build
 */
private static PKCS10CertificationRequest generateCSR(KeyPair keyPair, String userId) throws IOException, OperatorCreationException {
    String principal = "CN=" + userId;
    AsymmetricKeyParameter privateKey = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
    AlgorithmIdentifier signatureAlgorithm = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WITHRSA");
    AlgorithmIdentifier digestAlgorithm = new DefaultDigestAlgorithmIdentifierFinder().find("SHA-1");
    ContentSigner signer = new BcRSAContentSignerBuilder(signatureAlgorithm, digestAlgorithm).build(privateKey);
    PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(new X500Name(principal), keyPair.getPublic());
    ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
    extensionsGenerator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate());
    return csrBuilder.build(signer);
}
Also used : BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) ContentSigner(org.bouncycastle.operator.ContentSigner) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator)

Example 98 with AlgorithmIdentifier

use of com.android.apksig.internal.pkcs7.AlgorithmIdentifier in project wso2-synapse by wso2.

the class CRLVerifierTest method generateFakePeerCert.

public X509Certificate generateFakePeerCert(BigInteger serialNumber, PublicKey entityKey, PrivateKey caKey, X509Certificate caCert, X509Certificate firstCertificate) throws Exception {
    Utils utils = new Utils();
    X509v3CertificateBuilder certBuilder = utils.getUsableCertificateBuilder(entityKey, serialNumber);
    certBuilder.copyAndAddExtension(Extension.cRLDistributionPoints, false, new JcaX509CertificateHolder(firstCertificate));
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(PrivateKeyFactory.createKey(caKey.getEncoded()));
    X509CertificateHolder certificateHolder = certBuilder.build(contentSigner);
    return new JcaX509CertificateConverter().setProvider(CryptoConstants.BOUNCY_CASTLE_PROVIDER).getCertificate(certificateHolder);
}
Also used : BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) ContentSigner(org.bouncycastle.operator.ContentSigner) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder)

Example 99 with AlgorithmIdentifier

use of com.android.apksig.internal.pkcs7.AlgorithmIdentifier in project wso2-synapse by wso2.

the class Utils method getFakeCertificateChain.

/**
 * Generates a fake certificate chain. The array will contain two certificates, the root and the peer.
 * @return the created array of certificates.
 * @throws Exception
 */
public X509Certificate[] getFakeCertificateChain() throws Exception {
    KeyPair rootKeyPair = generateRSAKeyPair();
    X509Certificate rootCert = generateFakeRootCert(rootKeyPair);
    KeyPair entityKeyPair = generateRSAKeyPair();
    BigInteger entitySerialNum = BigInteger.valueOf(111);
    X509v3CertificateBuilder certBuilder = getUsableCertificateBuilder(entityKeyPair.getPublic(), entitySerialNum);
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(PrivateKeyFactory.createKey(entityKeyPair.getPrivate().getEncoded()));
    X509CertificateHolder certificateHolder = certBuilder.build(contentSigner);
    X509Certificate entityCert = new JcaX509CertificateConverter().setProvider(CryptoConstants.BOUNCY_CASTLE_PROVIDER).getCertificate(certificateHolder);
    return new X509Certificate[] { entityCert, rootCert };
}
Also used : BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ContentSigner(org.bouncycastle.operator.ContentSigner) BigInteger(java.math.BigInteger) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) X509Certificate(java.security.cert.X509Certificate) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder)

Example 100 with AlgorithmIdentifier

use of com.android.apksig.internal.pkcs7.AlgorithmIdentifier in project pri-fidoiot by secure-device-onboard.

the class InteropVoucher method doPost.

@Override
protected void doPost() throws Exception {
    try {
        String pemString = getStringBody();
        OwnershipVoucher voucher = null;
        UUID guid = null;
        PrivateKey signKey = null;
        try (StringReader reader = new StringReader(pemString);
            PEMParser parser = new PEMParser(reader)) {
            for (; ; ) {
                Object obj = parser.readPemObject();
                if (obj == null) {
                    break;
                }
                if (obj instanceof PemObject) {
                    PemObject pemObj = (PemObject) obj;
                    if (pemObj.getType().equals("OWNERSHIP VOUCHER")) {
                        voucher = Mapper.INSTANCE.readValue(pemObj.getContent(), OwnershipVoucher.class);
                        OwnershipVoucherHeader header = Mapper.INSTANCE.readValue(voucher.getHeader(), OwnershipVoucherHeader.class);
                        guid = header.getGuid().toUuid();
                        logger.info("voucher guid: " + guid.toString());
                    } else if (pemObj.getType().equals("EC PRIVATE KEY")) {
                        ASN1Sequence seq = ASN1Sequence.getInstance(pemObj.getContent());
                        // PrivateKeyInfo info = PrivateKeyInfo.getInstance(seq);
                        // signKey = new JcaPEMKeyConverter().getPrivateKey(info);
                        ECPrivateKey ecpKey = ECPrivateKey.getInstance(seq);
                        AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, ecpKey.getParameters());
                        byte[] serverPkcs8 = new PrivateKeyInfo(algId, ecpKey).getEncoded();
                        KeyFactory fact = KeyFactory.getInstance("EC", "BC");
                        signKey = fact.generatePrivate(new PKCS8EncodedKeySpec(serverPkcs8));
                    } else if (pemObj.getType().equals("RSA PRIVATE KEY")) {
                        ASN1Sequence seq = ASN1Sequence.getInstance(pemObj.getContent());
                        PrivateKeyInfo info = PrivateKeyInfo.getInstance(seq);
                        signKey = new JcaPEMKeyConverter().getPrivateKey(info);
                    }
                }
            }
        }
        // we should have voucher and private key
        if (voucher != null) {
            logger.info("decoded voucher from pem");
        } else {
            logger.warn("unable to decode voucher from pem");
            getResponse().setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        if (signKey != null) {
            logger.info("decoded private key from pem");
        } else {
            logger.warn("unable to decode private key from pem");
        }
        CryptoService cs = Config.getWorker(CryptoService.class);
        KeyResolver resolver = Config.getWorker(OwnerKeySupplier.class).get();
        OwnerPublicKey prevKey = VoucherUtils.getLastOwner(voucher);
        String alias = KeyResolver.getAlias(prevKey.getType(), new AlgorithmFinder().getKeySizeType(cs.decodeKey(prevKey)));
        Certificate[] certs = resolver.getCertificateChain(alias);
        extend(voucher, signKey, certs);
        getTransaction();
        OnboardingVoucher dbVoucher = getSession().get(OnboardingVoucher.class, guid.toString());
        if (dbVoucher == null) {
            dbVoucher = new OnboardingVoucher();
            dbVoucher.setGuid(guid.toString());
            dbVoucher.setData(Mapper.INSTANCE.writeValue(voucher));
            dbVoucher.setCreatedOn(new Date(System.currentTimeMillis()));
            getSession().save(dbVoucher);
        } else {
            dbVoucher.setData(Mapper.INSTANCE.writeValue(voucher));
            getSession().update(dbVoucher);
        }
        // save the voucher
        // todo: need to do TO0 manually
        // write the guid response
        byte[] guidResponse = guid.toString().getBytes(StandardCharsets.UTF_8);
        getResponse().setContentLength(guidResponse.length);
        getResponse().getOutputStream().write(guidResponse);
    } catch (Exception e) {
        logger.warn("Request failed because of internal server error.");
        getResponse().setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
Also used : ECPrivateKey(org.bouncycastle.asn1.sec.ECPrivateKey) RSAPrivateKey(org.bouncycastle.asn1.pkcs.RSAPrivateKey) PrivateKey(java.security.PrivateKey) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) PEMParser(org.bouncycastle.openssl.PEMParser) CryptoService(org.fidoalliance.fdo.protocol.dispatch.CryptoService) StringReader(java.io.StringReader) UUID(java.util.UUID) OwnerKeySupplier(org.fidoalliance.fdo.protocol.dispatch.OwnerKeySupplier) KeyFactory(java.security.KeyFactory) ECPrivateKey(org.bouncycastle.asn1.sec.ECPrivateKey) OwnershipVoucherHeader(org.fidoalliance.fdo.protocol.message.OwnershipVoucherHeader) OnboardingVoucher(org.fidoalliance.fdo.protocol.entity.OnboardingVoucher) OwnerPublicKey(org.fidoalliance.fdo.protocol.message.OwnerPublicKey) Date(java.util.Date) SignatureException(java.security.SignatureException) PemObject(org.bouncycastle.util.io.pem.PemObject) KeyResolver(org.fidoalliance.fdo.protocol.KeyResolver) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) PemObject(org.bouncycastle.util.io.pem.PemObject) OwnershipVoucher(org.fidoalliance.fdo.protocol.message.OwnershipVoucher) AlgorithmFinder(org.fidoalliance.fdo.protocol.AlgorithmFinder) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) Certificate(java.security.cert.Certificate)

Aggregations

AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)249 IOException (java.io.IOException)144 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)140 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)75 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)71 BigInteger (java.math.BigInteger)60 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)55 X500Name (org.bouncycastle.asn1.x500.X500Name)50 X509Certificate (java.security.cert.X509Certificate)44 Date (java.util.Date)43 ContentSigner (org.bouncycastle.operator.ContentSigner)39 DEROctetString (org.bouncycastle.asn1.DEROctetString)38 OutputStream (java.io.OutputStream)37 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)36 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)34 PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)33 BcRSAContentSignerBuilder (org.bouncycastle.operator.bc.BcRSAContentSignerBuilder)33 DefaultDigestAlgorithmIdentifierFinder (org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder)31 DefaultSignatureAlgorithmIdentifierFinder (org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder)31 DEROctetString (com.github.zhenwei.core.asn1.DEROctetString)28