コード例 #1
0
ファイル: RSATest.cs プロジェクト: ekr/hacrypto
        private byte[] derEncode(DerObjectIdentifier oid, byte[] hash)
        {
            AlgorithmIdentifier algId = new AlgorithmIdentifier(oid, DerNull.Instance);
            DigestInfo          dInfo = new DigestInfo(algId, hash);

            return(dInfo.GetEncoded(Asn1Encodable.Der));
        }
コード例 #2
0
            public SignerInfo Generate(DerObjectIdentifier contentType, AlgorithmIdentifier digestAlgorithm, byte[] calculatedDigest)
            {
                SignerInfo result;

                try
                {
                    string  digestAlgName = CmsSignedDataStreamGenerator.Helper.GetDigestAlgName(this._digestOID);
                    string  algorithm     = digestAlgName + "with" + this._encName;
                    byte[]  array         = calculatedDigest;
                    Asn1Set asn1Set       = null;
                    if (this._sAttr != null)
                    {
                        IDictionary baseParameters = this.outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest);
                        Org.BouncyCastle.Asn1.Cms.AttributeTable attributeTable = this._sAttr.GetAttributes(baseParameters);
                        if (contentType == null && attributeTable != null && attributeTable[CmsAttributes.ContentType] != null)
                        {
                            IDictionary dictionary = attributeTable.ToDictionary();
                            dictionary.Remove(CmsAttributes.ContentType);
                            attributeTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(dictionary);
                        }
                        asn1Set = this.outer.GetAttributeSet(attributeTable);
                        array   = asn1Set.GetEncoded("DER");
                    }
                    else if (this._encName.Equals("RSA"))
                    {
                        DigestInfo digestInfo = new DigestInfo(digestAlgorithm, calculatedDigest);
                        array = digestInfo.GetEncoded("DER");
                    }
                    this._sig.BlockUpdate(array, 0, array.Length);
                    byte[]  array2 = this._sig.GenerateSignature();
                    Asn1Set unauthenticatedAttributes = null;
                    if (this._unsAttr != null)
                    {
                        IDictionary baseParameters2 = this.outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest);
                        baseParameters2[CmsAttributeTableParameter.Signature] = array2.Clone();
                        Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = this._unsAttr.GetAttributes(baseParameters2);
                        unauthenticatedAttributes = this.outer.GetAttributeSet(attributes);
                    }
                    Asn1Encodable       defaultX509Parameters  = SignerUtilities.GetDefaultX509Parameters(algorithm);
                    AlgorithmIdentifier encAlgorithmIdentifier = CmsSignedGenerator.GetEncAlgorithmIdentifier(new DerObjectIdentifier(this._encOID), defaultX509Parameters);
                    result = new SignerInfo(this._signerIdentifier, digestAlgorithm, asn1Set, encAlgorithmIdentifier, new DerOctetString(array2), unauthenticatedAttributes);
                }
                catch (IOException e)
                {
                    throw new CmsStreamException("encoding error.", e);
                }
                catch (SignatureException e2)
                {
                    throw new CmsStreamException("error creating signature.", e2);
                }
                return(result);
            }
コード例 #3
0
 public SignerInfo Generate(DerObjectIdentifier contentType, AlgorithmIdentifier digestAlgorithm, byte[] calculatedDigest)
 {
     //IL_016e: Expected O, but got Unknown
     try
     {
         string  digestAlgName = Helper.GetDigestAlgName(_digestOID);
         string  algorithm     = digestAlgName + "with" + _encName;
         byte[]  array         = calculatedDigest;
         Asn1Set asn1Set       = null;
         if (_sAttr != null)
         {
             IDictionary baseParameters = outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest);
             Org.BouncyCastle.Asn1.Cms.AttributeTable attributeTable = _sAttr.GetAttributes(baseParameters);
             if (contentType == null && attributeTable != null && attributeTable[CmsAttributes.ContentType] != null)
             {
                 IDictionary val = attributeTable.ToDictionary();
                 val.Remove((object)CmsAttributes.ContentType);
                 attributeTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(val);
             }
             asn1Set = outer.GetAttributeSet(attributeTable);
             array   = asn1Set.GetEncoded("DER");
         }
         else if (_encName.Equals("RSA"))
         {
             DigestInfo digestInfo = new DigestInfo(digestAlgorithm, calculatedDigest);
             array = digestInfo.GetEncoded("DER");
         }
         _sig.BlockUpdate(array, 0, array.Length);
         byte[]  array2 = _sig.GenerateSignature();
         Asn1Set unauthenticatedAttributes = null;
         if (_unsAttr != null)
         {
             IDictionary baseParameters2 = outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest);
             baseParameters2.set_Item((object)CmsAttributeTableParameter.Signature, ((global::System.Array)array2).Clone());
             Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = _unsAttr.GetAttributes(baseParameters2);
             unauthenticatedAttributes = outer.GetAttributeSet(attributes);
         }
         Asn1Encodable       defaultX509Parameters  = SignerUtilities.GetDefaultX509Parameters(algorithm);
         AlgorithmIdentifier encAlgorithmIdentifier = Helper.GetEncAlgorithmIdentifier(new DerObjectIdentifier(_encOID), defaultX509Parameters);
         return(new SignerInfo(_signerIdentifier, digestAlgorithm, asn1Set, encAlgorithmIdentifier, new DerOctetString(array2), unauthenticatedAttributes));
     }
     catch (IOException val2)
     {
         IOException e = val2;
         throw new CmsStreamException("encoding error.", (global::System.Exception)(object) e);
     }
     catch (SignatureException e2)
     {
         throw new CmsStreamException("error creating signature.", e2);
     }
 }
コード例 #4
0
        private DigestInfo DerDecode(byte[] encoding)
        {
            if (encoding[0] != 48)
            {
                throw new IOException("not a digest info object");
            }
            DigestInfo instance = DigestInfo.GetInstance(Asn1Object.FromByteArray(encoding));

            if (instance.GetEncoded().Length != encoding.Length)
            {
                throw new CmsException("malformed RSA signature");
            }
            return(instance);
        }
コード例 #5
0
        private DigestInfo DerDecode(byte[] encoding)
        {
            //IL_000c: Unknown result type (might be due to invalid IL or missing references)
            if (encoding[0] != 48)
            {
                throw new IOException("not a digest info object");
            }
            DigestInfo instance = DigestInfo.GetInstance(Asn1Object.FromByteArray(encoding));

            if (instance.GetEncoded().Length != encoding.Length)
            {
                throw new CmsException("malformed RSA signature");
            }
            return(instance);
        }
コード例 #6
0
        private DigestInfo DerDecode(
            byte[] encoding)
        {
            if (encoding[0] != (int)(Asn1Tags.Constructed | Asn1Tags.Sequence))
            {
                throw new IOException("not a digest info object");
            }

            DigestInfo digInfo = DigestInfo.GetInstance(Asn1Object.FromByteArray(encoding));

            // length check to avoid Bleichenbacher vulnerability

            if (digInfo.GetEncoded().Length != encoding.Length)
            {
                throw new CmsException("malformed RSA signature");
            }

            return(digInfo);
        }
コード例 #7
0
            public SignerInfo Generate(DerObjectIdentifier contentType, AlgorithmIdentifier digestAlgorithm,
                                       byte[] calculatedDigest)
            {
                try
                {
                    string digestName    = Helper.GetDigestAlgName(_digestOID);
                    string signatureName = digestName + "with" + _encName;

//					AlgorithmIdentifier digAlgId = DigestAlgorithmID;
//
//					byte[] hash = (byte[])outer._messageHashes[Helper.GetDigestAlgName(this._digestOID)];
//					outer._digests[_digestOID] = hash.Clone();

                    byte[] bytesToSign = calculatedDigest;

                    /* RFC 3852 5.4
                     * The result of the message digest calculation process depends on
                     * whether the signedAttrs field is present.  When the field is absent,
                     * the result is just the message digest of the content as described
                     *
                     * above.  When the field is present, however, the result is the message
                     * digest of the complete DER encoding of the SignedAttrs value
                     * contained in the signedAttrs field.
                     */
                    Asn1Set signedAttr = null;
                    if (_sAttr != null)
                    {
                        IDictionary parameters = outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest);

//						Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(Collections.unmodifiableMap(parameters));
                        Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(parameters);

                        if (contentType == null) //counter signature
                        {
                            if (signed != null && signed[CmsAttributes.ContentType] != null)
                            {
                                IDictionary tmpSigned = signed.ToDictionary();
                                tmpSigned.Remove(CmsAttributes.ContentType);
                                signed = new Asn1.Cms.AttributeTable(tmpSigned);
                            }
                        }

                        signedAttr = outer.GetAttributeSet(signed);

                        // sig must be composed from the DER encoding.
                        bytesToSign = signedAttr.GetEncoded(Asn1Encodable.Der);
                    }
                    else
                    {
                        // Note: Need to use raw signatures here since we have already calculated the digest
                        if (_encName.Equals("RSA"))
                        {
                            DigestInfo dInfo = new DigestInfo(digestAlgorithm, calculatedDigest);
                            bytesToSign = dInfo.GetEncoded(Asn1Encodable.Der);
                        }
                    }

                    _sig.BlockUpdate(bytesToSign, 0, bytesToSign.Length);
                    byte[] sigBytes = _sig.GenerateSignature();

                    Asn1Set unsignedAttr = null;
                    if (_unsAttr != null)
                    {
                        IDictionary parameters = outer.GetBaseParameters(
                            contentType, digestAlgorithm, calculatedDigest);
                        parameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone();

//						Asn1.Cms.AttributeTable unsigned = _unsAttr.getAttributes(Collections.unmodifiableMap(parameters));
                        Asn1.Cms.AttributeTable unsigned = _unsAttr.GetAttributes(parameters);

                        unsignedAttr = outer.GetAttributeSet(unsigned);
                    }

                    // TODO[RSAPSS] Need the ability to specify non-default parameters
                    Asn1Encodable       sigX509Parameters         = SignerUtilities.GetDefaultX509Parameters(signatureName);
                    AlgorithmIdentifier digestEncryptionAlgorithm = Helper.GetEncAlgorithmIdentifier(
                        new DerObjectIdentifier(_encOID), sigX509Parameters);

                    return(new SignerInfo(_signerIdentifier, digestAlgorithm,
                                          signedAttr, digestEncryptionAlgorithm, new DerOctetString(sigBytes), unsignedAttr));
                }
                catch (IOException e)
                {
                    throw new CmsStreamException("encoding error.", e);
                }
                catch (SignatureException e)
                {
                    throw new CmsStreamException("error creating signature.", e);
                }
            }
コード例 #8
0
        private bool doVerify(bool isRawVerifier, IVerifierFactory <AlgorithmIdentifier> verifierFactory, IDigestFactory <AlgorithmIdentifier> digestFactory)
        {
            IStreamCalculator <IVerifier> contentVerifier = verifierFactory.CreateCalculator();
            Stream sigOut = contentVerifier.Stream;

            try
            {
                if (resultDigest == null)
                {
                    IStreamCalculator <IBlockResult> calc = digestFactory.CreateCalculator();
                    if (content != null)
                    {
                        Stream digOut = calc.Stream;

                        if (signedAttributeSet == null)
                        {
                            if (isRawVerifier)
                            {
                                content.Write(digOut);
                            }
                            else
                            {
                                Stream cOut = new TeeOutputStream(digOut, sigOut);

                                content.Write(cOut);

                                cOut.Close();
                            }
                        }
                        else
                        {
                            content.Write(digOut);
                            byte[] enc = this.GetEncodedSignedAttributes();
                            sigOut.Write(enc, 0, enc.Length);
                        }

                        digOut.Close();
                    }
                    else if (signedAttributeSet != null)
                    {
                        byte[] enc = this.GetEncodedSignedAttributes();

                        sigOut.Write(enc, 0, enc.Length);
                    }
                    else
                    {
                        // TODO Get rid of this exception and just treat content==null as empty not missing?
                        throw new CmsException("data not encapsulated in signature - use detached constructor.");
                    }

                    resultDigest = calc.GetResult().Collect();
                }
                else
                {
                    if (signedAttributeSet == null)
                    {
                        if (content != null)
                        {
                            content.Write(sigOut);
                        }
                    }
                    else
                    {
                        byte[] enc = this.GetEncodedSignedAttributes();

                        sigOut.Write(enc, 0, enc.Length);
                    }
                }

                sigOut.Close();
            }
            catch (Exception e)
            {
                throw new CmsException("can't process object to create signature.", e);
            }

            // RFC 3852 11.1 Check the content-type attribute is correct
            {
                Asn1Object validContentType = GetSingleValuedSignedAttribute(
                    CmsAttributes.ContentType, "content-type");
                if (validContentType == null)
                {
                    if (!isCounterSignature && signedAttributeSet != null)
                    {
                        throw new CmsException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data");
                    }
                }
                else
                {
                    if (isCounterSignature)
                    {
                        throw new CmsException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute");
                    }

                    if (!(validContentType is DerObjectIdentifier))
                    {
                        throw new CmsException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'");
                    }

                    DerObjectIdentifier signedContentType = (DerObjectIdentifier)validContentType;

                    if (!signedContentType.Equals(contentType))
                    {
                        throw new CmsException("content-type attribute value does not match eContentType");
                    }
                }
            }

            Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes;

            // RFC 6211 Validate Algorithm Identifier protection attribute if present
            {
                Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes;
                if (unsignedAttrTable != null && unsignedAttrTable.GetAll(CmsAttributes.CmsAlgorithmProtect).Count > 0)
                {
                    throw new CmsException("A cmsAlgorithmProtect attribute MUST be a signed attribute");
                }
                if (signedAttrTable != null)
                {
                    Asn1EncodableVector protectionAttributes = signedAttrTable.GetAll(CmsAttributes.CmsAlgorithmProtect);
                    if (protectionAttributes.Count > 1)
                    {
                        throw new CmsException("Only one instance of a cmsAlgorithmProtect attribute can be present");
                    }

                    if (protectionAttributes.Count > 0)
                    {
                        Asn1.Cms.Attribute attr = Asn1.Cms.Attribute.GetInstance(protectionAttributes[0]);
                        if (attr.AttrValues.Count != 1)
                        {
                            throw new CmsException("A cmsAlgorithmProtect attribute MUST contain exactly one value");
                        }

                        CmsAlgorithmProtection algorithmProtection = CmsAlgorithmProtection.GetInstance(attr.AttrValues[0]);

                        if (!CmsUtilities.IsEquivalent(algorithmProtection.DigestAlgorithm, info.DigestAlgorithm))
                        {
                            throw new CmsException("CMS Algorithm Identifier Protection check failed for digestAlgorithm");
                        }

                        if (!CmsUtilities.IsEquivalent(algorithmProtection.SignatureAlgorithm, info.DigestEncryptionAlgorithm))
                        {
                            throw new CmsException("CMS Algorithm Identifier Protection check failed for signatureAlgorithm");
                        }
                    }
                }
            }

            // RFC 3852 11.2 Check the message-digest attribute is correct
            {
                Asn1Encodable validMessageDigest = GetSingleValuedSignedAttribute(
                    CmsAttributes.MessageDigest, "message-digest");
                if (validMessageDigest == null)
                {
                    if (signedAttributeSet != null)
                    {
                        throw new CmsException("the message-digest signed attribute type MUST be present when there are any signed attributes present");
                    }
                }
                else
                {
                    if (!(validMessageDigest is Asn1OctetString))
                    {
                        throw new CmsException("message-digest attribute value not of ASN.1 type 'OCTET STRING'");
                    }

                    Asn1OctetString signedMessageDigest = (Asn1OctetString)validMessageDigest;

                    if (!Arrays.ConstantTimeAreEqual(resultDigest, signedMessageDigest.GetOctets()))
                    {
                        throw new CmsSignerDigestMismatchException("message-digest attribute value does not match calculated value");
                    }
                }
            }

            // RFC 3852 11.4 Validate countersignature attribute(s)
            {
                if (signedAttrTable != null &&
                    signedAttrTable.GetAll(CmsAttributes.CounterSignature).Count > 0)
                {
                    throw new CmsException("A countersignature attribute MUST NOT be a signed attribute");
                }

                Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes;
                if (unsignedAttrTable != null)
                {
                    Asn1EncodableVector csAttrs = unsignedAttrTable.GetAll(CmsAttributes.CounterSignature);
                    for (int i = 0; i < csAttrs.Count; ++i)
                    {
                        Asn1.Cms.Attribute csAttr = Asn1.Cms.Attribute.GetInstance(csAttrs[i]);
                        if (csAttr.AttrValues.Count < 1)
                        {
                            throw new CmsException("A countersignature attribute MUST contain at least one AttributeValue");
                        }

                        // Note: We don't recursively validate the countersignature value
                    }
                }
            }

            try
            {
                if (signedAttributeSet == null && resultDigest != null)
                {
                    if (isRawVerifier)
                    {
                        if (SignatureAlgorithmID.Algorithm.Equals(PkcsObjectIdentifiers.RsaEncryption))
                        {
                            DigestInfo digInfo = new DigestInfo(new AlgorithmIdentifier(digestAlgorithm.Algorithm, DerNull.Instance), resultDigest);
                            byte[]     data    = digInfo.GetEncoded(Asn1Encodable.Der);

                            sigOut.Write(data, 0, data.Length);

                            sigOut.Close();

                            return(contentVerifier.GetResult().IsVerified(this.GetSignature()));
                        }

                        sigOut.Write(resultDigest, 0, resultDigest.Length);

                        sigOut.Close();

                        return(contentVerifier.GetResult().IsVerified(this.GetSignature()));
                    }
                }

                sigOut.Close();

                return(contentVerifier.GetResult().IsVerified(this.GetSignature()));
            }
            catch (IOException e)
            {
                throw new CmsException("can't process mime object to create signature.", e);
            }
        }
コード例 #9
0
            internal SignerInfo ToSignerInfo(
                DerObjectIdentifier contentType)
            {
                string digestName    = Helper.GetDigestAlgName(_digestOID);
                string encName       = Helper.GetEncryptionAlgName(_encOID);
                string signatureName = digestName + "with" + encName;

                AlgorithmIdentifier digAlgId = DigestAlgorithmID;

                byte[] hash = (byte[])outer._messageHashes[Helper.GetDigestAlgName(this._digestOID)];
                outer._digests[_digestOID] = hash.Clone();

                byte[]  bytesToSign = hash;
                ISigner sig;

                /* RFC 3852 5.4
                 * The result of the message digest calculation process depends on
                 * whether the signedAttrs field is present.  When the field is absent,
                 * the result is just the message digest of the content as described
                 *
                 * above.  When the field is present, however, the result is the message
                 * digest of the complete DER encoding of the SignedAttrs value
                 * contained in the signedAttrs field.
                 */
                Asn1Set signedAttr = null;

                if (_sAttr != null)
                {
                    IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);
//					Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(Collections.unmodifiableMap(parameters));
                    Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(parameters);

                    // TODO Handle countersignatures (see CMSSignedDataGenerator)

                    signedAttr = outer.GetAttributeSet(signed);

                    // sig must be composed from the DER encoding.
                    bytesToSign = signedAttr.GetEncoded(Asn1Encodable.Der);
                    sig         = Helper.GetSignatureInstance(signatureName);
                }
                else
                {
                    // Note: Need to use raw signatures here since we have already calculated the digest
                    if (encName.Equals("RSA"))
                    {
                        DigestInfo dInfo = new DigestInfo(digAlgId, hash);
                        bytesToSign = dInfo.GetEncoded(Asn1Encodable.Der);
                        sig         = Helper.GetSignatureInstance("RSA");
                    }
                    else if (encName.Equals("DSA"))
                    {
                        sig = Helper.GetSignatureInstance("NONEwithDSA");
                    }
                    // TODO Add support for raw PSS
//					else if (encName.equals("RSAandMGF1"))
//					{
//						sig = CMSSignedHelper.INSTANCE.getSignatureInstance("NONEWITHRSAPSS", _sigProvider);
//						try
//						{
//							// Init the params this way to avoid having a 'raw' version of each PSS algorithm
//							Signature sig2 = CMSSignedHelper.INSTANCE.getSignatureInstance(signatureName, _sigProvider);
//							PSSParameterSpec spec = (PSSParameterSpec)sig2.getParameters().getParameterSpec(PSSParameterSpec.class);
//							sig.setParameter(spec);
//						}
//						catch (Exception e)
//						{
//							throw new SignatureException("algorithm: " + encName + " could not be configured.");
//						}
//					}
                    else
                    {
                        throw new SignatureException("algorithm: " + encName + " not supported in base signatures.");
                    }
                }

                sig.Init(true, new ParametersWithRandom(_key, outer.rand));
                sig.BlockUpdate(bytesToSign, 0, bytesToSign.Length);
                byte[] sigBytes = sig.GenerateSignature();

                Asn1Set unsignedAttr = null;

                if (_unsAttr != null)
                {
                    IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);
                    parameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone();

//					Asn1.Cms.AttributeTable unsigned = _unsAttr.getAttributes(Collections.unmodifiableMap(parameters));
                    Asn1.Cms.AttributeTable unsigned = _unsAttr.GetAttributes(parameters);

                    unsignedAttr = outer.GetAttributeSet(unsigned);
                }

                // TODO[RSAPSS] Need the ability to specify non-default parameters
                Asn1Encodable       sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName);
                AlgorithmIdentifier encAlgId          = CmsSignedGenerator.GetEncAlgorithmIdentifier(
                    new DerObjectIdentifier(_encOID), sigX509Parameters);

                return(new SignerInfo(_signerIdentifier, digAlgId,
                                      signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr));
            }