Search in sources :

Example 21 with IssuerAndSerialNumber

use of com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber in project LinLong-Java by zhenwei1108.

the class TimeStampToken method validate.

/**
 * Validate the time stamp token.
 * <p>
 * To be valid the token must be signed by the passed in certificate and the certificate must be
 * the one referred to by the SigningCertificate attribute included in the hashed attributes of
 * the token. The certificate must also have the ExtendedKeyUsageExtension with only
 * KeyPurposeId.id_kp_timeStamping and have been valid at the time the timestamp was created.
 * </p>
 * <p>
 * A successful call to validate means all the above are true.
 * </p>
 *
 * @param sigVerifier the content verifier create the objects required to verify the CMS object in
 *                    the timestamp.
 * @throws TSPException             if an exception occurs in processing the token.
 * @throws TSPValidationException   if the certificate or signature fail to be valid.
 * @throws IllegalArgumentException if the sigVerifierProvider has no associated certificate.
 */
public void validate(SignerInformationVerifier sigVerifier) throws TSPException, TSPValidationException {
    if (!sigVerifier.hasAssociatedCertificate()) {
        throw new IllegalArgumentException("verifier provider needs an associated certificate");
    }
    try {
        X509CertificateHolder certHolder = sigVerifier.getAssociatedCertificate();
        DigestCalculator calc = sigVerifier.getDigestCalculator(certID.getHashAlgorithm());
        OutputStream cOut = calc.getOutputStream();
        cOut.write(certHolder.getEncoded());
        cOut.close();
        if (!Arrays.constantTimeAreEqual(certID.getCertHash(), calc.getDigest())) {
            throw new TSPValidationException("certificate hash does not match certID hash.");
        }
        if (certID.getIssuerSerial() != null) {
            IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber(certHolder.toASN1Structure());
            if (!certID.getIssuerSerial().getSerial().equals(issuerSerial.getSerialNumber())) {
                throw new TSPValidationException("certificate serial number does not match certID for signature.");
            }
            GeneralName[] names = certID.getIssuerSerial().getIssuer().getNames();
            boolean found = false;
            for (int i = 0; i != names.length; i++) {
                if (names[i].getTagNo() == 4 && X500Name.getInstance(names[i].getName()).equals(X500Name.getInstance(issuerSerial.getName()))) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new TSPValidationException("certificate name does not match certID for signature. ");
            }
        }
        TSPUtil.validateCertificate(certHolder);
        if (!certHolder.isValidOn(tstInfo.getGenTime())) {
            throw new TSPValidationException("certificate not valid when time stamp created.");
        }
        if (!tsaSignerInfo.verify(sigVerifier)) {
            throw new TSPValidationException("signature not created by certificate.");
        }
    } catch (CMSException e) {
        if (e.getUnderlyingException() != null) {
            throw new TSPException(e.getMessage(), e.getUnderlyingException());
        } else {
            throw new TSPException("CMS exception: " + e, e);
        }
    } catch (IOException e) {
        throw new TSPException("problem processing certificate: " + e, e);
    } catch (OperatorCreationException e) {
        throw new TSPException("unable to create digest: " + e.getMessage(), e);
    }
}
Also used : IssuerAndSerialNumber(com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) DigestCalculator(com.github.zhenwei.pkix.operator.DigestCalculator) IOException(java.io.IOException) X509CertificateHolder(com.github.zhenwei.pkix.cert.X509CertificateHolder) GeneralName(com.github.zhenwei.core.asn1.x509.GeneralName) OperatorCreationException(com.github.zhenwei.pkix.operator.OperatorCreationException) CMSException(com.github.zhenwei.pkix.cms.CMSException)

Example 22 with IssuerAndSerialNumber

use of com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber in project LinLong-Java by zhenwei1108.

the class KeyAgreeRecipientInformation method getSenderPublicKeyInfo.

private SubjectPublicKeyInfo getSenderPublicKeyInfo(AlgorithmIdentifier recKeyAlgId, OriginatorIdentifierOrKey originator) throws CMSException, IOException {
    OriginatorPublicKey opk = originator.getOriginatorKey();
    if (opk != null) {
        return getPublicKeyInfoFromOriginatorPublicKey(recKeyAlgId, opk);
    }
    OriginatorId origID;
    IssuerAndSerialNumber iAndSN = originator.getIssuerAndSerialNumber();
    if (iAndSN != null) {
        origID = new OriginatorId(iAndSN.getName(), iAndSN.getSerialNumber().getValue());
    } else {
        SubjectKeyIdentifier ski = originator.getSubjectKeyIdentifier();
        origID = new OriginatorId(ski.getKeyIdentifier());
    }
    return getPublicKeyInfoFromOriginatorId(origID);
}
Also used : IssuerAndSerialNumber(com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber) SubjectKeyIdentifier(com.github.zhenwei.core.asn1.x509.SubjectKeyIdentifier) OriginatorPublicKey(com.github.zhenwei.pkix.util.asn1.cms.OriginatorPublicKey)

Example 23 with IssuerAndSerialNumber

use of com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber in project LinLong-Java by zhenwei1108.

the class KeyAgreeRecipientInformation method readRecipientInfo.

static void readRecipientInfo(List infos, KeyAgreeRecipientInfo info, AlgorithmIdentifier messageAlgorithm, CMSSecureReadable secureReadable, AuthAttributesProvider additionalData) {
    ASN1Sequence s = info.getRecipientEncryptedKeys();
    for (int i = 0; i < s.size(); ++i) {
        RecipientEncryptedKey id = RecipientEncryptedKey.getInstance(s.getObjectAt(i));
        RecipientId rid;
        KeyAgreeRecipientIdentifier karid = id.getIdentifier();
        IssuerAndSerialNumber iAndSN = karid.getIssuerAndSerialNumber();
        if (iAndSN != null) {
            rid = new KeyAgreeRecipientId(iAndSN.getName(), iAndSN.getSerialNumber().getValue());
        } else {
            RecipientKeyIdentifier rKeyID = karid.getRKeyID();
            // Note: 'date' and 'other' fields of RecipientKeyIdentifier appear to be only informational
            rid = new KeyAgreeRecipientId(rKeyID.getSubjectKeyIdentifier().getOctets());
        }
        infos.add(new KeyAgreeRecipientInformation(info, rid, id.getEncryptedKey(), messageAlgorithm, secureReadable, additionalData));
    }
}
Also used : IssuerAndSerialNumber(com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) RecipientEncryptedKey(com.github.zhenwei.pkix.util.asn1.cms.RecipientEncryptedKey) RecipientKeyIdentifier(com.github.zhenwei.pkix.util.asn1.cms.RecipientKeyIdentifier) KeyAgreeRecipientIdentifier(com.github.zhenwei.pkix.util.asn1.cms.KeyAgreeRecipientIdentifier)

Example 24 with IssuerAndSerialNumber

use of com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber in project itext2 by albfernandez.

the class PdfPublicKeySecurityHandler method computeRecipientInfo.

private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) throws GeneralSecurityException, IOException {
    ASN1InputStream asn1inputstream = new ASN1InputStream(new ByteArrayInputStream(x509certificate.getTBSCertificate()));
    TBSCertificateStructure tbscertificatestructure = TBSCertificateStructure.getInstance(asn1inputstream.readObject());
    AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo().getAlgorithm();
    IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbscertificatestructure.getIssuer(), tbscertificatestructure.getSerialNumber().getValue());
    Cipher cipher = Cipher.getInstance(algorithmidentifier.getAlgorithm().getId());
    cipher.init(1, x509certificate);
    DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
    RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
    return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring);
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) KeyTransRecipientInfo(org.bouncycastle.asn1.cms.KeyTransRecipientInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) TBSCertificateStructure(org.bouncycastle.asn1.x509.TBSCertificateStructure) Cipher(javax.crypto.Cipher) RecipientIdentifier(org.bouncycastle.asn1.cms.RecipientIdentifier) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 25 with IssuerAndSerialNumber

use of com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber in project iPLAss by ISID.

the class SmimeHandler method sign.

private MimeMessage sign(Session session, MimeMessage message, String keyPass) throws MessagingException {
    // TODO 先頭のaddressで署名するでよいか?
    Address[] from = message.getFrom();
    CertificateKeyPair ckp = certStore.getCertificateKeyPair(((InternetAddress) from[0]).getAddress(), keyPass);
    if (ckp == null) {
        throw new CertificateInvalidException("Valid CertificateKeyPair not found:" + ((InternetAddress) from[0]).getAddress());
    }
    // Sign the message
    MimeMultipart mm;
    try {
        // Create the SMIMESignedGenerator
        SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
        capabilities.addCapability(cmsAlgorithm);
        ASN1EncodableVector attributes = new ASN1EncodableVector();
        attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(new IssuerAndSerialNumber(new X500Name((ckp.getCertificate()).getIssuerDN().getName()), ckp.getCertificate().getSerialNumber())));
        attributes.add(new SMIMECapabilitiesAttribute(capabilities));
        SMIMESignedGenerator signer = new SMIMESignedGenerator();
        signer.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).setSignedAttributeGenerator(new AttributeTable(attributes)).build(signatureAlgorithmMap.get(ckp.getKey().getAlgorithm()), ckp.getKey(), ckp.getCertificate()));
        // Add the list of certs to the generator
        List<Object> certList = new ArrayList<>();
        certList.add(ckp.getCertificate());
        Store<?> certs = new JcaCertStore(certList);
        signer.addCertificates(certs);
        mm = signer.generate(message);
    } catch (CertificateEncodingException | OperatorCreationException | SMIMEException e) {
        throw new SmimeRuntimeException("can not sign to mail: " + e.getMessage(), e);
    }
    MimeMessage signedMessage = new MimeMessage(session);
    // /Set all original MIME headers in the signed message
    Enumeration<?> headers = message.getAllHeaderLines();
    while (headers.hasMoreElements()) {
        signedMessage.addHeaderLine((String) headers.nextElement());
    }
    // Set the content of the signed message
    signedMessage.setContent(mm);
    return signedMessage;
}
Also used : IssuerAndSerialNumber(org.bouncycastle.asn1.cms.IssuerAndSerialNumber) InternetAddress(javax.mail.internet.InternetAddress) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) ArrayList(java.util.ArrayList) SMIMESignedGenerator(org.bouncycastle.mail.smime.SMIMESignedGenerator) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) X500Name(org.bouncycastle.asn1.x500.X500Name) SMIMEEncryptionKeyPreferenceAttribute(org.bouncycastle.asn1.smime.SMIMEEncryptionKeyPreferenceAttribute) MimeMultipart(javax.mail.internet.MimeMultipart) SMIMECapabilityVector(org.bouncycastle.asn1.smime.SMIMECapabilityVector) MimeMessage(javax.mail.internet.MimeMessage) SMIMEException(org.bouncycastle.mail.smime.SMIMEException) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) SMIMECapabilitiesAttribute(org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute) JcaSimpleSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoGeneratorBuilder) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Aggregations

IssuerAndSerialNumber (org.bouncycastle.asn1.cms.IssuerAndSerialNumber)21 ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)8 X500Name (org.bouncycastle.asn1.x500.X500Name)8 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)7 CMSSignedData (org.bouncycastle.cms.CMSSignedData)5 IssuerAndSerialNumber (com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber)4 Date (java.util.Date)4 Cipher (javax.crypto.Cipher)4 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)4 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)4 DEROctetString (org.bouncycastle.asn1.DEROctetString)4 DhSigStatic (org.bouncycastle.asn1.crmf.DhSigStatic)4 CertificationRequest (org.bouncycastle.asn1.pkcs.CertificationRequest)4 SMIMEEncryptionKeyPreferenceAttribute (org.bouncycastle.asn1.smime.SMIMEEncryptionKeyPreferenceAttribute)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 KeyTransRecipientInfo (org.bouncycastle.asn1.cms.KeyTransRecipientInfo)3 RecipientIdentifier (org.bouncycastle.asn1.cms.RecipientIdentifier)3 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 BigInteger (java.math.BigInteger)2