Search in sources :

Example 26 with AlgorithmIdentifier

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

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 27 with AlgorithmIdentifier

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

the class GenUtil method GenP10.

public static String GenP10(String userid, String subject, String alg) throws GenP10Exception {
    if (!"".equalsIgnoreCase(userid)) {
        if (keyMap.containsKey(userid)) {
            throw new GenP10Exception("用户唯一标识【" + userid + "】不能重复");
        }
    } else {
        throw new GenP10Exception("用户唯一标识不能为空");
    }
    KeyPairGenerator kpg = null;
    try {
        kpg = KeyPairGenerator.getInstance(alg);
    } catch (NoSuchAlgorithmException e1) {
        throw new GenP10Exception("输入秘钥对产生算法不正确:" + alg);
    }
    if ("SM2".equalsIgnoreCase(alg)) {
        kpg.initialize(256);
    } else {
        kpg.initialize(2048);
    }
    KeyPair kp = kpg.generateKeyPair();
    keyMap.put(userid, kp);
    byte[] publickey = kp.getPublic().getEncoded();
    final String pubAlg = kp.getPublic().getAlgorithm();
    String sAlg = null;
    try {
        sAlg = AlgorithmId.get(pubAlg).getOID().toString();
    } catch (NoSuchAlgorithmException e1) {
        throw new GenP10Exception("输入秘钥对产生算法不正确:" + sAlg);
    }
    SubjectPublicKeyInfo spki = null;
    if (sAlg.equals("1.2.156.10197.1.301")) {
        spki = SubjectPublicKeyInfo.getInstance(publickey);
    } else {
        spki = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publickey));
    }
    if ("".equals(subject)) {
        subject = "CN=defaultName";
    }
    X500Name x500 = new X500Name(subject);
    PKCS10CertificationRequestBuilder prb = new PKCS10CertificationRequestBuilder(x500, spki);
    ContentSigner signer = null;
    PrivateKey privateKey = kp.getPrivate();
    final Signature sign;
    try {
        if (privateKey.getAlgorithm().equals("SM2")) {
            sign = Signature.getInstance("SM3withSM2");
        } else {
            sign = Signature.getInstance("SHA1withRSA");
        }
        sign.initSign(privateKey);
    } catch (NoSuchAlgorithmException e) {
        throw new GenP10Exception("输入秘钥对产生算法不正确:SHA1withRSA");
    } catch (InvalidKeyException e) {
        throw new GenP10Exception("无效的私钥信息");
    }
    signer = new ContentSigner() {

        ByteArrayOutputStream originStream = new ByteArrayOutputStream();

        public byte[] getSignature() {
            try {
                sign.update(this.originStream.toByteArray());
                return sign.sign();
            } catch (SignatureException e) {
                throw new RuntimeException(e);
            }
        }

        public OutputStream getOutputStream() {
            return this.originStream;
        }

        public AlgorithmIdentifier getAlgorithmIdentifier() {
            try {
                return new AlgorithmIdentifier(AlgorithmId.get(pubAlg).getOID().toString());
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException(e);
            }
        }
    };
    PKCS10CertificationRequestHolder pr = prb.build(signer);
    try {
        return new String(Base64.encode(pr.getEncoded()));
    } catch (IOException e) {
        throw new GenP10Exception("产生CSR错误,请检查输入参数");
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) GenP10Exception(com.itrus.Exception.GenP10Exception) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) KeyPairGenerator(java.security.KeyPairGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X500Name(org.bouncycastle.asn1.x500.X500Name) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SignatureException(java.security.SignatureException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) PKCS10CertificationRequestHolder(org.bouncycastle.pkcs.PKCS10CertificationRequestHolder) Signature(java.security.Signature)

Example 28 with AlgorithmIdentifier

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

the class SAML2ClientConfiguration method createKeystore.

private void createKeystore() {
    try {
        if (CommonHelper.isBlank(this.keyStoreAlias)) {
            this.keyStoreAlias = getClass().getSimpleName();
            LOGGER.warn("Using keystore alias {}", this.keyStoreAlias);
        }
        if (CommonHelper.isBlank(this.keyStoreType)) {
            this.keyStoreType = KeyStore.getDefaultType();
            LOGGER.warn("Using keystore type {}", this.keyStoreType);
        }
        final KeyStore ks = KeyStore.getInstance(this.keyStoreType);
        final char[] password = this.keystorePassword.toCharArray();
        ks.load(null, password);
        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(2048);
        final KeyPair kp = kpg.genKeyPair();
        final String sigAlgName = "SHA1WithRSA";
        final AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
        final String dn = InetAddress.getLocalHost().getHostName();
        final PrivateKey signingKey = kp.getPrivate();
        final X509Certificate certificate = createSelfSignedCert(new X500Name("CN=" + dn), sigAlgName, sigAlgID, kp);
        final char[] keyPassword = this.privateKeyPassword.toCharArray();
        ks.setKeyEntry(this.keyStoreAlias, signingKey, keyPassword, new Certificate[] { certificate });
        try (final FileOutputStream fos = new FileOutputStream(this.keystoreResource.getFile().getCanonicalPath())) {
            ks.store(fos, password);
            fos.flush();
        }
        LOGGER.info("Created keystore {} with key alias {} ", keystoreResource.getFile().getCanonicalPath(), ks.aliases().nextElement());
    } catch (final Exception e) {
        throw new SAMLException("Could not create keystore", e);
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) FileOutputStream(java.io.FileOutputStream) KeyPairGenerator(java.security.KeyPairGenerator) DERBitString(org.bouncycastle.asn1.DERBitString) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyStore(java.security.KeyStore) SAMLException(org.pac4j.saml.exceptions.SAMLException) X509Certificate(java.security.cert.X509Certificate) TechnicalException(org.pac4j.core.exception.TechnicalException) MalformedURLException(java.net.MalformedURLException) SAMLException(org.pac4j.saml.exceptions.SAMLException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 29 with AlgorithmIdentifier

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

the class SAML2ClientConfiguration method createSelfSignedCert.

/**
 * Generate a self-signed certificate for dn using the provided signature algorithm and key pair.
 *
 * @param dn X.500 name to associate with certificate issuer/subject.
 * @param sigName name of the signature algorithm to use.
 * @param sigAlgID algorithm ID associated with the signature algorithm name.
 * @param keyPair the key pair to associate with the certificate.
 * @return an X509Certificate containing the public key in keyPair.
 * @throws Exception
 */
private X509Certificate createSelfSignedCert(X500Name dn, String sigName, AlgorithmIdentifier sigAlgID, KeyPair keyPair) throws Exception {
    V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
    certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
    certGen.setIssuer(dn);
    certGen.setSubject(dn);
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L)));
    final Calendar c = Calendar.getInstance();
    c.setTime(new Date());
    c.add(Calendar.YEAR, 1);
    certGen.setEndDate(new Time(c.getTime()));
    certGen.setSignature(sigAlgID);
    certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
    Signature sig = Signature.getInstance(sigName);
    sig.initSign(keyPair.getPrivate());
    sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));
    TBSCertificate tbsCert = certGen.generateTBSCertificate();
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(tbsCert);
    v.add(sigAlgID);
    v.add(new DERBitString(sig.sign()));
    X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
    // check the certificate - this will confirm the encoded sig algorithm ID is correct.
    cert.verify(keyPair.getPublic());
    return cert;
}
Also used : DERSequence(org.bouncycastle.asn1.DERSequence) ByteArrayInputStream(java.io.ByteArrayInputStream) Calendar(java.util.Calendar) Signature(java.security.Signature) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) V3TBSCertificateGenerator(org.bouncycastle.asn1.x509.V3TBSCertificateGenerator) Time(org.bouncycastle.asn1.x509.Time) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate)

Example 30 with AlgorithmIdentifier

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

the class PKCS10CertificationRequest method getPublicKey.

public PublicKey getPublicKey(String provider) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
    SubjectPublicKeyInfo subjectPKInfo = reqInfo.getSubjectPublicKeyInfo();
    try {
        X509EncodedKeySpec xspec = new X509EncodedKeySpec(new DERBitString(subjectPKInfo).getBytes());
        AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithmId();
        return KeyFactory.getInstance(keyAlg.getObjectId().getId(), provider).generatePublic(xspec);
    } catch (InvalidKeySpecException e) {
        throw new InvalidKeyException("error encoding public key");
    }
}
Also used : X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) SubjectPublicKeyInfo(org.gudy.bouncycastle.asn1.x509.SubjectPublicKeyInfo) AlgorithmIdentifier(org.gudy.bouncycastle.asn1.x509.AlgorithmIdentifier)

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