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:org.cryptoworkshop.ximix.common.asn1.message.TranscriptTransferMessage.java

License:Apache License

@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(new ASN1Integer(stepNo));

    if (chunk != null) {
        v.add(new DEROctetString(chunk));
    }//from w  w w . java  2 s .co  m

    return new DERSequence(v);
}

From source file:org.cryptoworkshop.ximix.node.crypto.key.message.BLSCommittedSecretShareMessage.java

License:Apache License

@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(new ASN1Integer(index));
    v.add(new ASN1Integer(value));
    v.add(new ASN1Integer(witness));

    ASN1EncodableVector factV = new ASN1EncodableVector();
    for (int i = 0; i != commitmentFactors.length; i++) {
        factV.add(new DEROctetString(commitmentFactors[i].toBytes()));
    }// w ww  .  ja  v a  2s . c  o m

    v.add(new DERSequence(factV));
    v.add(new DEROctetString(pK.toBytes()));

    return new DERSequence(v);
}

From source file:org.cryptoworkshop.ximix.node.crypto.key.message.ECCommittedSecretShareMessage.java

License:Apache License

@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(new ASN1Integer(index));
    v.add(new ASN1Integer(value));
    v.add(new ASN1Integer(witness));

    ASN1EncodableVector factV = new ASN1EncodableVector();
    for (int i = 0; i != commitmentFactors.length; i++) {
        factV.add(new DEROctetString(commitmentFactors[i].getEncoded()));
    }// w  w w. ja  v a  2s. com

    v.add(new DERSequence(factV));
    v.add(new DEROctetString(q.getEncoded()));

    ASN1EncodableVector qFactV = new ASN1EncodableVector();
    for (int i = 0; i != qCommitmentFactors.length; i++) {
        qFactV.add(new DEROctetString(qCommitmentFactors[i].getEncoded()));
    }

    v.add(new DERSequence(qFactV));

    return new DERSequence(v);
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.attribute.impl.MessageDigest.java

License:Open Source License

@Override
public Attribute getValue() {
    try {// ww  w.j  av  a2 s . co m
        if (this.hash == null) {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance(signaturePolicy.getSignPolicyHashAlg().getAlgorithm().getValue());
            this.hash = md.digest(content);
        }
        return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DEROctetString(this.hash)));
    } catch (NoSuchAlgorithmException ex) {
        logger.info(ex.getMessage());
        return null;
    }

}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.attribute.impl.RevocationRefs.java

License:Open Source License

/**
 * //from   ww  w .jav a2 s . co  m
 * 
 * @param extract
 *            CrlValidatedID from X509CRL
 * @return a CrlValidatedID
 * @throws NoSuchAlgorithmException
 * @throws CRLException
 */

private CrlValidatedID makeCrlValidatedID(X509CRL crl) throws NoSuchAlgorithmException, CRLException {

    Digest digest = DigestFactory.getInstance().factoryDefault();
    digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);

    OtherHashAlgAndValue otherHashAlgAndValue = new OtherHashAlgAndValue(
            new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256),
            new DEROctetString(digest.digest(crl.getEncoded())));

    OtherHash hash = new OtherHash(otherHashAlgAndValue);

    BigInteger crlnumber;
    CrlIdentifier crlid;
    if (crl.getExtensionValue("2.5.29.20") != null) {
        ASN1Integer varASN1Integer = new ASN1Integer(crl.getExtensionValue("2.5.29.20"));
        crlnumber = varASN1Integer.getPositiveValue();

        crlid = new CrlIdentifier(new X500Name(crl.getIssuerX500Principal().getName()),
                new DERUTCTime(crl.getThisUpdate()), crlnumber);
    } else {
        crlid = new CrlIdentifier(new X500Name(crl.getIssuerX500Principal().getName()),
                new DERUTCTime(crl.getThisUpdate()));
    }

    CrlValidatedID crlvid = new CrlValidatedID(hash, crlid);

    return crlvid;
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.DemoiselleSignedAttributeTableGenerator.java

License:Open Source License

/**
 * Create a standard attribute table from the passed in parameters - this will
 * normally include contentType, signingTime, and messageDigest. If the constructor
 * using an AttributeTable was used, entries in it for contentType, signingTime, and
 * messageDigest will override the generated ones.
 *
 * @param parameters source parameters for table generation.
 *
 * @return a filled in Hashtable of attributes.
 *///from ww  w .j  a va2  s.  c  o  m
protected Hashtable createStandardAttributeTable(Map parameters) {
    Hashtable std = copyHashTable(table);

    if (!std.containsKey(CMSAttributes.contentType)) {
        ASN1ObjectIdentifier contentType = ASN1ObjectIdentifier
                .getInstance(parameters.get(CMSAttributeTableGenerator.CONTENT_TYPE));

        // contentType will be null if we're trying to generate a counter signature.
        if (contentType != null) {
            Attribute attr = new Attribute(CMSAttributes.contentType, new DERSet(contentType));
            std.put(attr.getAttrType(), attr);
        }
    }

    if (!std.containsKey(CMSAttributes.messageDigest)) {
        byte[] messageDigest = (byte[]) parameters.get(CMSAttributeTableGenerator.DIGEST);
        Attribute attr = new Attribute(CMSAttributes.messageDigest,
                new DERSet(new DEROctetString(messageDigest)));
        std.put(attr.getAttrType(), attr);
    }

    return std;
}

From source file:org.deviceconnect.android.ssl.EndPointKeyStoreManager.java

License:MIT License

/**
 * ??????./*  ww w.ja va2  s . co m*/
 *
 * @param keyPair 
 * @param commonName ?
 * @param generalNames SANs
 * @return ????
 * @throws GeneralSecurityException ?????
 */
private static PKCS10CertificationRequest createCSR(final KeyPair keyPair, final String commonName,
        final GeneralNames generalNames) throws GeneralSecurityException {
    final String signatureAlgorithm = "SHA256WithRSAEncryption";
    final X500Principal principal = new X500Principal(
            "CN=" + commonName + ", O=Device Connect Project, L=N/A, ST=N/A, C=JP");
    DERSequence sanExtension = new DERSequence(
            new ASN1Encodable[] { X509Extensions.SubjectAlternativeName, new DEROctetString(generalNames) });
    DERSet extensions = new DERSet(new DERSequence(sanExtension));
    DERSequence extensionRequest = new DERSequence(
            new ASN1Encodable[] { PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensions });
    DERSet attributes = new DERSet(extensionRequest);
    return new PKCS10CertificationRequest(signatureAlgorithm, principal, keyPair.getPublic(), attributes,
            keyPair.getPrivate());
}

From source file:org.ebayopensource.fido.uaf.ops.AuthenticationResponseProcessing.java

License:Apache License

private boolean verifySignature(Tag signedData, Tag signature, String pubKey, AlgAndEncodingEnum algAndEncoding)
        throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException,
        UnsupportedEncodingException, Exception {

    byte[] dataForSigning = getDataForSigning(signedData);

    logger.info(" : pub          : " + pubKey);
    logger.info(" : dataForSigning : " + Base64.encodeBase64URLSafeString(dataForSigning));
    logger.info(" : signature       : " + Base64.encodeBase64URLSafeString(signature.value));

    // This works
    // return NamedCurve.verify(KeyCodec.getKeyAsRawBytes(pubKey),
    // dataForSigning, Asn1.decodeToBigIntegerArray(signature.value));

    byte[] decodeBase64 = Base64.decodeBase64(pubKey);
    if (algAndEncoding == AlgAndEncodingEnum.UAF_ALG_SIGN_RSASSA_PSS_SHA256_RAW) {
        PublicKey publicKey = KeyCodec.getRSAPublicKey(decodeBase64);
        return RSA.verifyPSS(publicKey, SHA.sha(dataForSigning, "SHA-256"), signature.value);
    } else if (algAndEncoding == AlgAndEncodingEnum.UAF_ALG_SIGN_RSASSA_PSS_SHA256_DER) {
        PublicKey publicKey = KeyCodec.getRSAPublicKey(new DEROctetString(decodeBase64).getOctets());
        return RSA.verifyPSS(publicKey, SHA.sha(dataForSigning, "SHA-256"),
                new DEROctetString(signature.value).getOctets());
    } else {//from w ww.  j  a v  a2  s .  co  m
        if (algAndEncoding == AlgAndEncodingEnum.UAF_ALG_SIGN_SECP256K1_ECDSA_SHA256_DER) {
            ECPublicKey decodedPub = (ECPublicKey) KeyCodec.getPubKeyFromCurve(decodeBase64, "secp256k1");
            return NamedCurve.verifyUsingSecp256k1(KeyCodec.getKeyAsRawBytes(decodedPub),
                    SHA.sha(dataForSigning, "SHA-256"), Asn1.decodeToBigIntegerArray(signature.value));
        }
        if (algAndEncoding == AlgAndEncodingEnum.UAF_ALG_SIGN_SECP256R1_ECDSA_SHA256_DER) {
            if (decodeBase64.length > 65) {
                return NamedCurve.verify(KeyCodec.getKeyAsRawBytes(pubKey), SHA.sha(dataForSigning, "SHA-256"),
                        Asn1.decodeToBigIntegerArray(signature.value));
            } else {
                ECPublicKey decodedPub = (ECPublicKey) KeyCodec.getPubKeyFromCurve(decodeBase64, "secp256r1");
                return NamedCurve.verify(KeyCodec.getKeyAsRawBytes(decodedPub),
                        SHA.sha(dataForSigning, "SHA-256"), Asn1.decodeToBigIntegerArray(signature.value));
            }
        }
        if (signature.value.length == 64) {
            ECPublicKey decodedPub = (ECPublicKey) KeyCodec.getPubKeyFromCurve(decodeBase64, "secp256r1");
            return NamedCurve.verify(KeyCodec.getKeyAsRawBytes(decodedPub), SHA.sha(dataForSigning, "SHA-256"),
                    Asn1.transformRawSignature(signature.value));
        } else if (65 == decodeBase64.length
                && AlgAndEncodingEnum.UAF_ALG_SIGN_SECP256R1_ECDSA_SHA256_DER == algAndEncoding) {
            ECPublicKey decodedPub = (ECPublicKey) KeyCodec.getPubKeyFromCurve(decodeBase64, "secp256r1");
            return NamedCurve.verify(KeyCodec.getKeyAsRawBytes(decodedPub), SHA.sha(dataForSigning, "SHA-256"),
                    Asn1.decodeToBigIntegerArray(signature.value));
        } else {
            return NamedCurve.verify(KeyCodec.getKeyAsRawBytes(pubKey), SHA.sha(dataForSigning, "SHA-256"),
                    Asn1.decodeToBigIntegerArray(signature.value));
        }
    }
}

From source file:org.ejbca.core.ejb.ca.sign.SignSessionTest.java

License:Open Source License

public void test29TestExtensionOverride() throws Exception {
    final String altnames = "dNSName=foo1.bar.com,dNSName=foo2.bar.com,dNSName=foo3.bar.com,dNSName=foo4.bar.com,dNSName=foo5.bar.com,dNSName=foo6.bar.com,dNSName=foo7.bar.com,dNSName=foo8.bar.com,dNSName=foo9.bar.com,dNSName=foo10.bar.com,dNSName=foo11.bar.com,dNSName=foo12.bar.com,dNSName=foo13.bar.com,dNSName=foo14.bar.com,dNSName=foo15.bar.com,dNSName=foo16.bar.com,dNSName=foo17.bar.com,dNSName=foo18.bar.com,dNSName=foo19.bar.com,dNSName=foo20.bar.com,dNSName=foo21.bar.com";
    // Create a good certificate profile (good enough), using QC statement
    certificateProfileSession.removeCertificateProfile(admin, "TESTEXTENSIONOVERRIDE");
    EndUserCertificateProfile certprof = new EndUserCertificateProfile();
    // Default profile does not allow Extension override
    certprof.setValidity(298);//  w  ww.  j  av a2  s. c o  m
    certificateProfileSession.addCertificateProfile(admin, "TESTEXTENSIONOVERRIDE", certprof);
    int cprofile = certificateProfileSession.getCertificateProfileId(admin, "TESTEXTENSIONOVERRIDE");

    // Create a good end entity profile (good enough), allowing multiple UPN
    // names
    endEntityProfileSession.removeEndEntityProfile(admin, "TESTEXTENSIONOVERRIDE");
    EndEntityProfile profile = new EndEntityProfile();
    profile.addField(DnComponents.COUNTRY);
    profile.addField(DnComponents.COMMONNAME);
    profile.setValue(EndEntityProfile.AVAILCAS, 0, Integer.toString(SecConst.ALLCAS));
    profile.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, Integer.toString(cprofile));
    endEntityProfileSession.addEndEntityProfile(admin, "TESTEXTENSIONOVERRIDE", profile);
    int eeprofile = endEntityProfileSession.getEndEntityProfileId(admin, "TESTEXTENSIONOVERRIDE");
    UserDataVO user = new UserDataVO("foo", "C=SE,CN=extoverride", rsacaid, null, "foo@anatom.nu",
            SecConst.USER_ENDUSER, eeprofile, cprofile, SecConst.TOKEN_SOFT_PEM, 0, null);
    user.setPassword("foo123");
    user.setStatus(UserDataConstants.STATUS_NEW);
    // Change a user that we know...
    userAdminSession.changeUser(admin, user, false);

    // Create a P10 with extensions, in this case altNames with a lot of DNS
    // names
    ASN1EncodableVector extensionattr = new ASN1EncodableVector();
    extensionattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    // AltNames
    // String[] namearray = altnames.split(",");
    GeneralNames san = CertTools.getGeneralNamesFromAltName(altnames);
    ByteArrayOutputStream extOut = new ByteArrayOutputStream();
    DEROutputStream derOut = new DEROutputStream(extOut);
    try {
        derOut.writeObject(san);
    } catch (IOException e) {
        throw new IllegalArgumentException("error encoding value: " + e);
    }
    // Extension request attribute is a set of X509Extensions
    // ASN1EncodableVector x509extensions = new ASN1EncodableVector();
    // An X509Extensions is a sequence of Extension which is a sequence of
    // {oid, X509Extension}
    // ASN1EncodableVector extvalue = new ASN1EncodableVector();
    Vector<DERObjectIdentifier> oidvec = new Vector<DERObjectIdentifier>();
    oidvec.add(X509Extensions.SubjectAlternativeName);
    Vector<X509Extension> valuevec = new Vector<X509Extension>();
    valuevec.add(new X509Extension(false, new DEROctetString(extOut.toByteArray())));
    X509Extensions exts = new X509Extensions(oidvec, valuevec);
    extensionattr.add(new DERSet(exts));
    // Complete the Attribute section of the request, the set (Attributes)
    // contains one sequence (Attribute)
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new DERSequence(extensionattr));
    DERSet attributes = new DERSet(v);
    // Create PKCS#10 certificate request
    PKCS10CertificationRequest req = new PKCS10CertificationRequest("SHA1WithRSA",
            new X509Name("C=SE,CN=extoverride"), rsakeys.getPublic(), attributes, rsakeys.getPrivate());
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req);
    dOut.close();
    byte[] p10bytes = bOut.toByteArray();
    // FileOutputStream fos = new FileOutputStream("/tmp/foo.der");
    // fos.write(p10bytes);
    // fos.close();
    PKCS10RequestMessage p10 = new PKCS10RequestMessage(p10bytes);
    p10.setUsername("foo");
    p10.setPassword("foo123");
    // See if the request message works...
    X509Extensions p10exts = p10.getRequestExtensions();
    assertNotNull(p10exts);
    IResponseMessage resp = signSession.createCertificate(admin, p10,
            org.ejbca.core.protocol.X509ResponseMessage.class, null);
    X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage());
    assertNotNull("Failed to create certificate", cert);
    assertEquals("CN=extoverride,C=SE", cert.getSubjectDN().getName());
    // check altNames, should be none
    Collection c = cert.getSubjectAlternativeNames();
    assertNull(c);

    // Change so that we allow override of validity time
    CertificateProfile prof = certificateProfileSession.getCertificateProfile(admin, cprofile);
    prof.setAllowExtensionOverride(true);
    certificateProfileSession.changeCertificateProfile(admin, "TESTEXTENSIONOVERRIDE", prof);

    userAdminSession.changeUser(admin, user, false);
    resp = signSession.createCertificate(admin, p10, org.ejbca.core.protocol.X509ResponseMessage.class, null);
    cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage());
    assertNotNull("Failed to create certificate", cert);
    assertEquals("CN=extoverride,C=SE", cert.getSubjectDN().getName());
    // check altNames, should be one altName
    c = cert.getSubjectAlternativeNames();
    assertNotNull(c);
    assertEquals(21, c.size());
    String retAltNames = CertTools.getSubjectAlternativeName(cert);
    List<String> originalNames = Arrays.asList(altnames.split(","));
    List<String> returnNames = Arrays.asList(retAltNames.split(", "));
    assertTrue(originalNames.containsAll(returnNames));
}

From source file:org.ejbca.core.model.ca.certextensions.BasicCertificateExtension.java

License:Open Source License

private DEREncodable parseDEROctetString(String value) throws CertificateExtentionConfigurationException {
    DEREncodable retval = null;/*w w w . j a v a  2  s .co m*/
    if (value.matches("^\\p{XDigit}*")) {
        byte[] bytes = Hex.decode(value);
        retval = new DEROctetString(bytes);
    } else {
        throw new CertificateExtentionConfigurationException(intres
                .getLocalizedMessage("certext.basic.illegalvalue", value, Integer.valueOf(getId()), getOID()));
    }
    return retval;
}