Search in sources :

Example 11 with SubjectPublicKeyInfo

use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project Gene by Nervousync.

the class CertificateUtils method x509.

/**
 * Convert public key instance to X.509 certificate
 *
 * @param publicKey     Public key
 * @param serialNumber  Certificate serial number
 * @param beginDate     Certificate begin date
 * @param endDate       Certificate end date
 * @param certName      Certificate name
 * @param signKey       Certificate signer private key
 * @param signAlgorithm Signature algorithm
 * @return Generated X.509 certificate
 */
public static X509Certificate x509(PublicKey publicKey, long serialNumber, Date beginDate, Date endDate, String certName, PrivateKey signKey, String signAlgorithm) {
    if (publicKey == null || signKey == null || StringUtils.isEmpty(signAlgorithm)) {
        return null;
    }
    X500Name subjectDN = new X500Name("CN=" + certName);
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(subjectDN, BigInteger.valueOf(serialNumber), beginDate, endDate, subjectDN, publicKeyInfo);
    try {
        x509v3CertificateBuilder.addExtension(Extension.basicConstraints, Boolean.FALSE, new BasicConstraints(Boolean.FALSE));
        ContentSigner contentSigner = new JcaContentSignerBuilder(signAlgorithm).setProvider("BC").build(signKey);
        X509CertificateHolder certificateHolder = x509v3CertificateBuilder.build(contentSigner);
        return new JcaX509CertificateConverter().getCertificate(certificateHolder);
    } catch (OperatorCreationException | GeneralSecurityException | IOException e) {
        LOGGER.error("Generate PKCS12 Certificate Failed! ");
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Stack message: ", e);
        }
    }
    return null;
}
Also used : X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ContentSigner(org.bouncycastle.operator.ContentSigner) X500Name(org.bouncycastle.asn1.x500.X500Name) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 12 with SubjectPublicKeyInfo

use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project webauthn4j by webauthn4j.

the class TestAttestationUtil method createV1DummyCertificate.

public static X509Certificate createV1DummyCertificate() {
    try {
        X509v1CertificateBuilder certificateBuilder = new X509v1CertificateBuilder(new X500Name("O=SharpLab., C=US"), BigInteger.valueOf(1), Date.from(Instant.parse("2000-01-01T00:00:00Z")), Date.from(Instant.parse("2999-12-31T23:59:59Z")), new X500Name("O=SharpLab., C=US"), new SubjectPublicKeyInfo(new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256WITHRSA"), new byte[0]));
        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(RSAUtil.createKeyPair().getPrivate());
        X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner);
        try {
            return new JcaX509CertificateConverter().getCertificate(certificateHolder);
        } catch (CertificateException e) {
            throw new com.webauthn4j.validator.exception.CertificateException(e);
        }
    } catch (OperatorCreationException e) {
        throw new UnexpectedCheckedException(e);
    }
}
Also used : UnexpectedCheckedException(com.webauthn4j.util.exception.UnexpectedCheckedException) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) X509v1CertificateBuilder(org.bouncycastle.cert.X509v1CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Example 13 with SubjectPublicKeyInfo

use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project snowblossom by snowblossomcoin.

the class CertGen method generateSelfSignedCert.

/**
 * @param key_pair Key pair to use to sign the cert inner signed message, the node key
 * @param tls_wkp The temporary key to use just for this cert and TLS sessions
 * @param spec Address for 'key_pair'
 */
public static X509Certificate generateSelfSignedCert(WalletKeyPair key_pair, WalletKeyPair tls_wkp, AddressSpec spec) throws Exception {
    AddressSpecHash address_hash = AddressUtil.getHashForSpec(spec);
    String address = AddressUtil.getAddressString(Globals.NODE_ADDRESS_STRING, address_hash);
    byte[] encoded_pub = tls_wkp.getPublicKey().toByteArray();
    SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(encoded_pub));
    String dn = String.format("CN=%s, O=Snowblossom", address);
    X500Name issuer = new X500Name(dn);
    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
    Date notBefore = new Date(System.currentTimeMillis());
    Date notAfter = new Date(System.currentTimeMillis() + 86400000L * 365L * 10L);
    X500Name subject = issuer;
    X509v3CertificateBuilder cert_builder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, subjectPublicKeyInfo);
    // System.out.println(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName);
    ASN1ObjectIdentifier snow_claim_oid = new ASN1ObjectIdentifier("2.5.29.134");
    // System.out.println(spec);
    SignedMessagePayload payload = SignedMessagePayload.newBuilder().setTlsPublicKey(tls_wkp.getPublicKey()).build();
    SignedMessage sm = MsgSigUtil.signMessage(spec, key_pair, payload);
    byte[] sm_data = sm.toByteString().toByteArray();
    cert_builder.addExtension(snow_claim_oid, true, sm_data);
    String algorithm = "SHA256withRSA";
    AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(tls_wkp.getPrivateKey().toByteArray());
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    // ContentSigner sigGen = new BcECContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    X509CertificateHolder certificateHolder = cert_builder.build(sigGen);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
    return cert;
}
Also used : SignedMessagePayload(snowblossom.proto.SignedMessagePayload) SignedMessage(snowblossom.proto.SignedMessage) ContentSigner(org.bouncycastle.operator.ContentSigner) ByteString(com.google.protobuf.ByteString) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) AddressSpecHash(snowblossom.lib.AddressSpecHash) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 14 with SubjectPublicKeyInfo

use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project CipherTrust_Application_Protection by thalescpl-io.

the class ByokSample method readAWSPublicKeyFromFile.

private static byte[] readAWSPublicKeyFromFile(String publicKeyPath) throws Exception {
    File file = new File(publicKeyPath);
    FileInputStream ios = new FileInputStream(file);
    byte[] buffer = new byte[(int) file.length()];
    try {
        ios.read(buffer);
    } finally {
        ios.close();
    }
    // format conversion to PEM encoded PKCS#1 to allow import on to
    // keysecure
    X509EncodedKeySpec spec1 = new X509EncodedKeySpec(buffer);
    KeyFactory kf1 = KeyFactory.getInstance("RSA");
    RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);
    byte[] pubBytes = pubKey.getEncoded();
    SubjectPublicKeyInfo spkInfo = SubjectPublicKeyInfo.getInstance(pubBytes);
    ASN1Primitive primitive = spkInfo.parsePublicKey();
    if (primitive != null)
        return primitive.getEncoded();
    return null;
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) File(java.io.File) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) FileInputStream(java.io.FileInputStream) KeyFactory(java.security.KeyFactory)

Example 15 with SubjectPublicKeyInfo

use of com.android.apksig.internal.x509.SubjectPublicKeyInfo in project ca3sCore by kuehne-trustable-de.

the class CaCmpConnector method buildCertRequest.

/**
 * @param certReqId
 * @param csr
 * @param hmacSecret
 * @return PKIMessage
 * @throws GeneralSecurityException
 */
public PKIMessage buildCertRequest(long certReqId, final CSR csr, final String hmacSecret) throws GeneralSecurityException {
    // read the pem csr and verify the signature
    PKCS10CertificationRequest p10Req;
    try {
        p10Req = cryptoUtil.parseCertificateRequest(csr.getCsrBase64()).getP10Req();
    } catch (IOException e) {
        LOGGER.error("parsing csr", e);
        throw new GeneralSecurityException(e.getMessage());
    }
    List<RDN> rdnList = new ArrayList<>();
    for (de.trustable.ca3s.core.domain.RDN rdnDao : csr.getRdns()) {
        LOGGER.debug("rdnDao : " + rdnDao.getRdnAttributes());
        List<AttributeTypeAndValue> attrTVList = new ArrayList<AttributeTypeAndValue>();
        if (rdnDao != null && rdnDao.getRdnAttributes() != null) {
            for (RDNAttribute rdnAttr : rdnDao.getRdnAttributes()) {
                ASN1ObjectIdentifier aoi = new ASN1ObjectIdentifier(rdnAttr.getAttributeType());
                ASN1Encodable ae = new DERUTF8String(rdnAttr.getAttributeValue());
                AttributeTypeAndValue attrTV = new AttributeTypeAndValue(aoi, ae);
                attrTVList.add(attrTV);
            }
        }
        RDN rdn = new RDN(attrTVList.toArray(new AttributeTypeAndValue[attrTVList.size()]));
        LOGGER.debug("rdn : " + rdn.size() + " elements");
        rdnList.add(rdn);
    }
    X500Name subjectDN = new X500Name(rdnList.toArray(new RDN[rdnList.size()]));
    LOGGER.debug("subjectDN : " + subjectDN);
    Collection<Extension> certExtList = new ArrayList<>();
    // copy CSR attributes to Extension list
    for (Attribute attribute : p10Req.getAttributes()) {
        for (ASN1Encodable asn1Encodable : attribute.getAttributeValues()) {
            if (asn1Encodable != null) {
                try {
                    Extensions extensions = Extensions.getInstance(asn1Encodable);
                    for (ASN1ObjectIdentifier oid : extensions.getExtensionOIDs()) {
                        LOGGER.debug("copying oid '" + oid.toString() + "' from csr to PKIMessage");
                        certExtList.add(extensions.getExtension(oid));
                    }
                } catch (IllegalArgumentException iae) {
                    LOGGER.debug("processing asn1 value  '" + asn1Encodable + "' caused exception", iae);
                }
            }
        }
    }
    final SubjectPublicKeyInfo keyInfo = p10Req.getSubjectPublicKeyInfo();
    return cryptoUtil.buildCertRequest(certReqId, subjectDN, certExtList, keyInfo, hmacSecret);
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) RDNAttribute(de.trustable.ca3s.core.domain.RDNAttribute) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) RDNAttribute(de.trustable.ca3s.core.domain.RDNAttribute) CsrAttribute(de.trustable.ca3s.core.domain.CsrAttribute) Attribute(org.bouncycastle.asn1.pkcs.Attribute) GeneralSecurityException(java.security.GeneralSecurityException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) X500Name(org.bouncycastle.asn1.x500.X500Name) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) AttributeTypeAndValue(org.bouncycastle.asn1.x500.AttributeTypeAndValue) Extension(org.bouncycastle.asn1.x509.Extension) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) RDN(org.bouncycastle.asn1.x500.RDN) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)219 X500Name (org.bouncycastle.asn1.x500.X500Name)92 IOException (java.io.IOException)85 Date (java.util.Date)75 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)75 ContentSigner (org.bouncycastle.operator.ContentSigner)65 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)64 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)61 BigInteger (java.math.BigInteger)54 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)53 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)50 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)42 KeyPair (java.security.KeyPair)39 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)35 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)32 SubjectPublicKeyInfo (com.github.zhenwei.core.asn1.x509.SubjectPublicKeyInfo)30 KeyPairGenerator (java.security.KeyPairGenerator)30 PublicKey (java.security.PublicKey)30 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)30 InvalidKeyException (java.security.InvalidKeyException)28