Search in sources :

Example 46 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project Falcon-File-Transfer-Optimizer by arif-zaman.

the class MyProxy method get.

/**
 * Retrieves delegated credentials from the MyProxy server.
 *
 * @param  credential
 *         The local GSI credentials to use for authentication.
 *         Can be set to null if no local credentials.
 * @param  params
 *         The parameters for the get operation.
 * @return GSSCredential
 *         The retrieved delegated credentials.
 * @exception MyProxyException
 *         If an error occurred during the operation.
 */
public GSSCredential get(GSSCredential credential, GetParams params) throws MyProxyException {
    if (params == null) {
        throw new IllegalArgumentException("params == null");
    }
    if (credential == null) {
        try {
            credential = getAnonymousCredential();
        } catch (GSSException e) {
            throw new MyProxyException("Failed to create anonymous credentials", e);
        }
    }
    String msg = params.makeRequest();
    Socket gsiSocket = null;
    OutputStream out = null;
    InputStream in = null;
    try {
        gsiSocket = getSocket(credential);
        if (credential.getName().isAnonymous()) {
            this.context.requestAnonymity(true);
        }
        out = gsiSocket.getOutputStream();
        in = gsiSocket.getInputStream();
        if (!((GssSocket) gsiSocket).getContext().getConfState())
            throw new Exception("Confidentiality requested but not available");
        // send message
        out.write(msg.getBytes());
        out.flush();
        if (logger.isDebugEnabled()) {
            logger.debug("Req sent:" + params);
        }
        // may require authz handshake
        handleReply(in, out, params.getAuthzCreds(), params.getWantTrustroots());
        // start delegation - generate key pair
        KeyPair keyPair = CertificateUtil.generateKeyPair("RSA", DEFAULT_KEYBITS);
        // According to the MyProxy protocol, the MyProxy server
        // will ignore the subject in the client's certificate
        // signing request (CSR). However, in some cases it is
        // helpful to control the CSR subject (for example, when
        // the MyProxy server is using a CA back-end that can only
        // issue certificates with subjects matching the request).
        // So we construct the CSR subject using the given MyProxy
        // username (if possible).
        String CSRsubjectString = params.getUserName();
        CSRsubjectString = CSRsubjectString.trim();
        if (CSRsubjectString.contains("CN=") || CSRsubjectString.contains("cn=")) {
            // If the MyProxy username is a DN, use it.
            if (CSRsubjectString.charAt(0) == '/') {
                // "good enough" conversion of OpenSSL DN strings
                CSRsubjectString = CSRsubjectString.substring(1);
                CSRsubjectString = CSRsubjectString.replace('/', ',');
            }
        } else {
            CSRsubjectString = "CN=" + CSRsubjectString;
        }
        X509Name CSRsubjectName;
        try {
            CSRsubjectName = new X509Name(CSRsubjectString);
        } catch (Exception e) {
            // If our X509Name construction fails for any reason,
            // just use a default value (as in the past).
            CSRsubjectName = new X509Name("CN=ignore");
        }
        if (logger.isDebugEnabled()) {
            logger.debug("CSR subject: " + CSRsubjectName.toString());
        }
        BouncyCastleCertProcessingFactory certFactory = BouncyCastleCertProcessingFactory.getDefault();
        byte[] req = null;
        req = certFactory.createCertificateRequest(CSRsubjectName, "SHA1WithRSAEncryption", keyPair);
        // send the request to server
        out.write(req);
        out.flush();
        // read the number of certificates
        int size = in.read();
        if (logger.isDebugEnabled()) {
            logger.debug("Reading " + size + " certs");
        }
        X509Certificate[] chain = new X509Certificate[size];
        for (int i = 0; i < size; i++) {
            chain[i] = certFactory.loadCertificate(in);
            // DEBUG: display the cert names
            if (logger.isDebugEnabled()) {
                logger.debug("Received cert: " + chain[i].getSubjectDN());
            }
        }
        // get the response
        handleReply(in);
        // make sure the private key belongs to the right public key
        // currently only works with RSA keys
        RSAPublicKey pkey = (RSAPublicKey) chain[0].getPublicKey();
        RSAPrivateKey prkey = (RSAPrivateKey) keyPair.getPrivate();
        if (!pkey.getModulus().equals(prkey.getModulus())) {
            throw new MyProxyException("Private/Public key mismatch!");
        }
        X509Credential newCredential = null;
        newCredential = new X509Credential(keyPair.getPrivate(), chain);
        return new GlobusGSSCredentialImpl(newCredential, GSSCredential.INITIATE_AND_ACCEPT);
    } catch (Exception e) {
        throw new MyProxyException("MyProxy get failed.", e);
    } finally {
        // close socket
        close(out, in, gsiSocket);
    }
}
Also used : GlobusGSSCredentialImpl(org.globus.gsi.gssapi.GlobusGSSCredentialImpl) GssSocket(org.globus.gsi.gssapi.net.GssSocket) KeyPair(java.security.KeyPair) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) DataOutputStream(java.io.DataOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) GeneralSecurityException(java.security.GeneralSecurityException) GSSException(org.ietf.jgss.GSSException) EOFException(java.io.EOFException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) X509Certificate(java.security.cert.X509Certificate) X509Name(org.bouncycastle.asn1.x509.X509Name) X509Credential(org.globus.gsi.X509Credential) GSSException(org.ietf.jgss.GSSException) RSAPublicKey(java.security.interfaces.RSAPublicKey) BouncyCastleCertProcessingFactory(org.globus.gsi.bc.BouncyCastleCertProcessingFactory) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) SSLSocket(javax.net.ssl.SSLSocket) GssSocket(org.globus.gsi.gssapi.net.GssSocket) Socket(java.net.Socket)

Example 47 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project Falcon-File-Transfer-Optimizer by arif-zaman.

the class BouncyCastleCertProcessingFactory method createCertificateRequest.

/**
 * Creates a certificate request from the specified certificate and a key pair. The certificate's subject
 * DN with <I>"CN=proxy"</I> name component appended to the subject is used as the subject of the
 * certificate request. Also the certificate's signing algorithm is used as the certificate request
 * signing algorithm.
 *
 * @param cert
 *            the certificate to create the certificate request from.
 * @param keyPair
 *            the key pair of the certificate request
 * @return the certificate request.
 * @exception GeneralSecurityException
 *                if security error occurs.
 */
public byte[] createCertificateRequest(X509Certificate cert, KeyPair keyPair) throws GeneralSecurityException {
    String issuer = cert.getSubjectDN().getName();
    X509Name subjectDN = new X509Name(issuer + ",CN=proxy");
    String sigAlgName = cert.getSigAlgName();
    return createCertificateRequest(subjectDN, sigAlgName, keyPair);
}
Also used : X509Name(org.bouncycastle.asn1.x509.X509Name) DERBitString(org.bouncycastle.asn1.DERBitString)

Example 48 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project Falcon-File-Transfer-Optimizer by arif-zaman.

the class BouncyCastleUtil method getIdentity.

/**
 * Returns the subject DN of the given certificate in the Globus format.
 *
 * @param cert the certificate to get the subject of. The certificate
 *             must be of <code>X509CertificateObject</code> type.
 * @return the subject DN of the certificate in the Globus format.
 */
public static String getIdentity(X509Certificate cert) {
    if (cert == null) {
        return null;
    }
    String subjectDN = cert.getSubjectX500Principal().getName(X500Principal.RFC2253);
    X509Name name = new X509Name(true, subjectDN);
    return X509NameHelper.toString(name);
}
Also used : X509Name(org.bouncycastle.asn1.x509.X509Name) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1String(org.bouncycastle.asn1.ASN1String)

Example 49 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project Falcon-File-Transfer-Optimizer by arif-zaman.

the class BouncyCastleUtil method getCertificateType.

/**
 * Returns the certificate type of the given certificate.
 * Please see {@link #getCertificateType(TBSCertificateStructure,
 * TrustedCertificates) getCertificateType} for details for
 * determining the certificate type.
 *
 * @param cert the certificate to get the type of.
 * @param trustedCerts the trusted certificates to double check the
 *                     {@link GSIConstants#EEC GSIConstants.EEC}
 *                     certificate against.
 * @return the certificate type as determined by
 *             {@link #getCertificateType(TBSCertificateStructure,
 *              TrustedCertificates) getCertificateType}.
 * @exception CertificateException if something goes wrong.
 */
public static GSIConstants.CertificateType getCertificateType(X509Certificate cert, CertStore trustedCerts) throws CertificateException {
    try {
        TBSCertificateStructure crt = getTBSCertificateStructure(cert);
        GSIConstants.CertificateType type = getCertificateType(crt);
        // to make sure the cert is not a ca cert
        if (type == GSIConstants.CertificateType.EEC) {
            X509CertSelector selector = new X509CertSelector();
            selector.setSubject(cert.getSubjectX500Principal());
            Collection c = trustedCerts.getCertificates(selector);
            if (c != null && c.size() > 0) {
                type = GSIConstants.CertificateType.CA;
            }
        }
        return type;
    } catch (Exception e) {
        // but this should not happen
        throw new CertificateException("", e);
    }
}
Also used : GSIConstants(org.globus.gsi.GSIConstants) TBSCertificateStructure(org.bouncycastle.asn1.x509.TBSCertificateStructure) Collection(java.util.Collection) X509CertSelector(java.security.cert.X509CertSelector) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) InvalidNameException(javax.naming.InvalidNameException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 50 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project bitbreeds-webrtc by IIlllII.

the class CertUtil method getCertFingerPrint.

/**
 * @param alias alias
 * @param pass password
 * @param storePath path to keystore
 * @return sha-256 string based on cert in keystore
 */
public static String getCertFingerPrint(String storePath, String alias, String pass) {
    try {
        Certificate cert = DTLSUtils.loadCert(storePath, alias, pass);
        byte[] der = cert.getEncoded();
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] dat = md.digest(der);
        String fingerprint = createFingerprintString(dat);
        logger.info("Local cert signature is {} ", fingerprint);
        return fingerprint;
    } catch (Exception e) {
        logger.error("Failed to create cert fingerprint from {}", storePath, e);
        throw new IllegalStateException("Loading certificate failed");
    }
}
Also used : MessageDigest(java.security.MessageDigest) Certificate(org.bouncycastle.asn1.x509.Certificate)

Aggregations

IOException (java.io.IOException)242 X509Certificate (java.security.cert.X509Certificate)216 Date (java.util.Date)133 X500Name (org.bouncycastle.asn1.x500.X500Name)133 BigInteger (java.math.BigInteger)120 ContentSigner (org.bouncycastle.operator.ContentSigner)102 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)101 GeneralName (org.bouncycastle.asn1.x509.GeneralName)100 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)96 CertificateException (java.security.cert.CertificateException)95 ArrayList (java.util.ArrayList)90 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)85 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)82 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)78 GeneralSecurityException (java.security.GeneralSecurityException)69 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)62 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)62 Extension (org.bouncycastle.asn1.x509.Extension)61 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)60 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)59