Search in sources :

Example 61 with Sequence

use of com.google.showcase.v1beta1.Sequence in project jss by dogtagpki.

the class SignerInfo method verifyWithSignedAttributes.

/**
 * Verifies a SignerInfo with signed attributes.  If signed
 * attributes are present, then two particular attributes must
 * be present: <ul>
 * <li>PKCS #9 Content-Type, the type of content that is being signed.
 *      This must match the contentType parameter.
 * <li>PKCS #9 Message-Digest, the digest of the content that is being
 *      signed. This must match the messageDigest parameter.
 * </ul>
 * After these two attributes are verified to be both present and correct,
 * the encryptedDigest field of the SignerInfo is verified to be the
 * signature of the contents octets of the DER encoding of the
 * signedAttributes field.
 */
private void verifyWithSignedAttributes(byte[] messageDigest, OBJECT_IDENTIFIER contentType, PublicKey pubkey) throws NotInitializedException, NoSuchAlgorithmException, InvalidKeyException, TokenException, SignatureException {
    int numAttrib = signedAttributes.size();
    if (numAttrib < 2) {
        throw new SignatureException("At least two signed attributes must be present:" + " content-type and message-digest");
    }
    // go through the signed attributes, verifying the
    // interesting ones
    boolean foundContentType = false;
    boolean foundMessageDigest = false;
    for (int i = 0; i < numAttrib; i++) {
        if (!(signedAttributes.elementAt(i) instanceof Attribute)) {
            throw new SignatureException("Element of signedAttributes is not an Attribute");
        }
        Attribute attrib = (Attribute) signedAttributes.elementAt(i);
        if (attrib.getType().equals(CONTENT_TYPE)) {
            // content-type.  Compare with what was passed in.
            SET vals = attrib.getValues();
            if (vals.size() != 1) {
                throw new SignatureException("Content-Type attribute " + " does not have exactly one value");
            }
            ASN1Value val = vals.elementAt(0);
            OBJECT_IDENTIFIER ctype;
            try {
                if (val instanceof OBJECT_IDENTIFIER) {
                    ctype = (OBJECT_IDENTIFIER) val;
                } else if (val instanceof ANY) {
                    ctype = (OBJECT_IDENTIFIER) ((ANY) val).decodeWith(OBJECT_IDENTIFIER.getTemplate());
                } else {
                    // what the heck is it? not what it's supposed to be
                    throw new InvalidBERException("Content-Type signed attribute has unexpected" + " content type");
                }
            } catch (InvalidBERException e) {
                throw new SignatureException("Content-Type signed attribute does not have " + "OBJECT IDENTIFIER value");
            }
            // contentType parameter
            if (!ctype.equals(contentType)) {
                throw new SignatureException("Content-type in signed attributes does not " + "match content-type being verified");
            }
            // content type is A-OK
            foundContentType = true;
        } else if (attrib.getType().equals(MESSAGE_DIGEST)) {
            SET vals = attrib.getValues();
            if (vals.size() != 1) {
                throw new SignatureException("Message-digest attribute does not have" + " exactly one value");
            }
            ASN1Value val = vals.elementAt(0);
            byte[] mdigest;
            try {
                if (val instanceof OCTET_STRING) {
                    mdigest = ((OCTET_STRING) val).toByteArray();
                } else if (val instanceof ANY) {
                    OCTET_STRING os;
                    os = (OCTET_STRING) ((ANY) val).decodeWith(OCTET_STRING.getTemplate());
                    mdigest = os.toByteArray();
                } else {
                    // what the heck is it? not what it's supposed to be
                    throw new InvalidBERException("Content-Type signed attribute has unexpected" + " content type");
                }
            } catch (InvalidBERException e) {
                throw new SignatureException("Message-digest attribute does not" + " have OCTET STRING value");
            }
            // message digest being verified
            if (!byteArraysAreSame(mdigest, messageDigest)) {
                throw new SignatureException("Message-digest attribute does not" + " match message digest being verified");
            }
            // message digest is A-OK
            foundMessageDigest = true;
        }
    // we don't care about other attributes
    }
    if (!foundContentType) {
        throw new SignatureException("Signed attributes does not contain" + " PKCS #9 content-type attribute");
    }
    if (!foundMessageDigest) {
        throw new SignatureException("Signed attributes does not contain" + " PKCS #9 message-digest attribute");
    }
    SignatureAlgorithm sigAlg = SignatureAlgorithm.fromOID(digestEncryptionAlgorithm.getOID());
    // All the signed attributes are present and correct.
    // Now verify the signature.
    CryptoToken token = CryptoManager.getInstance().getInternalCryptoToken();
    Signature sig;
    // verify the contents octets of the DER encoded signed attribs
    byte[] encoding = ASN1Util.encode(signedAttributes);
    byte[] toBeVerified;
    if (sigAlg.getRawAlg() == SignatureAlgorithm.RSASignature) {
        // create DigestInfo structure
        SEQUENCE digestInfo = createDigestInfo(encoding, true);
        toBeVerified = ASN1Util.encode(digestInfo);
        sig = token.getSignatureContext(SignatureAlgorithm.RSASignature);
    } else {
        toBeVerified = encoding;
        sig = token.getSignatureContext(sigAlg);
    }
    sig.initVerify(pubkey);
    sig.update(toBeVerified);
    if (!sig.verify(encryptedDigest.toByteArray())) {
        // signature is invalid
        throw new SignatureException("encryptedDigest was not the correct" + " signature of the contents octets of the DER-encoded" + " signed attributes");
    }
// SUCCESSFULLY VERIFIED
}
Also used : SET(org.mozilla.jss.asn1.SET) CryptoToken(org.mozilla.jss.crypto.CryptoToken) Attribute(org.mozilla.jss.pkix.primitive.Attribute) OBJECT_IDENTIFIER(org.mozilla.jss.asn1.OBJECT_IDENTIFIER) SignatureAlgorithm(org.mozilla.jss.crypto.SignatureAlgorithm) SignatureException(java.security.SignatureException) ANY(org.mozilla.jss.asn1.ANY) InvalidBERException(org.mozilla.jss.asn1.InvalidBERException) ASN1Value(org.mozilla.jss.asn1.ASN1Value) OCTET_STRING(org.mozilla.jss.asn1.OCTET_STRING) Signature(org.mozilla.jss.crypto.Signature) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE)

Example 62 with Sequence

use of com.google.showcase.v1beta1.Sequence in project jss by dogtagpki.

the class CertReqMsg method main.

public static void main(String[] args) {
    try {
        if (args.length < 1) {
            System.err.println("Give an arg");
            System.exit(0);
        }
        SEQUENCE.OF_Template seqt = new SEQUENCE.OF_Template(new CertReqMsg.Template());
        SEQUENCE seq = null;
        byte[] bytes;
        try (FileInputStream fis = new FileInputStream(args[0])) {
            bytes = new byte[fis.available()];
            fis.read(bytes);
        }
        for (int i = 0; i < 1; i++) {
            seq = (SEQUENCE) seqt.decode(new ByteArrayInputStream(bytes));
        }
        System.out.println("Decoded " + seq.size() + " messages");
        CertReqMsg reqmsg = (CertReqMsg) seq.elementAt(0);
        CertRequest certreq = reqmsg.getCertReq();
        System.out.println("Request ID: " + certreq.getCertReqId());
        CertTemplate temp = certreq.getCertTemplate();
        if (temp.hasVersion()) {
            System.out.println("Version: " + temp.getVersion());
        } else {
            System.out.println("No version");
        }
        if (temp.hasSerialNumber()) {
            System.out.println("Serial Number: " + temp.getSerialNumber());
        } else {
            System.out.println("No serial number");
        }
        if (temp.hasSigningAlg()) {
            System.out.println("SigningAlg: " + temp.getSigningAlg().getOID());
        } else {
            System.out.println("No signing alg");
        }
        if (temp.hasIssuer()) {
            System.out.println("Issuer: " + temp.getIssuer().getRFC1485());
        } else {
            System.out.println("No issuer");
        }
        if (temp.hasSubject()) {
            System.out.println("Subject: " + temp.getSubject().getRFC1485());
        } else {
            System.out.println("No subject: ");
        }
        if (temp.hasPublicKey()) {
            System.out.println("Public Key: " + temp.getPublicKey().getAlgorithmIdentifier().getOID());
        } else {
            System.out.println("No public key");
        }
        if (temp.hasIssuerUID()) {
            System.out.println("Issuer UID: " + new BigInteger(1, temp.getIssuerUID().getBits()));
        } else {
            System.out.println("no issuer uid");
        }
        if (temp.hasSubjectUID()) {
            System.out.println("Subject UID: " + new BigInteger(1, temp.getIssuerUID().getBits()));
        } else {
            System.out.println("no subject uid");
        }
        if (temp.hasNotBefore()) {
            System.out.println("Not Before: " + DateFormat.getInstance().format(temp.getNotBefore()));
        }
        if (temp.hasNotAfter()) {
            System.out.println("Not After: " + DateFormat.getInstance().format(temp.getNotAfter()));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : FileInputStream(java.io.FileInputStream) InvalidBERException(org.mozilla.jss.asn1.InvalidBERException) InvalidKeyFormatException(org.mozilla.jss.crypto.InvalidKeyFormatException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) TokenException(org.mozilla.jss.crypto.TokenException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ByteArrayInputStream(java.io.ByteArrayInputStream) SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) BigInteger(java.math.BigInteger)

Example 63 with Sequence

use of com.google.showcase.v1beta1.Sequence in project jss by dogtagpki.

the class PKIStatusInfo method encode.

@Override
public void encode(Tag implicitTag, OutputStream ostream) throws IOException {
    SEQUENCE seq = new SEQUENCE();
    seq.addElement(status);
    if (statusString.size() > 0) {
        seq.addElement(statusString);
    }
    if (hasFailInfo) {
        // convert failInfo to BIT_STRING
        byte[] bytes = new byte[2];
        bytes[0] = (byte) ((failInfo & 0xff000000) >>> 24);
        bytes[1] = (byte) ((failInfo & 0x00ff0000) >>> 16);
        // 7 unused bits
        int padCount = 7;
        BIT_STRING bs = new BIT_STRING(bytes, padCount);
        bs.setRemoveTrailingZeroes(true);
        seq.addElement(bs);
    }
    seq.encode(implicitTag, ostream);
}
Also used : SEQUENCE(org.mozilla.jss.asn1.SEQUENCE) BIT_STRING(org.mozilla.jss.asn1.BIT_STRING)

Example 64 with Sequence

use of com.google.showcase.v1beta1.Sequence in project kramerius by ceskaexpedice.

the class IiifAPI method manifest.

@GET
@Path("{pid}/manifest")
@Produces({ MediaType.APPLICATION_JSON + ";charset=utf-8" })
public Response manifest(@PathParam("pid") String pid) {
    checkPid(pid);
    try {
        DocumentDto document = getIiifDocument(pid);
        PropertyValue titleLabel = new PropertyValueSimpleImpl(document.getTitle());
        Manifest manifest = new ManifestImpl(UriBuilder.fromUri(iiifUri).path(getClass(), "manifest").build(pid), titleLabel);
        List<String> fieldList = new ArrayList<String>();
        List<Canvas> canvases = new ArrayList<Canvas>();
        List<String> children = ItemResourceUtils.solrChildrenPids(pid, fieldList, solrAccess, solrMemoization);
        Map<String, Pair<Integer, Integer>> resolutions = getResolutions(children);
        for (String p : children) {
            String repPid = p.replace("/", "");
            if (repPid.equals(pid)) {
                continue;
            }
            DocumentDto page = getIiifDocument(repPid);
            if (!"page".equals(page.getModel()))
                continue;
            String id = ApplicationURL.applicationURL(this.requestProvider.get()) + "/canvas/" + repPid;
            Pair<Integer, Integer> resolution = resolutions.get(p);
            if (resolution != null) {
                Canvas canvas = new CanvasImpl(id, new PropertyValueSimpleImpl(page.getTitle()), resolution.getLeft(), resolution.getRight());
                ImageResource resource = new ImageResourceImpl();
                String resourceId = ApplicationURL.applicationURL(this.requestProvider.get()).toString() + "/iiif/" + repPid + "/full/full/0/default.jpg";
                resource.setType("dctypes:Image");
                resource.setId(resourceId);
                resource.setHeight(resolution.getLeft());
                resource.setWidth(resolution.getRight());
                resource.setFormat("image/jpeg");
                Service service = new ServiceImpl();
                service.setContext("http://iiif.io/api/image/2/context.json");
                service.setId(ApplicationURL.applicationURL(this.requestProvider.get()).toString() + "/iiif/" + repPid);
                service.setProfile("http://iiif.io/api/image/2/level1.json");
                resource.setService(service);
                Image image = new ImageImpl();
                image.setOn(new URI(id));
                image.setResource(resource);
                canvas.setImages(Collections.singletonList(image));
                canvases.add(canvas);
            }
        }
        // no pages - 500 ?
        if (canvases.isEmpty()) {
            throw new GenericApplicationException("cannot create manifest for pid '" + pid + "'");
        }
        Sequence sequence = new SequenceImpl();
        sequence.setCanvases(canvases);
        manifest.setSequences(Collections.singletonList(sequence));
        return Response.ok().entity(toJSON(manifest)).build();
    } catch (IOException e) {
        throw new GenericApplicationException(e.getMessage());
    } catch (URISyntaxException e) {
        throw new GenericApplicationException(e.getMessage());
    } catch (InterruptedException e) {
        throw new GenericApplicationException(e.getMessage());
    }
}
Also used : ArrayList(java.util.ArrayList) ManifestImpl(de.digitalcollections.iiif.presentation.model.impl.v2.ManifestImpl) SequenceImpl(de.digitalcollections.iiif.presentation.model.impl.v2.SequenceImpl) URISyntaxException(java.net.URISyntaxException) Image(de.digitalcollections.iiif.presentation.model.api.v2.Image) GenericApplicationException(cz.incad.kramerius.rest.api.exceptions.GenericApplicationException) URI(java.net.URI) ImageResourceImpl(de.digitalcollections.iiif.presentation.model.impl.v2.ImageResourceImpl) ImageResource(de.digitalcollections.iiif.presentation.model.api.v2.ImageResource) Pair(org.apache.commons.lang3.tuple.Pair) ServiceImpl(de.digitalcollections.iiif.presentation.model.impl.v2.ServiceImpl) Canvas(de.digitalcollections.iiif.presentation.model.api.v2.Canvas) PropertyValue(de.digitalcollections.iiif.presentation.model.api.v2.PropertyValue) Service(de.digitalcollections.iiif.presentation.model.api.v2.Service) Sequence(de.digitalcollections.iiif.presentation.model.api.v2.Sequence) IOException(java.io.IOException) Manifest(de.digitalcollections.iiif.presentation.model.api.v2.Manifest) ImageImpl(de.digitalcollections.iiif.presentation.model.impl.v2.ImageImpl) CanvasImpl(de.digitalcollections.iiif.presentation.model.impl.v2.CanvasImpl) PropertyValueSimpleImpl(de.digitalcollections.iiif.presentation.model.impl.v2.PropertyValueSimpleImpl) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

SEQUENCE (org.mozilla.jss.asn1.SEQUENCE)50 OCTET_STRING (org.mozilla.jss.asn1.OCTET_STRING)16 Sequence (org.sbolstandard.core2.Sequence)11 SET (org.mozilla.jss.asn1.SET)9 ANY (org.mozilla.jss.asn1.ANY)8 InvalidBERException (org.mozilla.jss.asn1.InvalidBERException)8 OBJECT_IDENTIFIER (org.mozilla.jss.asn1.OBJECT_IDENTIFIER)8 URI (java.net.URI)7 BMPString (org.mozilla.jss.asn1.BMPString)7 CryptoToken (org.mozilla.jss.crypto.CryptoToken)7 ASN1Value (org.mozilla.jss.asn1.ASN1Value)6 INTEGER (org.mozilla.jss.asn1.INTEGER)6 AuthenticatedSafes (org.mozilla.jss.pkcs12.AuthenticatedSafes)6 FileOutputStream (java.io.FileOutputStream)5 IOException (java.io.IOException)5 SignatureException (java.security.SignatureException)5 EXPLICIT (org.mozilla.jss.asn1.EXPLICIT)5 SafeBag (org.mozilla.jss.pkcs12.SafeBag)5 Certificate (org.mozilla.jss.pkix.cert.Certificate)5 ComponentDefinition (org.sbolstandard.core2.ComponentDefinition)5