Example usage for org.bouncycastle.asn1 ASN1InputStream readObject

List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1InputStream readObject.

Prototype

public ASN1Primitive readObject() throws IOException 

Source Link

Usage

From source file:org.glite.security.delegation.GrDProxyGenerator.java

License:Apache License

/**
 * Creates a proxy certificate from a certificate request and a proxy
 * certificate/* w w w.j  a v  a2s  .  c o  m*/
 * 
 * @param inCertReq
 *            Certificate request
 * @param inProxy
 *            user proxy certificate 
 *            
 * @return chaine of certificate containing proxy in first place
 * @deprecated Use proxy generator from util-java
 */
public byte[] x509MakeProxyCert(byte[] inCertReq, byte[] inProxy) throws IOException, GeneralSecurityException {

    // Holds the cert chain loaded from the proxy file
    X509Certificate[] proxyCertChain = null;

    // Holds the priv key loaded from the proxy file
    PrivateKey proxyPrivKey = null;

    // Holds the final certificate chain of the proxy
    X509Certificate[] finalCertChain = null;

    // Load the proxy certificate chain
    proxyCertChain = GrDPX509Util
            .loadCertificateChain(new BufferedInputStream(new ByteArrayInputStream(inProxy)));

    // Check for null arguments
    if (inCertReq == null || inProxy == null) {
        throw new GeneralSecurityException(
                "Either the cert request or proxy cert were passed as null arguments." + " Cannot continue.");
    }

    // Check for a valid chain
    if (proxyCertChain.length <= 0) {
        throw new GeneralSecurityException(
                "Invalid number of certificates in proxy chain: " + proxyCertChain.length);
    }
    logger.debug("Number of certificates in proxy chain: " + proxyCertChain.length);

    // Reading private key form proxy file
    FileCertReader fileReader = new FileCertReader();
    KeyStore store = fileReader.readProxy(new BufferedInputStream(new ByteArrayInputStream(inProxy)),
            "keypair");
    proxyPrivKey = (PrivateKey) store.getKey("host", "keypair".toCharArray());

    // Load the certificate request
    InputStream inTCertReq = new ByteArrayInputStream(
            GrDPX509Util.readPEM(new ByteArrayInputStream(inCertReq), GrDPConstants.CRH, GrDPConstants.CRF));
    ASN1InputStream derin = new ASN1InputStream(inTCertReq);
    DERObject reqInfo = derin.readObject();
    PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((DERSequence) reqInfo);

    // Verify cert request validity
    if (!certReq.verify()) {
        throw new GeneralSecurityException("Certificate request verification failed!");
    }

    // Generating proxy certificate
    finalCertChain = new X509Certificate[proxyCertChain.length + 1];
    finalCertChain[0] = createProxyCertificate(proxyCertChain[0], proxyPrivKey, certReq.getPublicKey(),
            lifetime, proxyType, "proxy");

    for (int i = 0; i < proxyCertChain.length; ++i) {
        finalCertChain[i + 1] = proxyCertChain[i];
    }

    // TODO: this should be removed at some point
    certProxy = finalCertChain[0];

    return GrDPX509Util.certChainToByte(finalCertChain);
}

From source file:org.glite.security.delegation.GrDProxyGenerator.java

License:Apache License

/**
 * Creates a proxy certificate from a certificate request
 * /*from   w  ww .  ja  v a  2s.  c  o m*/
 * @param inCertReq
 *            Certificate request
 * @param inUserCert
 *            Issuer certificate
 * @param inUserKey
 *            Issuer privateKey
 * @param pwd
 *            Issuer password
 * @return chaine of certificate containing proxy in first place
 * @deprecated Use proxy generator from util-java
 */
public X509Certificate[] createProxyFromCertReq(InputStream inCertReq, BufferedInputStream inUserCert,
        InputStream inUserKey, String pwd1) throws GeneralSecurityException, IOException, Exception {

    X509Certificate[] userCert = null;
    PrivateKey userPrivKey = null;
    PKCS10CertificationRequest certRequest = null;
    X509Certificate[] proxyCert = null;

    // Load the user certificate
    userCert = GrDPX509Util.loadCertificateChain(inUserCert);
    logger.debug("User Certificate - number of certificates in chain: " + userCert.length);

    // Load the private key
    userPrivKey = PrivateKeyReader.read(new BufferedInputStream(inUserKey), pwd1);

    // Load the certificate request
    ASN1InputStream derin = new ASN1InputStream(
            new ByteArrayInputStream(GrDPX509Util.readPEM(inCertReq, GrDPConstants.CRH, GrDPConstants.CRF)));
    DERObject reqInfo = derin.readObject();
    certRequest = new PKCS10CertificationRequest((DERSequence) reqInfo);

    // Initialize the proxy certificate chain
    proxyCert = new X509Certificate[userCert.length + 1];

    // Verify integrity of certificate request
    if (!certRequest.verify()) {
        throw new GeneralSecurityException("Certificate request verification failed.");
    }

    // Create the proxy certificate
    proxyCert[0] = createProxyCertificate(userCert[0], userPrivKey, certRequest.getPublicKey(), lifetime,
            proxyType, "proxy");

    // Complete the proxy certificate chain
    for (int index = 1; index <= userCert.length; ++index)
        proxyCert[index] = userCert[index - 1];

    certProxy = proxyCert[0];

    return proxyCert;
}

From source file:org.glite.voms.ac.AttributeCertificate.java

License:eu-egee.org license

/**
 * Create an Attribute Certificate from a input stream containing
 * DER-encoded data//w w w  . ja  v  a 2  s. c  o m
 *
 * @param in
 * @return the Attribute Certificate
 * @throws IOException
 */
public static AttributeCertificate getInstance(InputStream in) throws IOException {
    ASN1InputStream dIn = new ASN1InputStream(in);
    ASN1Sequence seq = (ASN1Sequence) dIn.readObject();

    return new AttributeCertificate(seq);
}

From source file:org.glite.voms.contact.X509NameHelper.java

License:Apache License

public static ASN1Primitive toDERObject(byte[] data) throws IOException {
    ByteArrayInputStream inStream = new ByteArrayInputStream(data);
    ASN1InputStream derInputStream = new ASN1InputStream(inStream);
    return derInputStream.readObject();
}

From source file:org.globus.gridshib.security.x509.GlobusCredentialTest.java

License:Apache License

public void testGlobusCredential() throws Exception {

    // get the default signing credential:
    X509Credential credential = BootstrapConfigLoader.getCredentialDefault();

    // create the certificate extension:
    DERUTF8String derString = new DERUTF8String(TEST);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream derOut = new DEROutputStream(bOut);
    try {//  ww  w  .java  2 s  . co m
        derOut.writeObject(derString);
    } catch (IOException e) {
        String msg = "Unable to create certificate extension";
        logger.error(msg, e);
        fail(msg);
    }
    X509ExtensionSet extensions = new X509ExtensionSet();
    X509Extension extension = new X509Extension(OID, false, bOut.toByteArray());
    //X509Extension extension =
    //    new X509Extension(OID, false, TEST.getBytes());
    extensions.add(extension);

    // issue a proxy and bind the extension:
    X509Credential proxy = null;
    try {
        proxy = certFactory.createCredential(credential.getCertificateChain(),
                (PrivateKey) credential.getPrivateKey(), 512, DEFAULT_LIFETIME,
                GSIConstants.CertificateType.GSI_4_IMPERSONATION_PROXY, extensions, null);
    } catch (GeneralSecurityException e) {
        String msg = "Unable to create proxy credential";
        logger.error(msg, e);
        fail(msg);
    }

    // recover the extension content:
    X509Certificate cert = proxy.getCertificateChain()[0];
    byte[] bytes = null;
    try {
        bytes = BouncyCastleUtil.getExtensionValue(cert, OID);
    } catch (IOException e) {
        String msg = "Unable to get extension value";
        logger.error(msg, e);
        fail(msg);
    }
    ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(bytes));
    derString = null;
    try {
        derString = (DERUTF8String) in.readObject();
    } catch (IOException e) {
        String msg = "Cannot recover original extension value";
        logger.error(msg, e);
        fail(msg);
    }

    assertTrue("Extension values (\"" + TEST + "\" and \"" + derString.getString() + "\") do not match",
            TEST.equals(derString.getString()));
}

From source file:org.globus.gridshib.security.x509.SAMLX509Extension.java

License:Apache License

/**
 * Gets the certificate extension value from the given
 * certificate and attempts to parse it as a SAML assertion.
 * If the extension does not exist, this method returns
 * null./*from  ww  w.ja va2 s . c  om*/
 * <p>
 * This method first checks for a non-critical extension
 * at <code>OID</code>.  If the standard extension does
 * not exist, it then checks for a non-critical extension
 * at <code>LEGACY_OID</code>.  If the legacy extension
 * does not exist either, this method returns null.
 *
 * @param cert an X.509 certificate that may or may not
 *             contain an embedded SAML assertion
 * @return a SAML subject assertion (or null if the given
 *         certificate does not contain an embedded SAML
 *         assertion)
 *
 * @exception java.io.IOException
 *            If unable to decode the certificate extension
 * @exception org.globus.opensaml11.saml.SAMLException
 *            If unable to parse the SAML assertion
 *
 * @since 0.3.0
 */
public static SAMLSubjectAssertion getSAMLAssertion(X509Certificate cert) throws IOException, SAMLException {

    // get the DER-encoded extension value (OCTET STRING):
    byte[] bytes = getExtensionValue(cert);
    if (bytes == null) {
        String msg = "No standard SAML extension found in cert";
        logger.debug(msg);
        bytes = getLegacyExtensionValue(cert);
        if (bytes == null) {
            msg = "No legacy SAML extension found in cert";
            logger.debug(msg);
            return null;
        }
        SAMLSubjectAssertion assertion = new SAMLSubjectAssertion(new ByteArrayInputStream(bytes));
        msg = "Cert contains the following assertion: ";
        logger.debug(msg + assertion.toString());
        return assertion;
    }

    // The API in jce-jdk13-125.jar does not include constructor
    //
    // org.bouncycastle.asn1.ASN1InputStream(byte[] input);
    //
    // (although the API in jce-jdk13-131.jar does) so convert
    // the bytes to an InputStream.  This works in both versions
    // of the BouncyCastle provider.

    // get the DER-encoded UTF8 string from the octet string:
    ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(bytes));
    DERUTF8String derString = (DERUTF8String) in.readObject();

    // recover the unencoded string:
    String assertionStr = derString.getString();
    String msg = "Cert contains the following assertion: ";
    logger.debug(msg + assertionStr);

    bytes = assertionStr.getBytes();
    return new SAMLSubjectAssertion(new ByteArrayInputStream(bytes));
}

From source file:org.globus.gsi.bc.BouncyCastleCertProcessingFactory.java

License:Apache License

/**
 * Creates a proxy certificate from the certificate request. (Signs a certificate request creating a new
 * certificate)// w  w w. java 2  s .c  o  m
 *
 * @see #createProxyCertificate(X509Certificate, PrivateKey, PublicKey, int, int, X509ExtensionSet,
 *      String) createProxyCertificate
 * @param certRequestInputStream
 *            the input stream to read the certificate request from.
 * @param cert
 *            the issuer certificate
 * @param privateKey
 *            the private key to sign the new certificate with.
 * @param lifetime
 *            lifetime of the new certificate in seconds. If 0 (or less then) the new certificate will
 *            have the same lifetime as the issuing certificate.
 * @param delegationMode
 *            the type of proxy credential to create
 * @param extSet
 *            a set of X.509 extensions to be included in the new proxy certificate. Can be null. If
 *            delegation mode is {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY
 *            GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} or {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY
 *            GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY} then
 *            {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension ProxyCertInfoExtension} must be
 *            present in the extension set.
 * @param cnValue
 *            the value of the CN component of the subject of the new certificate. If null, the defaults
 *            will be used depending on the proxy certificate type created.
 * @return <code>X509Certificate</code> the new proxy certificate
 * @exception IOException
 *                if error reading the certificate request
 * @exception GeneralSecurityException
 *                if a security error occurs.
 * @deprecated
 */
public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert,
        PrivateKey privateKey, int lifetime, int delegationMode, X509ExtensionSet extSet, String cnValue)
        throws IOException, GeneralSecurityException {

    ASN1InputStream derin = new ASN1InputStream(certRequestInputStream);
    ASN1Primitive reqInfo = derin.readObject();
    PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((ASN1Sequence) reqInfo);

    boolean rs = certReq.verify();

    if (!rs) {
        String err = i18n.getMessage("certReqVerification");
        throw new GeneralSecurityException(err);
    }

    return createProxyCertificate(cert, privateKey, certReq.getPublicKey(), lifetime, delegationMode, extSet,
            cnValue);
}

From source file:org.globus.gsi.bc.BouncyCastleCertProcessingFactory.java

License:Apache License

/**
 * Creates a proxy certificate from the certificate request. (Signs a certificate request creating a new
 * certificate)/*  w  ww.  j av  a  2  s. c  o m*/
 *
 * @see #createProxyCertificate(X509Certificate, PrivateKey, PublicKey, int, int, X509ExtensionSet,
 *      String) createProxyCertificate
 * @param certRequestInputStream
 *            the input stream to read the certificate request from.
 * @param cert
 *            the issuer certificate
 * @param privateKey
 *            the private key to sign the new certificate with.
 * @param lifetime
 *            lifetime of the new certificate in seconds. If 0 (or less then) the new certificate will
 *            have the same lifetime as the issuing certificate.
 * @param certType
 *            the type of proxy credential to create
 * @param extSet
 *            a set of X.509 extensions to be included in the new proxy certificate. Can be null. If
 *            delegation mode is {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY
 *            GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} or {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY
 *            GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY} then
 *            {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension ProxyCertInfoExtension} must be
 *            present in the extension set.
 * @param cnValue
 *            the value of the CN component of the subject of the new certificate. If null, the defaults
 *            will be used depending on the proxy certificate type created.
 * @return <code>X509Certificate</code> the new proxy certificate
 * @exception IOException
 *                if error reading the certificate request
 * @exception GeneralSecurityException
 *                if a security error occurs.
 */
public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert,
        PrivateKey privateKey, int lifetime, GSIConstants.CertificateType certType, X509ExtensionSet extSet,
        String cnValue) throws IOException, GeneralSecurityException {

    ASN1InputStream derin = new ASN1InputStream(certRequestInputStream);
    ASN1Primitive reqInfo = derin.readObject();
    PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((ASN1Sequence) reqInfo);

    boolean rs = certReq.verify();

    if (!rs) {
        String err = i18n.getMessage("certReqVerification");
        throw new GeneralSecurityException(err);
    }

    return createProxyCertificate(cert, privateKey, certReq.getPublicKey(), lifetime, certType, extSet,
            cnValue);
}

From source file:org.globus.gsi.bc.BouncyCastleCertProcessingFactory.java

License:Apache License

/**
 * Loads a X509 certificate from the specified input stream. Input stream must contain DER-encoded
 * certificate./*from w  w w  .  j a  v a2  s  . co  m*/
 *
 * @param in
 *            the input stream to read the certificate from.
 * @return <code>X509Certificate</code> the loaded certificate.
 * @exception GeneralSecurityException
 *                if certificate failed to load.
 */
public X509Certificate loadCertificate(InputStream in) throws IOException, GeneralSecurityException {
    ASN1InputStream derin = new ASN1InputStream(in);
    ASN1Primitive certInfo = derin.readObject();
    ASN1Sequence seq = ASN1Sequence.getInstance(certInfo);
    return new X509CertificateObject(Certificate.getInstance(seq));
}

From source file:org.globus.gsi.bc.BouncyCastleOpenSSLKey.java

License:Apache License

protected PrivateKey getKey(String alg, byte[] data) throws GeneralSecurityException {
    if (alg.equals("RSA")) {
        try {//  w  w  w .  j av a  2s . c  o m
            if (data.length == 0) {
                throw new GeneralSecurityException("Cannot process empty byte stream.");
            }
            ByteArrayInputStream bis = new ByteArrayInputStream(data);
            ASN1InputStream derin = new ASN1InputStream(bis);
            ASN1Primitive keyInfo = derin.readObject();

            ASN1ObjectIdentifier rsaOid = PKCSObjectIdentifiers.rsaEncryption;
            AlgorithmIdentifier rsa = new AlgorithmIdentifier(rsaOid);
            PrivateKeyInfo pkeyinfo = new PrivateKeyInfo(rsa, keyInfo);
            ASN1Primitive derkey = pkeyinfo.toASN1Primitive();
            byte[] keyData = BouncyCastleUtil.toByteArray(derkey);
            // The DER object needs to be mangled to
            // create a proper ProvateKeyInfo object
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyData);
            KeyFactory kfac = KeyFactory.getInstance("RSA");

            return kfac.generatePrivate(spec);
        } catch (IOException e) {
            // that should never happen
            return null;
        }

    } else {
        return null;
    }
}