Search in sources :

Example 66 with AlgorithmIdentifier

use of com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier in project airavata by apache.

the class X509SecurityContext method generateShortLivedCredential.

public KeyAndCertCredential generateShortLivedCredential(String userDN, String caCertPath, String caKeyPath, String caPwd) throws Exception {
    // 15 minutes
    final long CredentialGoodFromOffset = 1000L * 60L * 15L;
    // ago
    final long startTime = System.currentTimeMillis() - CredentialGoodFromOffset;
    final long endTime = startTime + 30 * 3600 * 1000;
    String keyLengthProp = "1024";
    int keyLength = Integer.parseInt(keyLengthProp);
    String signatureAlgorithm = "SHA1withRSA";
    KeyAndCertCredential caCred = getCACredential(caCertPath, caKeyPath, caPwd);
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(caCred.getKey().getAlgorithm());
    kpg.initialize(keyLength);
    KeyPair pair = kpg.generateKeyPair();
    X500Principal subjectDN = new X500Principal(userDN);
    Random rand = new Random();
    SubjectPublicKeyInfo publicKeyInfo;
    try {
        publicKeyInfo = SubjectPublicKeyInfo.getInstance(new ASN1InputStream(pair.getPublic().getEncoded()).readObject());
    } catch (IOException e) {
        throw new InvalidKeyException("Can not parse the public key" + "being included in the short lived certificate", e);
    }
    X500Name issuerX500Name = CertificateHelpers.toX500Name(caCred.getCertificate().getSubjectX500Principal());
    X500Name subjectX500Name = CertificateHelpers.toX500Name(subjectDN);
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerX500Name, new BigInteger(20, rand), new Date(startTime), new Date(endTime), subjectX500Name, publicKeyInfo);
    AlgorithmIdentifier sigAlgId = X509v3CertificateBuilder.extractAlgorithmId(caCred.getCertificate());
    X509Certificate certificate = certBuilder.build(caCred.getKey(), sigAlgId, signatureAlgorithm, null, null);
    certificate.checkValidity(new Date());
    certificate.verify(caCred.getCertificate().getPublicKey());
    KeyAndCertCredential result = new KeyAndCertCredential(pair.getPrivate(), new X509Certificate[] { certificate, caCred.getCertificate() });
    return result;
}
Also used : KeyPair(java.security.KeyPair) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) KeyPairGenerator(java.security.KeyPairGenerator) IOException(java.io.IOException) X500Name(org.bouncycastle.asn1.x500.X500Name) InvalidKeyException(java.security.InvalidKeyException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) Random(java.util.Random) X509v3CertificateBuilder(eu.emi.security.authn.x509.helpers.proxy.X509v3CertificateBuilder) KeyAndCertCredential(eu.emi.security.authn.x509.impl.KeyAndCertCredential) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger)

Example 67 with AlgorithmIdentifier

use of com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier in project airavata by apache.

the class MyProxyLogon method generateCertificationRequest.

private PKCS10CertificationRequest generateCertificationRequest(String dn, KeyPair kp) throws Exception {
    X500Name subject = new X500Name(dn);
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();
    AsymmetricKeyParameter pubkeyParam = PublicKeyFactory.createKey(pubKey.getEncoded());
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(pubkeyParam);
    PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(subject, publicKeyInfo);
    AlgorithmIdentifier signatureAi = new AlgorithmIdentifier(OIWObjectIdentifiers.sha1WithRSA);
    BcRSAContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(signatureAi, AlgorithmIdentifier.getInstance(OIWObjectIdentifiers.idSHA1));
    AsymmetricKeyParameter pkParam = PrivateKeyFactory.createKey(privKey.getEncoded());
    ContentSigner signer = signerBuilder.build(pkParam);
    return builder.build(signer);
}
Also used : BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) PrivateKey(java.security.PrivateKey) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) PublicKey(java.security.PublicKey) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 68 with AlgorithmIdentifier

use of com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier in project airavata by apache.

the class X509SecurityContext method generateShortLivedCredential.

public KeyAndCertCredential generateShortLivedCredential(String userDN, String caCertPath, String caKeyPath, String caPwd) throws Exception {
    // 15 minutes
    final long CredentialGoodFromOffset = 1000L * 60L * 15L;
    // ago
    final long startTime = System.currentTimeMillis() - CredentialGoodFromOffset;
    final long endTime = startTime + 30 * 3600 * 1000;
    String keyLengthProp = "1024";
    int keyLength = Integer.parseInt(keyLengthProp);
    String signatureAlgorithm = "SHA1withRSA";
    KeyAndCertCredential caCred = getCACredential(caCertPath, caKeyPath, caPwd);
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(caCred.getKey().getAlgorithm());
    kpg.initialize(keyLength);
    KeyPair pair = kpg.generateKeyPair();
    X500Principal subjectDN = new X500Principal(userDN);
    Random rand = new Random();
    SubjectPublicKeyInfo publicKeyInfo;
    try {
        publicKeyInfo = SubjectPublicKeyInfo.getInstance(new ASN1InputStream(pair.getPublic().getEncoded()).readObject());
    } catch (IOException e) {
        throw new InvalidKeyException("Can not parse the public key" + "being included in the short lived certificate", e);
    }
    X500Name issuerX500Name = CertificateHelpers.toX500Name(caCred.getCertificate().getSubjectX500Principal());
    X500Name subjectX500Name = CertificateHelpers.toX500Name(subjectDN);
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerX500Name, new BigInteger(20, rand), new Date(startTime), new Date(endTime), subjectX500Name, publicKeyInfo);
    AlgorithmIdentifier sigAlgId = X509v3CertificateBuilder.extractAlgorithmId(caCred.getCertificate());
    X509Certificate certificate = certBuilder.build(caCred.getKey(), sigAlgId, signatureAlgorithm, null, null);
    certificate.checkValidity(new Date());
    certificate.verify(caCred.getCertificate().getPublicKey());
    KeyAndCertCredential result = new KeyAndCertCredential(pair.getPrivate(), new X509Certificate[] { certificate, caCred.getCertificate() });
    return result;
}
Also used : KeyPair(java.security.KeyPair) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) KeyPairGenerator(java.security.KeyPairGenerator) IOException(java.io.IOException) X500Name(org.bouncycastle.asn1.x500.X500Name) InvalidKeyException(java.security.InvalidKeyException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) Random(java.util.Random) X509v3CertificateBuilder(eu.emi.security.authn.x509.helpers.proxy.X509v3CertificateBuilder) KeyAndCertCredential(eu.emi.security.authn.x509.impl.KeyAndCertCredential) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger)

Example 69 with AlgorithmIdentifier

use of com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier in project spring-cloud-digital-sign by SpringForAll.

the class ServerPKCSUtil method genCsr.

/**
 * genCsr
 *
 * @param alg0 alg
 * 密钥算法
 * @return
 */
public static String genCsr(String alg0) {
    if ("".equals(alg0)) {
        alg = alg0;
    }
    // 产生秘钥对
    KeyPairGenerator kpg = null;
    try {
        kpg = KeyPairGenerator.getInstance(alg);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    // 根据秘钥算法配置秘钥长度
    if ("SM2".equalsIgnoreCase(alg)) {
        kpg.initialize(256);
    } else {
        kpg.initialize(2048);
    }
    KeyPair kp = kpg.generateKeyPair();
    securityKP = kp;
    // 获取公钥以及公钥算法
    byte[] publickey = kp.getPublic().getEncoded();
    String pubAlg = kp.getPublic().getAlgorithm();
    String sAlg = null;
    try {
        sAlg = AlgorithmId.get(pubAlg).getOID().toString();
    } catch (NoSuchAlgorithmException e) {
    }
    SubjectPublicKeyInfo spki = null;
    // 区分SM2和RSA
    if (sAlg.equals("1.2.156.10197.1.301")) {
        spki = SubjectPublicKeyInfo.getInstance(publickey);
    } else {
        spki = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publickey));
    }
    String subject = "CN=defaultName";
    X500Name x500 = new X500Name(subject);
    // 产生csr构造器
    PKCS10CertificationRequestBuilder prb = new PKCS10CertificationRequestBuilder(x500, spki);
    // 构建签名信息
    ContentSigner signer = null;
    PrivateKey privateKey = kp.getPrivate();
    Signature sign = null;
    try {
        if (privateKey.getAlgorithm().equals("SM2")) {
            sign = Signature.getInstance("SM3withSM2");
        } else {
            sign = Signature.getInstance("SHA1withRSA");
        }
        sign.initSign(privateKey);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    final Signature sign1 = sign;
    signer = new ContentSigner() {

        ByteArrayOutputStream originStream = new ByteArrayOutputStream();

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

        public OutputStream getOutputStream() {
            return originStream;
        }

        public AlgorithmIdentifier getAlgorithmIdentifier() {
            try {
                return new AlgorithmIdentifier(AlgorithmId.get(sign1.getAlgorithm()).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) {
        e.printStackTrace();
    }
    return null;
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) 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 70 with AlgorithmIdentifier

use of com.github.zhenwei.core.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)

Aggregations

AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)249 IOException (java.io.IOException)157 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)140 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)79 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)72 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)65 BigInteger (java.math.BigInteger)62 X500Name (org.bouncycastle.asn1.x500.X500Name)52 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)47 Date (java.util.Date)47 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)45 X509Certificate (java.security.cert.X509Certificate)45 ContentSigner (org.bouncycastle.operator.ContentSigner)40 DEROctetString (com.github.zhenwei.core.asn1.DEROctetString)39 OutputStream (java.io.OutputStream)39 DERSequence (com.github.zhenwei.core.asn1.DERSequence)38 GeneralSecurityException (java.security.GeneralSecurityException)37 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)35 Cipher (javax.crypto.Cipher)33 PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)33