Example usage for org.bouncycastle.asn1 DEROctetString DEROctetString

List of usage examples for org.bouncycastle.asn1 DEROctetString DEROctetString

Introduction

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

Prototype

public DEROctetString(ASN1Encodable obj) throws IOException 

Source Link

Document

Constructor from the encoding of an ASN.1 object.

Usage

From source file:net.sourceforge.javacardsign.iso7816_15.PrivateKeyAttributes.java

License:Open Source License

public DERObject getDERObject() {
    DERInteger idType = new DERInteger(4);
    DEROctetString id = new DEROctetString(this.keyId);
    return new DERSequence(new ASN1Encodable[] { idType, id });
}

From source file:net.sourceforge.javacardsign.iso7816_15.RSAPrivateKeyAttributes.java

License:Open Source License

public DERObject getDERObject() {
    byte[] p = new byte[2];
    p[0] = (byte) (this.path >> 8 & 0xFF);
    p[1] = (byte) (this.path & 0xFF);
    DERSequence path = new DERSequence(new ASN1Encodable[] { new DEROctetString(p) });
    DERInteger modSize = new DERInteger(this.modSize);
    return new DERSequence(new ASN1Encodable[] { path, modSize });
}

From source file:net.sourceforge.javacardsign.iso7816_15.X509CertificateAttributes.java

License:Open Source License

public DERObject getDERObject() {
    byte[] p = new byte[2];
    p[0] = (byte) (this.path >> 8 & 0xFF);
    p[1] = (byte) (this.path & 0xFF);
    DERSequence path = new DERSequence(new ASN1Encodable[] { new DEROctetString(p) });
    return new DERSequence(new ASN1Encodable[] { path });
}

From source file:net.wstech2.me.httpsclient.CertificateValidatorUtils.java

License:Apache License

/**
 * /*from ww w.j a  va 2  s .co  m*/
 * Inspected and display various informations from the Certificate passed as
 * parameter. Keys are presented in HEX values and ASN1 structures dumped
 * using ASN1Dump.dumpAsString.
 * 
 * This method is intended for debug purposes only.
 * 
 * 
 * @param cert
 *            The X509CertificateStructure to be inspected.
 * 
 */
public static void dumpCertificateInfo(org.bouncycastle.asn1.x509.Certificate cert) {
    boolean valid = false;
    TBSCertificate tbs = cert.getTBSCertificate();
    RSAEngine engine = new RSAEngine();
    SHA1Digest digest = new SHA1Digest();

    GenericSigner signer = new GenericSigner((engine), digest);
    RSAPublicKey signingKey;
    try {
        signingKey = RSAPublicKey.getInstance(cert.getSubjectPublicKeyInfo().parsePublicKey());

        HttpsConnectionUtils.logDebug("Public Key:[[" + cert.getSubjectPublicKeyInfo().parsePublicKey() + "]]");

        RSAKeyParameters keySpec = new RSAKeyParameters(false, signingKey.getModulus(),
                signingKey.getPublicExponent());
        signer.init(false, keySpec);
        HttpsConnectionUtils.logDebug("TBS DER object:[[" + tbs.getEncoded("DER") + "]]");

        signer.update(tbs.getEncoded(), 0, tbs.getEncoded().length);

        valid = signer.verifySignature(cert.getSignature().getBytes());

        HttpsConnectionUtils.logDebug("signer.verifySignature:[[" + valid + "]]");

        SHA1Digest d2 = new SHA1Digest();
        d2.update(tbs.getEncoded("DER"), 0, tbs.getEncoded("DER").length);
        byte[] hash = new byte[d2.getDigestSize()];
        d2.doFinal(hash, 0);
        HttpsConnectionUtils.logDebug("tbs.getDEREncoded() HASH:[[" + new String(Hex.encode(hash)) + "]]");
        DEROctetString asn1Hash = new DEROctetString(hash);
        HttpsConnectionUtils.logDebug(
                "ASN1 DEROctetString hash:[[" + new String(Hex.encode(asn1Hash.getEncoded("DER"))) + "]]");

        d2 = new SHA1Digest();
        d2.update(cert.getEncoded(), 0, cert.getEncoded().length);
        hash = new byte[d2.getDigestSize()];
        d2.doFinal(hash, 0);
        HttpsConnectionUtils.logDebug("cert.getEncoded() HASH:[[" + new String(Hex.encode(hash)) + "]]");

        byte[] signature = cert.getSignature().getBytes();
        HttpsConnectionUtils
                .logDebug("cert.getSignature().getBytes():[[" + new String(Hex.encode(signature)) + "]]");

        PKCS1Encoding engine2 = new PKCS1Encoding(new RSAEngine());
        engine2.init(false, keySpec);
        byte[] decryptedHash = engine2.processBlock(signature, 0, signature.length);
        HttpsConnectionUtils.logDebug("decryptedHash:[[" + new String(Hex.encode(decryptedHash)) + "]]");

        ASN1Object o = ASN1Primitive.fromByteArray(decryptedHash);
        HttpsConnectionUtils.logDebug(
                "decryptedHash.getDEREncoded():[[" + new String(Hex.encode(o.getEncoded("DER"))) + "]]");

        HttpsConnectionUtils.logDebug(
                "ASN1Dump.dumpAsString(decryptedHash,true):[[" + ASN1Dump.dumpAsString(o, true) + "]]");

        HttpsConnectionUtils.logDebug("engine.getInputBlockSize():[[" + engine2.getInputBlockSize() + "]]");

        HttpsConnectionUtils.logDebug("engine.getOutputBlockSize():[[" + engine2.getOutputBlockSize() + "]]");

        ASN1Sequence asn1SignSeq = (ASN1Sequence) ASN1Sequence.fromByteArray(decryptedHash);
        HttpsConnectionUtils
                .logDebug("Signature ASN1 Sequence:[[" + ASN1Dump.dumpAsString(asn1SignSeq, true) + "]]");

        AlgorithmIdentifier algorithm = AlgorithmIdentifier.getInstance(asn1SignSeq.getObjectAt(0));
        HttpsConnectionUtils.logDebug("AlgorithmIdentifier:[[" + ASN1Dump.dumpAsString(algorithm, true) + "]]");

        DEROctetString signedHash = (DEROctetString) DEROctetString.getInstance(asn1SignSeq.getObjectAt(1));
        HttpsConnectionUtils.logDebug("signedHash:[[" + ASN1Dump.dumpAsString(signedHash, true) + "]]");

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:nl.uva.vlet.grid.voms.VOMSAttributeCertificate.java

License:Apache License

public void setVOMSFQANs(String[] fqans) throws Exception {
    try {// w ww  .jav  a  2s .  c o m
        //--------------------------------------------------------------------------
        // put the FQANs into the SEQUENCE

        DEREncodableVector fqanVector = new ASN1EncodableVector();

        for (int f = 0; f < fqans.length; f++) {
            DERGeneralString fqan = new DERGeneralString(fqans[f]);
            ASN1OctetString fqanOctetString = ASN1OctetString.getInstance(new DEROctetString(fqan.getOctets()));
            fqanVector.add(fqanOctetString);
        }

        ASN1Sequence fqanSequence = ASN1Sequence.getInstance(new DERSequence(fqanVector));

        //--------------------------------------------------------------------------
        // put something into the undocumented TaggedObject

        DERGeneralString origin = new DERGeneralString("gridportal://newvoms:15000");

        ASN1OctetString originOctetString = ASN1OctetString.getInstance(new DEROctetString(origin.getOctets()));

        /*
         ASN1TaggedObject taggedObject2 = ASN1TaggedObject.getInstance( new DERTaggedObject( 6 , originOctetString ) , true ) ;
                
         ASN1TaggedObject taggedObject = ASN1TaggedObject.getInstance( new DERTaggedObject( 0 , taggedObject2 ) , true ) ;
                
         DEROctetString originOctetString = new DEROctetString( origin.getOctets() ) ;
         */

        DERTaggedObject taggedObject2 = new DERTaggedObject(6, originOctetString);

        DERTaggedObject taggedObject = new DERTaggedObject(0, taggedObject2);

        //--------------------------------------------------------------------------
        // put the taggedObject and then the fqanSequence into sequence2

        DEREncodableVector sequence2Vector = new ASN1EncodableVector();
        sequence2Vector.add(taggedObject);
        sequence2Vector.add(fqanSequence);
        ASN1Sequence sequence2 = ASN1Sequence.getInstance(new DERSequence(sequence2Vector));

        //--------------------------------------------------------------------------
        // the SET has one member - sequence2

        ASN1Set set = ASN1Set.getInstance(new DERSet(sequence2));

        //--------------------------------------------------------------------------
        // SEQUENCE sequence has an OID and the set

        DERObjectIdentifier voms4oid = new DERObjectIdentifier("1.3.6.1.4.1.8005.100.100.4");

        DEREncodableVector sequenceVector = new ASN1EncodableVector();
        sequenceVector.add(voms4oid);
        sequenceVector.add(set);
        ASN1Sequence sequence = ASN1Sequence.getInstance(new DERSequence(sequenceVector));

        //--------------------------------------------------------------------------

        this.attributes = ASN1Sequence.getInstance(new DERSequence(sequence));

    } catch (Exception e) {
        throw e;
    }

}

From source file:nl.uva.vlet.grid.voms.VOMSAttributeCertificate.java

License:Apache License

private void setExtensions() throws Exception {
    try {/* w w w .ja va 2  s .  c  o m*/
        Vector<DERObjectIdentifier> myOIDs = new Vector<DERObjectIdentifier>();
        Hashtable<DERObjectIdentifier, X509Extension> myExtensions = new Hashtable<DERObjectIdentifier, X509Extension>();

        //--------------------------------------------------------------------------
        // id-ce-noRevAvail

        ByteArrayOutputStream a = new ByteArrayOutputStream();
        new DEROutputStream(a).writeObject((new DERNull()).toASN1Object());
        ASN1OctetString nraOctetString = ASN1OctetString.getInstance(new DEROctetString(a.toByteArray()));

        X509Extension nraExtension = new X509Extension(new DERBoolean(false), nraOctetString);
        DERObjectIdentifier nraOID = new DERObjectIdentifier("2.5.29.56");

        myOIDs.add(nraOID);
        myExtensions.put(nraOID, nraExtension);

        //--------------------------------------------------------------------------
        // AuthorityKeyIdentifier
        //            myLogger.warn("VOMSAttributeCertificate verification not implemented yet.");

        //      String issuerDN = this.getIssuer() ;
        //
        //      String serverName = "unknown" ;
        //      //serverName = VirtualOrganisation.getServer( issuerDN ) ;
        //
        //      if( ! serverName.equals( "unknown" ) )
        //      {
        //        String vomsServerCredentialLocation = new String( System.getProperty( "user.home" ) + "/gridsecurity/certificates/voms-server-certificates/" + serverName ) ;
        //
        //        X509Certificate vomsServerCredential = CertUtil.loadCertificate( vomsServerCredentialLocation ) ;
        //
        //        PublicKey pk = vomsServerCredential.getPublicKey() ;
        //
        //        SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream( new ByteArrayInputStream( pk.getEncoded() ) ).readObject() ) ;
        //        AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier( spki ) ;
        //
        //        // not clear why this does not work...
        //        // DEROctetString akiOctetString = (DEROctetString) DEROctetString.getInstance( akiSequence.getDERObject() ) ;
        //
        //        // These three lines get to the desired result...
        //        ByteArrayOutputStream b = new ByteArrayOutputStream() ;
        //        new DEROutputStream( b ).writeObject( aki.toASN1Object() ) ; 
        //        ASN1OctetString akiOctetString = ASN1OctetString.getInstance( new DEROctetString( b.toByteArray() ) ) ;
        //
        //        X509Extension akiExtension = new X509Extension( new DERBoolean( false ) , akiOctetString ) ;
        //        DERObjectIdentifier akiOID = new DERObjectIdentifier( "2.5.29.35" ) ;
        //
        //        myOIDs.add( akiOID ) ;
        //        myExtensions.put( akiOID , akiExtension ) ;
        //
        //        this.extensions = new X509Extensions( myOIDs , myExtensions ) ;
        //
        //      }

    } catch (Exception e) {
        //            myLogger.error(null, e);
        //e.printStackTrace() ; 
    }

}

From source file:no.difi.oxalis.as2.util.SMimeBC.java

License:EUPL

public static byte[] createSignature(byte[] digest, SMimeDigestMethod digestMethod, PrivateKey privateKey,
        X509Certificate certificate) throws OxalisSecurityException {
    try {//w w w  .j  a v a2 s. c o  m
        ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
        signedAttributes.add(new Attribute(CMSAttributes.contentType, new DERSet(digestMethod.getOid())));
        signedAttributes
                .add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(digest))));
        signedAttributes.add(new Attribute(CMSAttributes.signingTime, new DERSet(new DERUTCTime(new Date()))));

        AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
        signedAttributesTable.toASN1EncodableVector();
        DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
                signedAttributesTable);

        /* Build the SignerInfo generator builder, that will build the generator... that will generate the SignerInformation... */
        SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                        .build());
        signerInfoBuilder.setSignedAttributeGenerator(signedAttributeGenerator);
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        JcaContentSignerBuilder contentSigner = new JcaContentSignerBuilder(digestMethod.getMethod())
                .setProvider(BouncyCastleProvider.PROVIDER_NAME);

        generator.addSignerInfoGenerator(signerInfoBuilder.build(contentSigner.build(privateKey),
                new X509CertificateHolder(certificate.getEncoded())));
        generator.addCertificates(new JcaCertStore(Collections.singletonList(certificate)));

        return generator.generate(new CMSAbsentContent()).getEncoded();
    } catch (CMSException | IOException | CertificateEncodingException | OperatorCreationException e) {
        throw new OxalisSecurityException(e.getMessage(), e);
    }
}

From source file:no.difi.sdp.client.internal.CreateCMSDocument.java

License:Apache License

private AlgorithmIdentifier rsaesOaepIdentifier() {
    AlgorithmIdentifier hash = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, DERNull.INSTANCE);
    AlgorithmIdentifier mask = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, hash);
    AlgorithmIdentifier p_source = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_pSpecified,
            new DEROctetString(new byte[0]));
    ASN1Encodable parameters = new RSAESOAEPparams(hash, mask, p_source);
    return new AlgorithmIdentifier(PKCSObjectIdentifiers.id_RSAES_OAEP, parameters);
}

From source file:org.apache.ace.authentication.processor.clientcert.MemoryKeyStore.java

License:Apache License

private X509Certificate generateRootCertificate(String commonName, Date notBefore, Date notAfter)
        throws Exception {
    X500Name issuer = new X500Name(commonName);
    BigInteger serial = BigInteger.probablePrime(16, new Random());

    SubjectPublicKeyInfo pubKeyInfo = convertToSubjectPublicKeyInfo(m_caKey.getPublic());

    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer,
            pubKeyInfo);/*  w  w  w  . j a v  a 2s  . c o m*/
    builder.addExtension(
            new Extension(Extension.basicConstraints, true, new DEROctetString(new BasicConstraints(true))));

    X509CertificateHolder certHolder = builder
            .build(new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(m_caKey.getPrivate()));
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}

From source file:org.apache.felix.deploymentadmin.itest.util.CertificateUtil.java

License:Apache License

private static X509Certificate createSelfSignedCert(String commonName, KeyPair keypair) throws Exception {
    PublicKey publicKey = keypair.getPublic();
    String keyAlg = DPSigner.getSignatureAlgorithm(publicKey);

    X500Name issuer = new X500Name(commonName);
    BigInteger serial = BigInteger.probablePrime(16, new Random());
    Date notBefore = new Date(System.currentTimeMillis() - 1000);
    Date notAfter = new Date(notBefore.getTime() + 6000);

    SubjectPublicKeyInfo pubKeyInfo;//from www.  j  ava 2 s . co  m
    try (ASN1InputStream is = new ASN1InputStream(publicKey.getEncoded())) {
        pubKeyInfo = SubjectPublicKeyInfo.getInstance(is.readObject());
    }

    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer,
            pubKeyInfo);
    builder.addExtension(
            new Extension(Extension.basicConstraints, true, new DEROctetString(new BasicConstraints(false))));

    X509CertificateHolder certHolder = builder
            .build(new JcaContentSignerBuilder(keyAlg).build(keypair.getPrivate()));
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}