Ejemplo n.º 1
0
		internal static void SetSignatureParameters(
			ISigner			signature,
			Asn1Encodable	parameters)
		{
			if (parameters != null && !derNull.Equals(parameters))
			{
				// TODO Put back in
//				AlgorithmParameters sigParams = AlgorithmParameters.GetInstance(signature.getAlgorithm());
//
//				try
//				{
//					sigParams.Init(parameters.ToAsn1Object().GetDerEncoded());
//				}
//				catch (IOException e)
//				{
//					throw new SignatureException("IOException decoding parameters: " + e.Message);
//				}
//
//				if (Platform.EndsWith(signature.getAlgorithm(), "MGF1"))
//				{
//					try
//					{
//						signature.setParameter(sigParams.getParameterSpec(PSSParameterSpec.class));
//					}
//					catch (GeneralSecurityException e)
//					{
//						throw new SignatureException("Exception extracting parameters: " + e.Message);
//					}
//				}
			}
		}
Ejemplo n.º 2
0
        public Challenge Decode(IdentifierPart ip, ChallengePart cp, ISigner signer)
        {
            if (cp.Type != AcmeProtocol.CHALLENGE_TYPE_HTTP)
                throw new InvalidDataException("unsupported Challenge type")
                    .With("challengeType", cp.Type)
                    .With("supportedChallengeTypes", AcmeProtocol.CHALLENGE_TYPE_HTTP);

            //var token = (string)cp["token"];
            var token = cp.Token;

            // This response calculation is described in:
            //    https://tools.ietf.org/html/draft-ietf-acme-acme-01#section-7.2

            var keyAuthz = JwsHelper.ComputeKeyAuthorization(signer, token);
            var path = $"{AcmeProtocol.HTTP_CHALLENGE_PATHPREFIX}{token}";
            var url = $"http://{ip.Value}/{path}";


            var ca = new HttpChallengeAnswer
            {
                KeyAuthorization = keyAuthz,
            };

            var c = new HttpChallenge(cp.Type, ca)
            {
                Token = token,
                FileUrl = url,
                FilePath = path,
                FileContent = keyAuthz,
            };

            return c;
        }
Ejemplo n.º 3
0
		public override Script GenerateScriptSig(Script scriptPubKey, IKeyRepository keyRepo, ISigner signer)
		{
			var multiSigParams = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey);
			TransactionSignature[] signatures = new TransactionSignature[multiSigParams.PubKeys.Length];
			var keys =
				multiSigParams
				.PubKeys
				.Select(p => keyRepo.FindKey(p.ScriptPubKey))
				.ToArray();

			int sigCount = 0;
			for(int i = 0 ; i < keys.Length ; i++)
			{
				if(sigCount == multiSigParams.SignatureCount)
					break;
				if(keys[i] != null)
				{
					var sig = signer.Sign(keys[i]);
					signatures[i] = sig;
					sigCount++;
				}
			}

			IEnumerable<TransactionSignature> sigs = signatures;
			if(sigCount == multiSigParams.SignatureCount)
			{
				sigs = sigs.Where(s => s != TransactionSignature.Empty && s != null);
			}
			return PayToMultiSigTemplate.Instance.GenerateScriptSig(sigs);
		}
Ejemplo n.º 4
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MimeKit.Cryptography.DkimSignatureStream"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="DkimSignatureStream"/>.
		/// </remarks>
		/// <param name="signer">The digest signer.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="signer"/>is <c>null</c>.
		/// </exception>
		public DkimSignatureStream (ISigner signer)
		{
			if (signer == null)
				throw new ArgumentNullException ("signer");

			Signer = signer;
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="DkimSigningRoutingAgent"/> class.
        /// </summary>
        /// <param name="dkimSigner">The object that knows how to sign messages.</param>
        public DkimSigningRoutingAgent(List<DomainElement> domainSettings, ISigner dkimSigner)
        {
            this.domainSettings = domainSettings;
            this.dkimSigner = dkimSigner;

            this.OnCategorizedMessage += this.WhenMessageCategorized;
        }
Ejemplo n.º 6
0
        public Challenge Decode(IdentifierPart ip, ChallengePart cp, ISigner signer)
        {
            if (cp.Type != AcmeProtocol.CHALLENGE_TYPE_DNS)
                throw new InvalidDataException("unsupported Challenge type")
                    .With("challengeType", cp.Type)
                    .With("supportedChallengeTypes", AcmeProtocol.CHALLENGE_TYPE_DNS);

            //var token = (string)cp["token"];
            var token = cp.Token;

            // This response calculation is described in:
            //    https://tools.ietf.org/html/draft-ietf-acme-acme-01#section-7.5

            var keyAuthz = JwsHelper.ComputeKeyAuthorization(signer, token);
            var keyAuthzDig = JwsHelper.ComputeKeyAuthorizationDigest(signer, token);

            var ca = new DnsChallengeAnswer
            {
                KeyAuthorization = keyAuthz,
            };

            var c = new DnsChallenge(cp.Type, ca)
            {
                Token = token,
                RecordName = $"{AcmeProtocol.DNS_CHALLENGE_NAMEPREFIX}{ip.Value}",
                RecordValue = keyAuthzDig,
            };

            return c;
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Returns a key-value pair that represents the HTTP resource path that
 /// needs to be configured (the key) and the resource content that should be returned
 /// for an HTTP request for this path on a server that the target DNS resolve to.
 /// </summary>
 /// <param name="dnsId"></param>
 /// <param name="signer"></param>
 /// <returns></returns>
 public KeyValuePair<string, string> GenerateHttpChallengeAnswer(string dnsId, ISigner signer)
 {
     var keyAuthz = JwsHelper.ComputeKeyAuthorization(signer, Token);
     
     return new KeyValuePair<string, string>(
             $"{HTTP_CHALLENGE_PATHPREFIX}{Token}", keyAuthz);
 }
Ejemplo n.º 8
0
		public override Script GenerateScriptSig(Script scriptPubKey, IKeyRepository keyRepo, ISigner signer)
		{
			var key = keyRepo.FindKey(scriptPubKey);
			if(key == null)
				return null;
			var sig = signer.Sign(key);
			return PayToPubkeyTemplate.Instance.GenerateScriptSig(sig);
		}
        /// <summary>Create a generator for the passed in keyAlgorithm and hashAlgorithm codes.</summary>
        public PgpSignatureGenerator(PublicKeyAlgorithmTag keyAlgorithm, HashAlgorithmTag hashAlgorithm)
        {
            _keyAlgorithm = keyAlgorithm;
            _hashAlgorithm = hashAlgorithm;

            _dig = DigestUtilities.GetDigest(PgpUtilities.GetDigestName(hashAlgorithm));
            _sig = SignerUtilities.GetSigner(PgpUtilities.GetSignatureName(keyAlgorithm, hashAlgorithm));
        }
Ejemplo n.º 10
0
		public SignerStream(
			Stream	stream,
			ISigner	readSigner,
			ISigner	writeSigner)
		{
			this.stream = stream;
			this.inSigner = readSigner;
			this.outSigner = writeSigner;
		}
Ejemplo n.º 11
0
		public override Script GenerateScriptSig(Script scriptPubKey, IKeyRepository keyRepo, ISigner signer)
		{
			var parameters = PayToPubkeyHashTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey);
			var key = keyRepo.FindKey(parameters.ScriptPubKey);
			if(key == null)
				return null;
			var sig = signer.Sign(key);
			return PayToPubkeyHashTemplate.Instance.GenerateScriptSig(sig, key.PubKey);
		}
		/// <summary>Create a generator for the passed in keyAlgorithm and hashAlgorithm codes.</summary>
        public PgpV3SignatureGenerator(
            PublicKeyAlgorithmTag	keyAlgorithm,
            HashAlgorithmTag		hashAlgorithm)
        {
            this.keyAlgorithm = keyAlgorithm;
            this.hashAlgorithm = hashAlgorithm;

            dig = DigestUtilities.GetDigest(PgpUtilities.GetDigestName(hashAlgorithm));
            sig = SignerUtilities.GetSigner(PgpUtilities.GetSignatureName(keyAlgorithm, hashAlgorithm));
        }
Ejemplo n.º 13
0
        public AcmeClient(Uri rootUrl = null, AcmeServerDirectory dir = null,
                ISigner signer = null, AcmeRegistration reg = null)
        {
            RootUrl = rootUrl;
            Directory = dir;
            Signer = signer;
            Registration = reg;

            UserAgent = string.Format(AcmeProtocol.HTTP_USER_AGENT_FMT,
                    this.GetType().Assembly.GetName().Version);
        }
Ejemplo n.º 14
0
        internal PgpOnePassSignature(
            OnePassSignaturePacket sigPack)
        {
            this.sigPack = sigPack;
            this.signatureType = sigPack.SignatureType;

            try
            {
                this.sig = SignerUtilities.GetSigner(
                    PgpUtilities.GetSignatureName(sigPack.KeyAlgorithm, sigPack.HashAlgorithm));
            }
            catch (Exception e)
            {
                throw new PgpException("can't set up signature object.",  e);
            }
        }
            internal SignerInf(
				CmsSignedDataStreamGenerator	outer,
				AsymmetricKeyParameter			key,
				X509Certificate					cert,
				string							digestOID,
				string							encOID,
				CmsAttributeTableGenerator		sAttr,
				CmsAttributeTableGenerator		unsAttr,
				ISigner							signature)
			{
				this.outer = outer;

				_key = key;
				_cert = cert;
				_digestOID = digestOID;
				_encOID = encOID;
				_sAttr = sAttr;
				_unsAttr = unsAttr;
				_signature = signature;
			}
Ejemplo n.º 16
0
		/// <summary>Initialise the signature object for verification.</summary>
        public void InitVerify(
            PgpPublicKey pubKey)
        {
			lastb = 0;

			try
			{
				sig = SignerUtilities.GetSigner(
					PgpUtilities.GetSignatureName(sigPack.KeyAlgorithm, sigPack.HashAlgorithm));
			}
			catch (Exception e)
			{
				throw new PgpException("can't set up signature object.",  e);
			}

			try
            {
                sig.Init(false, pubKey.GetKey());
            }
			catch (InvalidKeyException e)
            {
                throw new PgpException("invalid key.", e);
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Returns a key-value pair that represents the DNS domain name that needs
        /// to be configured (the key) and the value that should be returned (the value)
        /// for a query against that domain name for a record of type TXT.
        /// </summary>
        /// <param name="dnsId"></param>
        /// <param name="signer"></param>
        /// <returns></returns>
        public KeyValuePair<string, string> GenerateDnsChallengeAnswer(string dnsId, ISigner signer)
        {
            var resp = new
            {
                type = "dns",
                token = Token
            };
            var json = JsonConvert.SerializeObject(resp);
            var hdrs = new { alg = signer.JwsAlg, jwk = signer.ExportJwk() };
            var signed = JwsHelper.SignFlatJsonAsObject(
                    signer.Sign, json, unprotectedHeaders: hdrs);

            /*
            // We format it as a set of lines broken on 100-character boundaries to make it
            // easier to copy and put into a DNS TXT RR which normally have a 255-char limit
            // so this result may need to be broken up into multiple smaller TXT RR entries
            var sigFormatted = Regex.Replace(signed.signature,
                    "(.{100,100})", "$1\r\n");
            */

            return new KeyValuePair<string, string>(
                    $"{DNS_CHALLENGE_NAMEPREFIX}{dnsId}",
                    signed.signature); /*sigFormatted);*/
        }
Ejemplo n.º 18
0
 public SignController(IServiceProvider serviceProvider)
 {
     _serviceProvider = serviceProvider;
     _signer          = (ISigner)serviceProvider.GetService(typeof(ISigner));
 }
Ejemplo n.º 19
0
        private void generationTest()
        {
            byte[]  data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            ISigner s    = SignerUtilities.GetSigner("GOST3410");

            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");

            g.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            AsymmetricCipherKeyPair p = g.GenerateKeyPair();

            AsymmetricKeyParameter sKey = p.Private;
            AsymmetricKeyParameter vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("GOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("GOST3410 verification failed");
            }

            //
            // default initialisation test
            //
            s = SignerUtilities.GetSigner("GOST3410");
            g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");

            // TODO This is supposed to be a 'default initialisation' test, but don't have a factory
            // These values are defaults from JCE provider
            g.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("GOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("GOST3410 verification failed");
            }

            //
            // encoded test
            //
            //KeyFactory f = KeyFactory.getInstance("GOST3410");
            //X509EncodedKeySpec  x509s = new X509EncodedKeySpec(vKey.GetEncoded());
            //Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters)f.generatePublic(x509s);
            byte[] vKeyEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded();
            Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters)
                                             PublicKeyFactory.CreateKey(vKeyEnc);

            if (!k1.Y.Equals(((Gost3410PublicKeyParameters)vKey).Y))
            {
                Fail("public number not decoded properly");
            }

            //PKCS8EncodedKeySpec  pkcs8 = new PKCS8EncodedKeySpec(sKey.GetEncoded());
            //Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters)f.generatePrivate(pkcs8);
            byte[] sKeyEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded();
            Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters)
                                              PrivateKeyFactory.CreateKey(sKeyEnc);

            if (!k2.X.Equals(((Gost3410PrivateKeyParameters)sKey).X))
            {
                Fail("private number not decoded properly");
            }

            //
            // ECGOST3410 generation test
            //
            s = SignerUtilities.GetSigner("ECGOST3410");
            g = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");

            BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041");
            BigInteger mod_q = new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619");

            ECCurve curve = new FpCurve(
                mod_p,
                new BigInteger("7"),                                                                             // a
                new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414"), // b
                mod_q, BigInteger.One);

            ECDomainParameters ecSpec = new ECDomainParameters(
                curve,
                curve.CreatePoint(
                    new BigInteger("2"),
                    new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280")),
                mod_q, BigInteger.One);

            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECGOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECGOST3410 verification failed");
            }
        }
Ejemplo n.º 20
0
 public FindNodeMessageSerializer(ISigner signer, IPrivateKeyGenerator privateKeyGenerator, IDiscoveryMessageFactory messageFactory, INodeIdResolver nodeIdResolver) : base(signer, privateKeyGenerator, messageFactory, nodeIdResolver)
 {
 }
            internal SignerInfo ToSignerInfo(
                DerObjectIdentifier contentType,
                CmsProcessable content,
                SecureRandom random)
            {
                AlgorithmIdentifier digAlgId = DigestAlgorithmID;
                string  digestName           = Helper.GetDigestAlgName(digestOID);
                IDigest dig = Helper.GetDigestInstance(digestName);

                string  signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);
                ISigner sig           = Helper.GetSignatureInstance(signatureName);

                // TODO Optimise the case where more than one signer with same digest
                if (content != null)
                {
                    content.Write(new DigOutputStream(dig));
                }

                byte[] hash = DigestUtilities.DoFinal(dig);
                outer._digests.Add(digestOID, hash.Clone());

                sig.Init(true, new ParametersWithRandom(key, random));
#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || NETFX_CORE
                Stream sigStr = new SigOutputStream(sig);
#else
                Stream sigStr = new BufferedStream(new SigOutputStream(sig));
#endif

                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);

                    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);
                        }
                    }

                    // TODO Validate proposed signed attributes

                    signedAttr = outer.GetAttributeSet(signed);

                    // sig must be composed from the DER encoding.
                    new DerOutputStream(sigStr).WriteObject(signedAttr);
                }
                else if (content != null)
                {
                    // TODO Use raw signature of the hash value instead
                    content.Write(sigStr);
                }

                sigStr.Dispose();
                byte[] sigBytes = sig.GenerateSignature();

                Asn1Set unsignedAttr = null;
                if (unsAttr != null)
                {
                    IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash);
                    baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone();

//					Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters));
                    Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters);

                    // TODO Validate proposed unsigned attributes

                    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));
            }
Ejemplo n.º 22
0
        public IStreamCalculator CreateCalculator()
        {
            ISigner verifier = SignerUtilities.InitSigner(X509Utilities.GetSignatureName(algID), false, publicKey, null);

            return(new DefaultVerifierCalculator(verifier));
        }
        /// <inheritdoc/>
        protected override async Task OnOpenAsync(CancellationToken token = default(CancellationToken))
        {
            this.logger?.LogInformation($"Opening session channel with endpoint '{this.RemoteEndpoint.EndpointUrl}'.");
            this.logger?.LogInformation($"SecurityPolicy: '{this.RemoteEndpoint.SecurityPolicyUri}'.");
            this.logger?.LogInformation($"SecurityMode: '{this.RemoteEndpoint.SecurityMode}'.");
            this.logger?.LogInformation($"UserIdentity: '{this.UserIdentity}'.");

            await base.OnOpenAsync(token).ConfigureAwait(false);

            token.ThrowIfCancellationRequested();

            // if SessionId is provided then we skip the CreateSessionRequest and go directly to (re)ActivateSession.
            // requires from previous Session: SessionId, AuthenticationToken, RemoteNonce
            if (this.SessionId == null)
            {
                var localNonce           = this.RemoteEndpoint.SecurityMode != MessageSecurityMode.None ? this.GetNextNonce(NonceLength) : null;
                var localCertificate     = this.RemoteEndpoint.SecurityMode != MessageSecurityMode.None ? this.LocalCertificate : null;
                var createSessionRequest = new CreateSessionRequest
                {
                    ClientDescription       = this.LocalDescription,
                    EndpointUrl             = this.RemoteEndpoint.EndpointUrl,
                    SessionName             = this.LocalDescription.ApplicationName,
                    ClientNonce             = localNonce,
                    ClientCertificate       = localCertificate,
                    RequestedSessionTimeout = this.options.SessionTimeout,
                    MaxResponseMessageSize  = this.RemoteMaxMessageSize
                };

                var createSessionResponse = await this.CreateSessionAsync(createSessionRequest).ConfigureAwait(false);

                this.SessionId           = createSessionResponse.SessionId;
                this.AuthenticationToken = createSessionResponse.AuthenticationToken;
                this.RemoteNonce         = createSessionResponse.ServerNonce;

                // verify the server's certificate is the same as the certificate from the selected endpoint.
                if (this.RemoteEndpoint.ServerCertificate != null && !this.RemoteEndpoint.ServerCertificate.SequenceEqual(createSessionResponse.ServerCertificate))
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Server did not return the same certificate used to create the channel.");
                }

                // verify the server's signature.
                ISigner verifier = null;
                bool    verified = false;

                switch (this.RemoteEndpoint.SecurityPolicyUri)
                {
                case SecurityPolicyUris.Basic128Rsa15:
                case SecurityPolicyUris.Basic256:
                    verifier = SignerUtilities.GetSigner("SHA-1withRSA");
                    verifier.Init(false, this.RemotePublicKey);
                    verifier.BlockUpdate(localCertificate, 0, localCertificate.Length);
                    verifier.BlockUpdate(localNonce, 0, localNonce.Length);
                    verified = verifier.VerifySignature(createSessionResponse.ServerSignature.Signature);
                    break;

                case SecurityPolicyUris.Basic256Sha256:
                case SecurityPolicyUris.Aes128_Sha256_RsaOaep:
                    verifier = SignerUtilities.GetSigner("SHA-256withRSA");
                    verifier.Init(false, this.RemotePublicKey);
                    verifier.BlockUpdate(localCertificate, 0, localCertificate.Length);
                    verifier.BlockUpdate(localNonce, 0, localNonce.Length);
                    verified = verifier.VerifySignature(createSessionResponse.ServerSignature.Signature);
                    break;

                case SecurityPolicyUris.Aes256_Sha256_RsaPss:
                    verifier = SignerUtilities.GetSigner("SHA-256withRSAandMGF1");
                    verifier.Init(false, this.RemotePublicKey);
                    verifier.BlockUpdate(localCertificate, 0, localCertificate.Length);
                    verifier.BlockUpdate(localNonce, 0, localNonce.Length);
                    verified = verifier.VerifySignature(createSessionResponse.ServerSignature.Signature);
                    break;

                default:
                    verified = true;
                    break;
                }

                verifier = null;
                if (!verified)
                {
                    throw new ServiceResultException(StatusCodes.BadApplicationSignatureInvalid, "Server did not provide a correct signature for the nonce data provided by the client.");
                }
            }

            // create client signature
            SignatureData clientSignature = null;
            ISigner       signer          = null;

            switch (this.RemoteEndpoint.SecurityPolicyUri)
            {
            case SecurityPolicyUris.Basic128Rsa15:
            case SecurityPolicyUris.Basic256:
                signer = SignerUtilities.GetSigner("SHA-1withRSA");
                signer.Init(true, this.LocalPrivateKey);
                signer.BlockUpdate(this.RemoteEndpoint.ServerCertificate, 0, this.RemoteEndpoint.ServerCertificate.Length);
                signer.BlockUpdate(this.RemoteNonce, 0, this.RemoteNonce.Length);
                clientSignature = new SignatureData
                {
                    Signature = signer.GenerateSignature(),
                    Algorithm = RsaSha1Signature,
                };

                break;

            case SecurityPolicyUris.Basic256Sha256:
            case SecurityPolicyUris.Aes128_Sha256_RsaOaep:
                signer = SignerUtilities.GetSigner("SHA-256withRSA");
                signer.Init(true, this.LocalPrivateKey);
                signer.BlockUpdate(this.RemoteEndpoint.ServerCertificate, 0, this.RemoteEndpoint.ServerCertificate.Length);
                signer.BlockUpdate(this.RemoteNonce, 0, this.RemoteNonce.Length);
                clientSignature = new SignatureData
                {
                    Signature = signer.GenerateSignature(),
                    Algorithm = RsaSha256Signature,
                };

                break;

            case SecurityPolicyUris.Aes256_Sha256_RsaPss:
                signer = SignerUtilities.GetSigner("SHA-256withRSAandMGF1");
                signer.Init(true, this.LocalPrivateKey);
                signer.BlockUpdate(this.RemoteEndpoint.ServerCertificate, 0, this.RemoteEndpoint.ServerCertificate.Length);
                signer.BlockUpdate(this.RemoteNonce, 0, this.RemoteNonce.Length);
                clientSignature = new SignatureData
                {
                    Signature = signer.GenerateSignature(),
                    Algorithm = RsaPssSha256Signature,
                };

                break;

            default:
                clientSignature = new SignatureData();
                break;
            }

            signer = null;

            // supported UserIdentityToken types are AnonymousIdentityToken, UserNameIdentityToken, IssuedIdentityToken, X509IdentityToken
            UserIdentityToken identityToken  = null;
            SignatureData     tokenSignature = null;

            // if UserIdentity type is IssuedIdentity
            if (this.UserIdentity is IssuedIdentity)
            {
                var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.IssuedToken);
                if (tokenPolicy == null)
                {
                    throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected);
                }

                var             issuedIdentity  = (IssuedIdentity)this.UserIdentity;
                int             plainTextLength = issuedIdentity.TokenData.Length + this.RemoteNonce.Length;
                IBufferedCipher encryptor;
                byte[]          cipherText;
                int             pos;

                var secPolicyUri = tokenPolicy.SecurityPolicyUri ?? this.RemoteEndpoint.SecurityPolicyUri;
                switch (secPolicyUri)
                {
                case SecurityPolicyUris.Basic128Rsa15:
                    encryptor = CipherUtilities.GetCipher("RSA//PKCS1Padding");
                    encryptor.Init(true, this.RemotePublicKey);
                    cipherText    = new byte[encryptor.GetOutputSize(4 + plainTextLength)];
                    pos           = encryptor.ProcessBytes(BitConverter.GetBytes(plainTextLength), cipherText, 0);
                    pos           = encryptor.ProcessBytes(issuedIdentity.TokenData, cipherText, pos);
                    pos           = encryptor.DoFinal(this.RemoteNonce, cipherText, pos);
                    identityToken = new IssuedIdentityToken
                    {
                        TokenData           = cipherText,
                        EncryptionAlgorithm = RsaV15KeyWrap,
                        PolicyId            = tokenPolicy.PolicyId
                    };

                    break;

                case SecurityPolicyUris.Basic256:
                case SecurityPolicyUris.Basic256Sha256:
                case SecurityPolicyUris.Aes128_Sha256_RsaOaep:
                    encryptor = CipherUtilities.GetCipher("RSA//OAEPPADDING");
                    encryptor.Init(true, this.RemotePublicKey);
                    cipherText    = new byte[encryptor.GetOutputSize(4 + plainTextLength)];
                    pos           = encryptor.ProcessBytes(BitConverter.GetBytes(plainTextLength), cipherText, 0);
                    pos           = encryptor.ProcessBytes(issuedIdentity.TokenData, cipherText, pos);
                    pos           = encryptor.DoFinal(this.RemoteNonce, cipherText, pos);
                    identityToken = new IssuedIdentityToken
                    {
                        TokenData           = cipherText,
                        EncryptionAlgorithm = RsaOaepKeyWrap,
                        PolicyId            = tokenPolicy.PolicyId
                    };

                    break;

                case SecurityPolicyUris.Aes256_Sha256_RsaPss:
                    encryptor = CipherUtilities.GetCipher("RSA//OAEPWITHSHA256ANDMGF1PADDING");
                    encryptor.Init(true, this.RemotePublicKey);
                    cipherText    = new byte[encryptor.GetOutputSize(4 + plainTextLength)];
                    pos           = encryptor.ProcessBytes(BitConverter.GetBytes(plainTextLength), cipherText, 0);
                    pos           = encryptor.ProcessBytes(issuedIdentity.TokenData, cipherText, pos);
                    pos           = encryptor.DoFinal(this.RemoteNonce, cipherText, pos);
                    identityToken = new IssuedIdentityToken
                    {
                        TokenData           = cipherText,
                        EncryptionAlgorithm = RsaOaepSha256KeyWrap,
                        PolicyId            = tokenPolicy.PolicyId
                    };

                    break;

                default:
                    identityToken = new IssuedIdentityToken
                    {
                        TokenData           = issuedIdentity.TokenData,
                        EncryptionAlgorithm = null,
                        PolicyId            = tokenPolicy.PolicyId
                    };
                    break;
                }

                tokenSignature = new SignatureData();
                encryptor      = null;
                cipherText     = null;
            }

            // if UserIdentity type is X509Identity
            else if (this.UserIdentity is X509Identity)
            {
                var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.Certificate);
                if (tokenPolicy == null)
                {
                    throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected);
                }

                var x509Identity = (X509Identity)this.UserIdentity;
                identityToken = new X509IdentityToken {
                    CertificateData = x509Identity.Certificate?.GetEncoded(), PolicyId = tokenPolicy.PolicyId
                };

                var secPolicyUri = tokenPolicy.SecurityPolicyUri ?? this.RemoteEndpoint.SecurityPolicyUri;
                switch (secPolicyUri)
                {
                case SecurityPolicyUris.Basic128Rsa15:
                case SecurityPolicyUris.Basic256:
                    signer = SignerUtilities.GetSigner("SHA-1withRSA");
                    signer.Init(true, x509Identity.PrivateKey);
                    signer.BlockUpdate(this.RemoteEndpoint.ServerCertificate, 0, this.RemoteEndpoint.ServerCertificate.Length);
                    signer.BlockUpdate(this.RemoteNonce, 0, this.RemoteNonce.Length);
                    tokenSignature = new SignatureData
                    {
                        Signature = signer.GenerateSignature(),
                        Algorithm = RsaSha1Signature,
                    };

                    break;

                case SecurityPolicyUris.Basic256Sha256:
                case SecurityPolicyUris.Aes128_Sha256_RsaOaep:
                    signer = SignerUtilities.GetSigner("SHA-256withRSA");
                    signer.Init(true, x509Identity.PrivateKey);
                    signer.BlockUpdate(this.RemoteEndpoint.ServerCertificate, 0, this.RemoteEndpoint.ServerCertificate.Length);
                    signer.BlockUpdate(this.RemoteNonce, 0, this.RemoteNonce.Length);
                    tokenSignature = new SignatureData
                    {
                        Signature = signer.GenerateSignature(),
                        Algorithm = RsaSha256Signature,
                    };
                    break;

                case SecurityPolicyUris.Aes256_Sha256_RsaPss:
                    signer = SignerUtilities.GetSigner("SHA-256withRSAandMGF1");
                    signer.Init(true, x509Identity.PrivateKey);
                    signer.BlockUpdate(this.RemoteEndpoint.ServerCertificate, 0, this.RemoteEndpoint.ServerCertificate.Length);
                    signer.BlockUpdate(this.RemoteNonce, 0, this.RemoteNonce.Length);
                    tokenSignature = new SignatureData
                    {
                        Signature = signer.GenerateSignature(),
                        Algorithm = RsaSha256Signature,
                    };
                    break;

                default:
                    tokenSignature = new SignatureData();
                    break;
                }

                signer = null;
            }

            // if UserIdentity type is UserNameIdentity
            else if (this.UserIdentity is UserNameIdentity)
            {
                var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.UserName);
                if (tokenPolicy == null)
                {
                    throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected);
                }

                var             userNameIdentity = (UserNameIdentity)this.UserIdentity;
                byte[]          passwordBytes    = System.Text.Encoding.UTF8.GetBytes(userNameIdentity.Password);
                int             plainTextLength  = passwordBytes.Length + this.RemoteNonce.Length;
                IBufferedCipher encryptor;
                byte[]          cipherText;
                int             pos;

                var secPolicyUri = tokenPolicy.SecurityPolicyUri ?? this.RemoteEndpoint.SecurityPolicyUri;
                switch (secPolicyUri)
                {
                case SecurityPolicyUris.Basic128Rsa15:
                    encryptor = CipherUtilities.GetCipher("RSA//PKCS1Padding");
                    encryptor.Init(true, this.RemotePublicKey);
                    cipherText    = new byte[encryptor.GetOutputSize(4 + plainTextLength)];
                    pos           = encryptor.ProcessBytes(BitConverter.GetBytes(plainTextLength), cipherText, 0);
                    pos           = encryptor.ProcessBytes(passwordBytes, cipherText, pos);
                    pos           = encryptor.DoFinal(this.RemoteNonce, cipherText, pos);
                    identityToken = new UserNameIdentityToken
                    {
                        UserName            = userNameIdentity.UserName,
                        Password            = cipherText,
                        EncryptionAlgorithm = RsaV15KeyWrap,
                        PolicyId            = tokenPolicy.PolicyId
                    };

                    break;

                case SecurityPolicyUris.Basic256:
                case SecurityPolicyUris.Basic256Sha256:
                case SecurityPolicyUris.Aes128_Sha256_RsaOaep:
                    encryptor = CipherUtilities.GetCipher("RSA//OAEPPADDING");
                    encryptor.Init(true, this.RemotePublicKey);
                    cipherText    = new byte[encryptor.GetOutputSize(4 + plainTextLength)];
                    pos           = encryptor.ProcessBytes(BitConverter.GetBytes(plainTextLength), cipherText, 0);
                    pos           = encryptor.ProcessBytes(passwordBytes, cipherText, pos);
                    pos           = encryptor.DoFinal(this.RemoteNonce, cipherText, pos);
                    identityToken = new UserNameIdentityToken
                    {
                        UserName            = userNameIdentity.UserName,
                        Password            = cipherText,
                        EncryptionAlgorithm = RsaOaepKeyWrap,
                        PolicyId            = tokenPolicy.PolicyId
                    };

                    break;

                case SecurityPolicyUris.Aes256_Sha256_RsaPss:
                    encryptor = CipherUtilities.GetCipher("RSA//OAEPWITHSHA256ANDMGF1PADDING");
                    encryptor.Init(true, this.RemotePublicKey);
                    cipherText    = new byte[encryptor.GetOutputSize(4 + plainTextLength)];
                    pos           = encryptor.ProcessBytes(BitConverter.GetBytes(plainTextLength), cipherText, 0);
                    pos           = encryptor.ProcessBytes(passwordBytes, cipherText, pos);
                    pos           = encryptor.DoFinal(this.RemoteNonce, cipherText, pos);
                    identityToken = new UserNameIdentityToken
                    {
                        UserName            = userNameIdentity.UserName,
                        Password            = cipherText,
                        EncryptionAlgorithm = RsaOaepSha256KeyWrap,
                        PolicyId            = tokenPolicy.PolicyId
                    };

                    break;

                default:
                    identityToken = new UserNameIdentityToken
                    {
                        UserName            = userNameIdentity.UserName,
                        Password            = passwordBytes,
                        EncryptionAlgorithm = null,
                        PolicyId            = tokenPolicy.PolicyId
                    };
                    break;
                }

                tokenSignature = new SignatureData();
                passwordBytes  = null;
                encryptor      = null;
                cipherText     = null;
            }

            // if UserIdentity type is AnonymousIdentity or null
            else
            {
                var tokenPolicy = this.RemoteEndpoint.UserIdentityTokens.FirstOrDefault(t => t.TokenType == UserTokenType.Anonymous);
                if (tokenPolicy == null)
                {
                    throw new ServiceResultException(StatusCodes.BadIdentityTokenRejected);
                }

                identityToken = new AnonymousIdentityToken {
                    PolicyId = tokenPolicy.PolicyId
                };
                tokenSignature = new SignatureData();
            }

            var activateSessionRequest = new ActivateSessionRequest
            {
                ClientSignature    = clientSignature,
                LocaleIds          = new[] { CultureInfo.CurrentUICulture.TwoLetterISOLanguageName },
                UserIdentityToken  = identityToken,
                UserTokenSignature = tokenSignature
            };
            var activateSessionResponse = await this.ActivateSessionAsync(activateSessionRequest).ConfigureAwait(false);

            this.RemoteNonce = activateSessionResponse.ServerNonce;

            // fetch namespace array, etc.
            var readValueIds = new ReadValueId[]
            {
                new ReadValueId
                {
                    NodeId      = NodeId.Parse(VariableIds.Server_NamespaceArray),
                    AttributeId = AttributeIds.Value
                },
                new ReadValueId
                {
                    NodeId      = NodeId.Parse(VariableIds.Server_ServerArray),
                    AttributeId = AttributeIds.Value
                }
            };
            var readRequest = new ReadRequest
            {
                NodesToRead = readValueIds
            };

            var readResponse = await this.ReadAsync(readRequest).ConfigureAwait(false);

            if (readResponse.Results.Length == 2)
            {
                if (StatusCode.IsGood(readResponse.Results[0].StatusCode))
                {
                    this.NamespaceUris.Clear();
                    this.NamespaceUris.AddRange(readResponse.Results[0].GetValueOrDefault <string[]>());
                }

                if (StatusCode.IsGood(readResponse.Results[1].StatusCode))
                {
                    this.ServerUris.Clear();
                    this.ServerUris.AddRange(readResponse.Results[1].GetValueOrDefault <string[]>());
                }
            }

            // create the keep alive subscription.
            var subscriptionRequest = new CreateSubscriptionRequest
            {
                RequestedPublishingInterval = DefaultPublishingInterval,
                RequestedMaxKeepAliveCount  = DefaultKeepaliveCount,
                RequestedLifetimeCount      = DefaultKeepaliveCount * 3,
                PublishingEnabled           = true,
            };
            var subscriptionResponse = await this.CreateSubscriptionAsync(subscriptionRequest).ConfigureAwait(false);

            // link up the dataflow blocks
            var id        = subscriptionResponse.SubscriptionId;
            var linkToken = this.LinkTo(this.actionBlock, pr => pr.SubscriptionId == id);

            // start publishing.
            this.stateMachineTask = Task.Run(() => this.StateMachineAsync(this.stateMachineCts.Token));
        }
Ejemplo n.º 24
0
 public XciHeaderSource(ref XciInfo xciInfo, XciMeta xciMeta, ISource rootPartitionFsHeaderHashSource, ICbcModeEncryptor headerEncryptor, ISigner headerSigner)
 {
     this.m_xciInfo = xciInfo;
     this.m_xciMeta = xciMeta;
     this.m_rootPartitionFsHeaderHashSource = rootPartitionFsHeaderHashSource;
     this.m_headerEncryptor = headerEncryptor;
     this.m_headerSigner    = headerSigner;
     this.Size = (long)(XciInfo.PageSize * XciInfo.CardHeaderPageCount);
 }
            internal SignerInfoGeneratorImpl(
                CmsSignedDataStreamGenerator	outer,
                AsymmetricKeyParameter			key,
                SignerIdentifier				signerIdentifier,
                string							digestOID,
                string							encOID,
                CmsAttributeTableGenerator		sAttr,
                CmsAttributeTableGenerator		unsAttr)
            {
                this.outer = outer;

                _signerIdentifier = signerIdentifier;
                _digestOID = digestOID;
                _encOID = encOID;
                _sAttr = sAttr;
                _unsAttr = unsAttr;
                _encName = Helper.GetEncryptionAlgName(_encOID);

                string digestName = Helper.GetDigestAlgName(_digestOID);
                string signatureName = digestName + "with" + _encName;

                if (_sAttr != null)
                {
                    _sig = Helper.GetSignatureInstance(signatureName);
                }
                else
                {
                    // Note: Need to use raw signatures here since we have already calculated the digest
                    if (_encName.Equals("RSA"))
                    {
                        _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));
            }
Ejemplo n.º 26
0
 public PowBlockValidator(IBlockFinalizer blockFinalizer, ITransactionValidator transactionValidator, ITimestamper timestamper, ISigner signer)
 {
     _blockFinalizer       = blockFinalizer ?? throw new ArgumentNullException(nameof(blockFinalizer));
     _transactionValidator = transactionValidator ?? throw new ArgumentNullException(nameof(transactionValidator));
     _timestamper          = timestamper ?? throw new ArgumentNullException(nameof(timestamper));
     _signer = signer ?? throw new ArgumentNullException(nameof(signer));
 }
Ejemplo n.º 27
0
        private OcspReq GenerateRequest(
            DerObjectIdentifier signingAlgorithm,
            AsymmetricKeyParameter privateKey,
            X509Certificate[]               chain,
            SecureRandom random)
        {
            Asn1EncodableVector requests = new Asn1EncodableVector();

            foreach (RequestObject reqObj in list)
            {
                try
                {
                    requests.Add(reqObj.ToRequest());
                }
                catch (Exception e)
                {
                    throw new OcspException("exception creating Request", e);
                }
            }

            TbsRequest tbsReq = new TbsRequest(requestorName, new DerSequence(requests), requestExtensions);

            ISigner   sig       = null;
            Signature signature = null;

            if (signingAlgorithm != null)
            {
                if (requestorName == null)
                {
                    throw new OcspException("requestorName must be specified if request is signed.");
                }

                try
                {
                    sig = SignerUtilities.GetSigner(signingAlgorithm.Id);
                    if (random != null)
                    {
                        sig.Init(true, new ParametersWithRandom(privateKey, random));
                    }
                    else
                    {
                        sig.Init(true, privateKey);
                    }
                }
                catch (Exception e)
                {
                    throw new OcspException("exception creating signature: " + e, e);
                }

                DerBitString bitSig = null;

                try
                {
                    byte[] encoded = tbsReq.GetEncoded();
                    sig.BlockUpdate(encoded, 0, encoded.Length);

                    bitSig = new DerBitString(sig.GenerateSignature());
                }
                catch (Exception e)
                {
                    throw new OcspException("exception processing TBSRequest: " + e, e);
                }

                AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(signingAlgorithm, DerNull.Instance);

                if (chain != null && chain.Length > 0)
                {
                    Asn1EncodableVector v = new Asn1EncodableVector();
                    try
                    {
                        for (int i = 0; i != chain.Length; i++)
                        {
                            v.Add(
                                X509CertificateStructure.GetInstance(
                                    Asn1Object.FromByteArray(chain[i].GetEncoded())));
                        }
                    }
                    catch (IOException e)
                    {
                        throw new OcspException("error processing certs", e);
                    }
                    catch (CertificateEncodingException e)
                    {
                        throw new OcspException("error encoding certs", e);
                    }

                    signature = new Signature(sigAlgId, bitSig, new DerSequence(v));
                }
                else
                {
                    signature = new Signature(sigAlgId, bitSig);
                }
            }

            return(new OcspReq(new OcspRequest(tbsReq, signature)));
        }
Ejemplo n.º 28
0
 IBuilder_HardwareIdentifier IBuilder_Signer.WithSigner(ISigner signer)
 {
     mySigner = signer ?? throw new ArgumentNullException(nameof(signer));
     return(this as IBuilder_HardwareIdentifier);
 }
Ejemplo n.º 29
0
 public abstract Script GenerateScriptSig(Script scriptPubKey, IKeyRepository keyRepo, ISigner signer);
Ejemplo n.º 30
0
 public StandardPublishingIdFormatter(ISigner signer)
 {
     _Signer = signer;
 }
Ejemplo n.º 31
0
 public SigOutputStream(
     ISigner sig)
 {
     this.sig = sig;
 }
Ejemplo n.º 32
0
 /// <summary>
 /// Sign bytes with the given signer
 /// </summary>
 /// <param name="signer">the signer to use</param>
 /// <param name="data">input data</param>
 /// <returns>signature</returns>
 public static byte[] Sign(this ISigner signer, byte[] data)
 {
     signer.Reset();
     signer.BlockUpdate(data, 0, data.Length);
     return(signer.GenerateSignature());
 }
Ejemplo n.º 33
0
        /**
         * Use this constructor if you want to verify a signature using
         * the sub-filter adbe.pkcs7.detached or adbe.pkcs7.sha1.
         * @param contentsKey the /Contents key
         * @param tsp set to true if there's a PAdES LTV time stamp.
         * @param provider the provider or <code>null</code> for the default provider
         */
        public PdfPKCS7(byte[] contentsKey, bool tsp)
        {
            isTsp = tsp;
            Asn1InputStream din = new Asn1InputStream(new MemoryStream(contentsKey));

            //
            // Basic checks to make sure it's a PKCS#7 SignedData Object
            //
            Asn1Object pkcs;

            try {
                pkcs = din.ReadObject();
            }
            catch  {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.decode.pkcs7signeddata.object"));
            }
            if (!(pkcs is Asn1Sequence)) {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.a.sequence"));
            }
            Asn1Sequence signedData = (Asn1Sequence)pkcs;
            DerObjectIdentifier objId = (DerObjectIdentifier)signedData[0];
            if (!objId.Id.Equals(SecurityIDs.ID_PKCS7_SIGNED_DATA))
                throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.signed.data"));
            Asn1Sequence content = (Asn1Sequence)((Asn1TaggedObject)signedData[1]).GetObject();
            // the positions that we care are:
            //     0 - version
            //     1 - digestAlgorithms
            //     2 - possible ID_PKCS7_DATA
            //     (the certificates and crls are taken out by other means)
            //     last - signerInfos

            // the version
            version = ((DerInteger)content[0]).Value.IntValue;

            // the digestAlgorithms
            digestalgos = new Dictionary<string,object>();
            IEnumerator e = ((Asn1Set)content[1]).GetEnumerator();
            while (e.MoveNext())
            {
                Asn1Sequence s = (Asn1Sequence)e.Current;
                DerObjectIdentifier o = (DerObjectIdentifier)s[0];
                digestalgos[o.Id] = null;
            }

            // the certificates and crls
            X509CertificateParser cf = new X509CertificateParser();
            certs = new List<X509Certificate>();
            foreach (X509Certificate cc in cf.ReadCertificates(contentsKey)) {
                certs.Add(cc);
            }
            crls = new List<X509Crl>();

            // the possible ID_PKCS7_DATA
            Asn1Sequence rsaData = (Asn1Sequence)content[2];
            if (rsaData.Count > 1) {
                Asn1OctetString rsaDataContent = (Asn1OctetString)((Asn1TaggedObject)rsaData[1]).GetObject();
                RSAdata = rsaDataContent.GetOctets();
            }

            // the signerInfos
            int next = 3;
            while (content[next] is Asn1TaggedObject)
                ++next;
            Asn1Set signerInfos = (Asn1Set)content[next];
            if (signerInfos.Count != 1)
                throw new ArgumentException(MessageLocalization.GetComposedMessage("this.pkcs.7.object.has.multiple.signerinfos.only.one.is.supported.at.this.time"));
            Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[0];
            // the positions that we care are
            //     0 - version
            //     1 - the signing certificate issuer and serial number
            //     2 - the digest algorithm
            //     3 or 4 - digestEncryptionAlgorithm
            //     4 or 5 - encryptedDigest
            signerversion = ((DerInteger)signerInfo[0]).Value.IntValue;
            // Get the signing certificate
            Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1];
            Org.BouncyCastle.Asn1.X509.X509Name issuer = Org.BouncyCastle.Asn1.X509.X509Name.GetInstance(issuerAndSerialNumber[0]);
            BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value;
            foreach (X509Certificate cert in certs) {
                if (issuer.Equivalent(cert.IssuerDN) && serialNumber.Equals(cert.SerialNumber)) {
                    signCert = cert;
                    break;
                }
            }
            if (signCert == null) {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.find.signing.certificate.with.serial.1",
                    issuer.ToString() + " / " + serialNumber.ToString(16)));
            }
            CalcSignCertificateChain();
            digestAlgorithmOid = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id;
            next = 3;
            if (signerInfo[next] is Asn1TaggedObject) {
                Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next];
                Asn1Set sseq = Asn1Set.GetInstance(tagsig, false);
                sigAttr = sseq.GetEncoded(Asn1Encodable.Der);

                for (int k = 0; k < sseq.Count; ++k) {
                    Asn1Sequence seq2 = (Asn1Sequence)sseq[k];
                    if (((DerObjectIdentifier)seq2[0]).Id.Equals(SecurityIDs.ID_MESSAGE_DIGEST)) {
                        Asn1Set sset = (Asn1Set)seq2[1];
                        digestAttr = ((DerOctetString)sset[0]).GetOctets();
                    }
                    else if (((DerObjectIdentifier)seq2[0]).Id.Equals(SecurityIDs.ID_ADBE_REVOCATION)) {
                        Asn1Set setout = (Asn1Set)seq2[1];
                        Asn1Sequence seqout = (Asn1Sequence)setout[0];
                        for (int j = 0; j < seqout.Count; ++j) {
                            Asn1TaggedObject tg = (Asn1TaggedObject)seqout[j];
                            if (tg.TagNo == 1) {
                                Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                                FindOcsp(seqin);
                            }
                            if (tg.TagNo == 0) {
                                Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                                FindCRL(seqin);
                            }
                        }
                    }
                }
                if (digestAttr == null)
                    throw new ArgumentException(MessageLocalization.GetComposedMessage("authenticated.attribute.is.missing.the.digest"));
                ++next;
            }
            digestEncryptionAlgorithmOid = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id;
            digest = ((Asn1OctetString)signerInfo[next++]).GetOctets();
            if (next < signerInfo.Count && (signerInfo[next] is DerTaggedObject)) {
                Asn1TaggedObject taggedObject = (Asn1TaggedObject) signerInfo[next];
                Asn1Set unat = Asn1Set.GetInstance(taggedObject, false);
                Org.BouncyCastle.Asn1.Cms.AttributeTable attble = new Org.BouncyCastle.Asn1.Cms.AttributeTable(unat);
                Org.BouncyCastle.Asn1.Cms.Attribute ts = attble[PkcsObjectIdentifiers.IdAASignatureTimeStampToken];
                if (ts != null && ts.AttrValues.Count > 0) {
                    Asn1Set attributeValues = ts.AttrValues;
                    Asn1Sequence tokenSequence = Asn1Sequence.GetInstance(attributeValues[0]);
                    Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(tokenSequence);
                    this.timeStampToken = new TimeStampToken(contentInfo);
                }
            }
            if (isTsp) {
                Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfoTsp = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(signedData);
                this.timeStampToken = new TimeStampToken(contentInfoTsp);
                TimeStampTokenInfo info = timeStampToken.TimeStampInfo;
                String algOID = info.MessageImprintAlgOid;
                messageDigest = DigestUtilities.GetDigest(algOID);
            }
            else {
                if (RSAdata != null || digestAttr != null) {
                    messageDigest = GetHashClass();
                    encContDigest = GetHashClass();
                }
                sig = SignerUtilities.GetSigner(GetDigestAlgorithm());
                sig.Init(false, signCert.GetPublicKey());
            }
        }
Ejemplo n.º 34
0
 /// <summary>
 /// Verify data with the given signer and signature
 /// </summary>
 /// <param name="signer">the signer to use</param>
 /// <param name="data">input data</param>
 /// <param name="signature">signature</param>
 /// <returns>validity</returns>
 public static bool Verify(this ISigner signer, byte[] data, byte[] signature)
 {
     signer.Reset();
     signer.BlockUpdate(data, 0, data.Length);
     return(signer.VerifySignature(signature));
 }
Ejemplo n.º 35
0
        private bool VerifyDigest(
            byte[]                                  digest,
            AsymmetricKeyParameter key,
            byte[]                                  signature)
        {
            string algorithm = Helper.GetEncryptionAlgName(this.EncryptionAlgOid);

            try
            {
                if (algorithm.Equals("RSA"))
                {
                    IBufferedCipher c = CmsEnvelopedHelper.Instance.CreateAsymmetricCipher("RSA/ECB/PKCS1Padding");

                    c.Init(false, key);

                    byte[] decrypt = c.DoFinal(signature);

                    DigestInfo digInfo = DerDecode(decrypt);

                    if (!digInfo.AlgorithmID.ObjectID.Equals(digestAlgorithm.ObjectID))
                    {
                        return(false);
                    }

                    if (!IsNull(digInfo.AlgorithmID.Parameters))
                    {
                        return(false);
                    }

                    byte[] sigHash = digInfo.GetDigest();

                    return(Arrays.ConstantTimeAreEqual(digest, sigHash));
                }
                else if (algorithm.Equals("DSA"))
                {
                    ISigner sig = SignerUtilities.GetSigner("NONEwithDSA");

                    sig.Init(false, key);

                    sig.BlockUpdate(digest, 0, digest.Length);

                    return(sig.VerifySignature(signature));
                }
                else
                {
                    throw new CmsException("algorithm: " + algorithm + " not supported in base signatures.");
                }
            }
            catch (SecurityUtilityException e)
            {
                throw e;
            }
            catch (GeneralSecurityException e)
            {
                throw new CmsException("Exception processing signature: " + e, e);
            }
            catch (IOException e)
            {
                throw new CmsException("Exception decoding signature: " + e, e);
            }
        }
Ejemplo n.º 36
0
 public override Script GenerateScriptSig(Script scriptPubKey, IKeyRepository keyRepo, ISigner signer)
 {
     return(Script.Empty);
 }
Ejemplo n.º 37
0
        public override Script GenerateScriptSig(Script scriptPubKey, IKeyRepository keyRepo, ISigner signer)
        {
            var key = keyRepo.FindKey(scriptPubKey);

            if (key == null)
            {
                return(null);
            }
            var sig = signer.Sign(key);

            return(PayToPubkeyTemplate.Instance.GenerateScriptSig(sig));
        }
Ejemplo n.º 38
0
 internal SigCalculator(ISigner sig)
 {
     this.sig    = sig;
     this.stream = new SignerBucket(sig);
 }
 private void SaveSignerToFile(ISigner signer, string signerPath)
 {
     _log.Debug("Saving signer");
     using (var signerStream = File.OpenWrite(signerPath))
         signer.Save(signerStream);
 }
Ejemplo n.º 40
0
        /// <summary>
        /// Returns a key-value pair that represents the Simple HTTP resource path that
        /// needs to be configured (the key) and the resource content that should be returned
        /// for an HTTP request for this path on a server that the target DNS resolve to.
        /// </summary>
        /// <param name="dnsId"></param>
        /// <param name="signer"></param>
        /// <param name="tls"></param>
        /// <returns></returns>
        public KeyValuePair<string, string> GenerateHttpChallengeAnswer(string dnsId, ISigner signer, bool tls)
        {
            var resp = new
            {
                type = "simpleHttp",
                token = Token,
                tls = tls
            };
            var json = JsonConvert.SerializeObject(resp);
            var hdrs = new { alg = signer.JwsAlg, jwk = signer.ExportJwk() };
            var signed = JwsHelper.SignFlatJsonAsObject(
                    signer.Sign, json, unprotectedHeaders: hdrs);

            return new KeyValuePair<string, string>(
                    $"{HTTP_CHALLENGE_PATHPREFIX}{Token}",
                    JsonConvert.SerializeObject(signed, Formatting.Indented));
        }
			internal SignerInf(
				CmsSignedDataStreamGenerator	outer,
				AsymmetricKeyParameter			key,
				byte[]							subjectKeyID,
				string							digestOID,
				string							encOID,
				CmsAttributeTableGenerator		sAttr,
				CmsAttributeTableGenerator		unsAttr,
				ISigner							signature)
	        {
				this.outer = outer;

	            _key = key;
	            _subjectKeyID = subjectKeyID;
	            _digestOID = digestOID;
	            _encOID = encOID;
	            _sAttr = sAttr;
	            _unsAttr = unsAttr;
	            _signature = signature;
	        }
Ejemplo n.º 42
0
        /*
         * we generate a self signed certificate for the sake of testing - SHA224withECDSA
         */
        private void createECRequest(
            string algorithm,
            DerObjectIdentifier algOid)
        {
            FPCurve curve = new FPCurve(
                new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p)
                new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16),                      // a
                new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16));                     // b

            ECDomainParameters spec = new ECDomainParameters(
                curve,
//				curve.DecodePoint(Hex.Decode("02C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G
                curve.DecodePoint(Hex.Decode("0200C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")),     // G
                new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16));                 // n

            ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(
                new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"),                 // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
//				curve.DecodePoint(Hex.Decode("026BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
                curve.DecodePoint(Hex.Decode("02006BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")),                 // Q
                spec);

//			//
//			// set up the keys
//			//
//			IAsymmetricKeyParameter privKey;
//			IAsymmetricKeyParameter pubKey;
//
//			KeyFactory fact = KeyFactory.getInstance("ECDSA");
//
//			privKey = fact.generatePrivate(privKeySpec);
//			pubKey = fact.generatePublic(pubKeySpec);

            Pkcs10CertificationRequest req = new Pkcs10CertificationRequest(
                algorithm, new X509Name("CN=XXX"), pubKey, null, privKey);

            if (!req.Verify())
            {
                Fail("Failed Verify check EC.");
            }

            req = new Pkcs10CertificationRequest(req.GetEncoded());
            if (!req.Verify())
            {
                Fail("Failed Verify check EC encoded.");
            }

            //
            // try with point compression turned off
            //
//			((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED");
            FPPoint q = (FPPoint)pubKey.Q;

            pubKey = new ECPublicKeyParameters(
                pubKey.AlgorithmName,
                new FPPoint(q.Curve, q.X, q.Y, false),
                pubKey.Parameters);

            req = new Pkcs10CertificationRequest(
                algorithm, new X509Name("CN=XXX"), pubKey, null, privKey);
            if (!req.Verify())
            {
                Fail("Failed Verify check EC uncompressed.");
            }

            req = new Pkcs10CertificationRequest(req.GetEncoded());
            if (!req.Verify())
            {
                Fail("Failed Verify check EC uncompressed encoded.");
            }

            if (!req.SignatureAlgorithm.ObjectID.Equals(algOid))
            {
                Fail("ECDSA oid incorrect.");
            }

            if (req.SignatureAlgorithm.Parameters != null)
            {
                Fail("ECDSA parameters incorrect.");
            }

            ISigner sig = SignerUtilities.GetSigner(algorithm);

            sig.Init(false, pubKey);

            byte[] b = req.GetCertificationRequestInfo().GetEncoded();
            sig.BlockUpdate(b, 0, b.Length);

            if (!sig.VerifySignature(req.Signature.GetBytes()))
            {
                Fail("signature not mapped correctly.");
            }
        }
//        /// <summary>
//        /// Get the Der Encoded Pkcs10 Certification Request.
//        /// </summary>
//        /// <returns>A byte array.</returns>
//        public byte[] GetEncoded()
//        {
//        	return new CertificationRequest(reqInfo, sigAlgId, sigBits).GetDerEncoded();
//        }

		// TODO Figure out how to set parameters on an ISigner
		private void SetSignatureParameters(
			ISigner			signature,
			Asn1Encodable	asn1Params)
		{
			if (asn1Params != null && !(asn1Params is Asn1Null))
			{
//				AlgorithmParameters sigParams = AlgorithmParameters.GetInstance(signature.getAlgorithm());
//
//				try
//				{
//					sigParams.init(asn1Params.ToAsn1Object().GetDerEncoded());
//				}
//				catch (IOException e)
//				{
//					throw new SignatureException("IOException decoding parameters: " + e.Message);
//				}

				if (signature.AlgorithmName.EndsWith("MGF1"))
				{
					throw Platform.CreateNotImplementedException("signature algorithm with MGF1");

//					try
//					{
//						signature.setParameter(sigParams.getParameterSpec(PSSParameterSpec.class));
//					}
//					catch (GeneralSecurityException e)
//					{
//						throw new SignatureException("Exception extracting parameters: " + e.getMessage());
//					}
				}
			}
		}
Ejemplo n.º 44
0
 /**
 * Verifies a signature using the sub-filter adbe.pkcs7.detached or
 * adbe.pkcs7.sha1.
 * @param contentsKey the /Contents key
 * @param provider the provider or <code>null</code> for the default provider
 * @throws SecurityException on error
 * @throws CRLException on error
 * @throws InvalidKeyException on error
 * @throws CertificateException on error
 * @throws NoSuchProviderException on error
 * @throws NoSuchAlgorithmException on error
 */    
 public PdfPKCS7(byte[] contentsKey) {
     Asn1InputStream din = new Asn1InputStream(new MemoryStream(contentsKey));
     
     //
     // Basic checks to make sure it's a PKCS#7 SignedData Object
     //
     Asn1Object pkcs;
     
     try {
         pkcs = din.ReadObject();
     }
     catch  {
         throw new ArgumentException("can't decode PKCS7SignedData object");
     }
     if (!(pkcs is Asn1Sequence)) {
         throw new ArgumentException("Not a valid PKCS#7 object - not a sequence");
     }
     Asn1Sequence signedData = (Asn1Sequence)pkcs;
     DerObjectIdentifier objId = (DerObjectIdentifier)signedData[0];
     if (!objId.Id.Equals(ID_PKCS7_SIGNED_DATA))
         throw new ArgumentException("Not a valid PKCS#7 object - not signed data");
     Asn1Sequence content = (Asn1Sequence)((DerTaggedObject)signedData[1]).GetObject();
     // the positions that we care are:
     //     0 - version
     //     1 - digestAlgorithms
     //     2 - possible ID_PKCS7_DATA
     //     (the certificates and crls are taken out by other means)
     //     last - signerInfos
     
     // the version
     version = ((DerInteger)content[0]).Value.IntValue;
     
     // the digestAlgorithms
     digestalgos = new Hashtable();
     IEnumerator e = ((Asn1Set)content[1]).GetEnumerator();
     while (e.MoveNext())
     {
         Asn1Sequence s = (Asn1Sequence)e.Current;
         DerObjectIdentifier o = (DerObjectIdentifier)s[0];
         digestalgos[o.Id] = null;
     }
     
     // the certificates and crls
     X509CertificateParser cf = new X509CertificateParser();
     certs = new ArrayList();
     foreach (X509Certificate cc in cf.ReadCertificates(contentsKey)) {
         certs.Add(cc);
     }
     crls = new ArrayList();
     
     // the possible ID_PKCS7_DATA
     Asn1Sequence rsaData = (Asn1Sequence)content[2];
     if (rsaData.Count > 1) {
         DerOctetString rsaDataContent = (DerOctetString)((DerTaggedObject)rsaData[1]).GetObject();
         RSAdata = rsaDataContent.GetOctets();
     }
     
     // the signerInfos
     int next = 3;
     while (content[next] is DerTaggedObject)
         ++next;
     Asn1Set signerInfos = (Asn1Set)content[next];
     if (signerInfos.Count != 1)
         throw new ArgumentException("This PKCS#7 object has multiple SignerInfos - only one is supported at this time");
     Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[0];
     // the positions that we care are
     //     0 - version
     //     1 - the signing certificate serial number
     //     2 - the digest algorithm
     //     3 or 4 - digestEncryptionAlgorithm
     //     4 or 5 - encryptedDigest
     signerversion = ((DerInteger)signerInfo[0]).Value.IntValue;
     // Get the signing certificate
     Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1];
     BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value;
     foreach (X509Certificate cert in certs) {                                                            
         if (serialNumber.Equals(cert.SerialNumber)) {
             signCert = cert;                                                                             
             break;                                                                                            
         }                                                                                                
     }
     if (signCert == null) {
         throw new ArgumentException("Can't find signing certificate with serial " + serialNumber.ToString(16));
     }
     CalcSignCertificateChain();
     digestAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id;
     next = 3;
     if (signerInfo[next] is Asn1TaggedObject) {
         Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next];
         Asn1Set sseq = Asn1Set.GetInstance(tagsig, false);
         sigAttr = sseq.GetEncoded(Asn1Encodable.Der);
         
         for (int k = 0; k < sseq.Count; ++k) {
             Asn1Sequence seq2 = (Asn1Sequence)sseq[k];
             if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_MESSAGE_DIGEST)) {
                 Asn1Set sset = (Asn1Set)seq2[1];
                 digestAttr = ((DerOctetString)sset[0]).GetOctets();
             }
             else if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_ADBE_REVOCATION)) {
                 Asn1Set setout = (Asn1Set)seq2[1];
                 Asn1Sequence seqout = (Asn1Sequence)setout[0];
                 for (int j = 0; j < seqout.Count; ++j) {
                     Asn1TaggedObject tg = (Asn1TaggedObject)seqout[j];
                     if (tg.TagNo != 1)
                         continue;
                     Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                     FindOcsp(seqin);
                 }
             }
         }
         if (digestAttr == null)
             throw new ArgumentException("Authenticated attribute is missing the digest.");
         ++next;
     }
     digestEncryptionAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id;
     digest = ((DerOctetString)signerInfo[next++]).GetOctets();
     if (next < signerInfo.Count && (signerInfo[next] is DerTaggedObject)) {
         DerTaggedObject taggedObject = (DerTaggedObject) signerInfo[next];
         Asn1Set unat = Asn1Set.GetInstance(taggedObject, false);
         Org.BouncyCastle.Asn1.Cms.AttributeTable attble = new Org.BouncyCastle.Asn1.Cms.AttributeTable(unat);
         Org.BouncyCastle.Asn1.Cms.Attribute ts = attble[PkcsObjectIdentifiers.IdAASignatureTimeStampToken];
         if (ts != null) {
             Asn1Set attributeValues = ts.AttrValues;
             Asn1Sequence tokenSequence = Asn1Sequence.GetInstance(attributeValues[0]);
             Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(tokenSequence);
             this.timeStampToken = new TimeStampToken(contentInfo);
         }
     }
     if (RSAdata != null || digestAttr != null) {
         messageDigest = GetHashClass();
     }
     sig = SignerUtilities.GetSigner(GetDigestAlgorithm());
     sig.Init(false, signCert.GetPublicKey());
 }
 private void LoadSignerFromFile(ISigner signer, string signerPath)
 {
     _log.Debug("Loading signer from {signerPath}", signerPath);
     using (var signerStream = File.OpenRead(signerPath))
         signer.Load(signerStream);
 }
Ejemplo n.º 46
0
 public SigOutputStream(ISigner sig)
 {
     this.sig = sig;
 }
Ejemplo n.º 47
0
		private void checkSignature(
			int						size,
			ECPrivateKeyParameters	sKey,
			ECPublicKeyParameters	vKey,
			ISigner					sgr,
			SecureRandom			k,
			byte[]					message,
			BigInteger				r,
			BigInteger				s)
		{
			sgr.Init(true, new ParametersWithRandom(sKey, k));

			sgr.BlockUpdate(message, 0, message.Length);

			byte[] sigBytes = sgr.GenerateSignature();

			sgr.Init(false, vKey);

			sgr.BlockUpdate(message, 0, message.Length);

			if (!sgr.VerifySignature(sigBytes))
			{
				Fail(size + " bit EC verification failed");
			}

			BigInteger[] sig = derDecode(sigBytes);

			if (!r.Equals(sig[0]))
			{
				Fail(size + "bit"
					+ ": r component wrong." + SimpleTest.NewLine
					+ " expecting: " + r + SimpleTest.NewLine
					+ " got      : " + sig[0]);
			}

			if (!s.Equals(sig[1]))
			{
				Fail(size + "bit"
					+ ": s component wrong." + SimpleTest.NewLine
					+ " expecting: " + s + SimpleTest.NewLine
					+ " got      : " + sig[1]);
			}
		}
Ejemplo n.º 48
0
 public MDLPClientAdapter(UnityContainer unityContainer, ILogger log, ISigner signer, ISettingProvider setting) :
     base(unityContainer, log, signer, setting)
 {
 }
Ejemplo n.º 49
0
        /// <summary>
        /// Computes the JWS-signed ACME request body for the given message object
        /// and signer instance.
        /// </summary>
        /// <param name="message"></param>
        /// <param name="signer"></param>
        /// <returns></returns>
        private string ComputeAcmeSigned(object message, ISigner signer)
        {
            var protectedHeader = new
            {
                nonce = NextNonce
            };
            var unprotectedHeader = new
            {
                alg = Signer.JwsAlg,
                jwk = Signer.ExportJwk()
            };

            var payload = string.Empty;
            if (message is JObject)
                payload = ((JObject)message).ToString(Formatting.None);
            else
                payload = JsonConvert.SerializeObject(message, Formatting.None);

            var acmeSigned = JwsHelper.SignFlatJson(Signer.Sign, payload,
                    protectedHeader, unprotectedHeader);

            return acmeSigned;
        }
Ejemplo n.º 50
0
 public abstract HttpRequest SignRequest(ISigner signer, Credential credential,
                                         FormatType?format, ProductDomain domain);
Ejemplo n.º 51
0
        // Constructors for creating new signatures
        /**
         * Assembles all the elements needed to create a signature, except for the data.
         * @param privKey the private key
         * @param certChain the certificate chain
         * @param crlList the certificate revocation list
         * @param hashAlgorithm the hash algorithm
         * @param provider the provider or <code>null</code> for the default provider
         * @param hasRSAdata <CODE>true</CODE> if the sub-filter is adbe.pkcs7.sha1
         * @throws InvalidKeyException on error
         * @throws NoSuchProviderException on error
         * @throws NoSuchAlgorithmException on error
         */
        public PdfPKCS7(ICipherParameters privKey, ICollection<X509Certificate> certChain, 
                        String hashAlgorithm, bool hasRSAdata)
        {
            digestAlgorithmOid = DigestAlgorithms.GetAllowedDigests(hashAlgorithm);
            if (digestAlgorithmOid == null)
                throw new ArgumentException(MessageLocalization.GetComposedMessage("unknown.hash.algorithm.1", hashAlgorithm));

            version = signerversion = 1;
            certs = new List<X509Certificate>(certChain);
            crls = new List<X509Crl>();
            digestalgos = new Dictionary<string,object>();
            digestalgos[digestAlgorithmOid] = null;

            //
            // Copy in the certificates and crls used to sign the private key.
            //
            signCert = certs[0];

            if (privKey != null) {
                //
                // Now we have private key, find out what the digestEncryptionAlgorithm is.
                //
                if (privKey is RsaKeyParameters)
                    digestEncryptionAlgorithmOid = SecurityIDs.ID_RSA;
                else if (privKey is DsaKeyParameters)
                    digestEncryptionAlgorithmOid = SecurityIDs.ID_DSA;
                else
                    throw new ArgumentException(MessageLocalization.GetComposedMessage("unknown.key.algorithm.1", privKey.ToString()));

            }
            if (hasRSAdata) {
                RSAdata = new byte[0];
                messageDigest = GetHashClass();
            }

            if (privKey != null) {
                sig = SignerUtilities.GetSigner(GetDigestAlgorithm());
                sig.Init(true, privKey);
            }
        }
Ejemplo n.º 52
0
        private static bool SignFile(ref string filename)
        {
            Signing s = new Signing();

            if (!s.LoadFile(filename))
            {
                Console.WriteLine("error loading xml file:" + filename);
                Environment.Exit(-1);
                return(false);
            }


            AsymmetricKeyEntry key = null;

            Org.BouncyCastle.X509.X509Certificate cert = null;

            try
            {
                string signercert = ConfigurationManager.AppSettings["signercert"].ToString();
                string signerpwd  = ConfigurationManager.AppSettings["signerpwd"].ToString();


                FileStream  fs    = new FileStream(signercert, FileMode.Open, FileAccess.Read);
                Pkcs12Store store = new Pkcs12Store(fs, signerpwd.ToCharArray());

                string pName = null;
                foreach (string n in store.Aliases)
                {
                    if (store.IsKeyEntry(n))
                    {
                        pName = n;
                        break;
                    }
                }
                key  = store.GetKey(pName);
                cert = store.GetCertificate(pName).Certificate;
            }
            catch (Exception)
            {
                Console.WriteLine("error loading signer (config)");
                Environment.Exit(-1);
                return(false);
            }

            if ((null == key) || (null == cert))
            {
                Console.WriteLine("error loading signer (config) (2)");
                Environment.Exit(-1);
                return(false);
            }


            string signedxml = "";

            try
            {
                byte[] tobesigned = s.AddSignature(cert);

                // sha256WithRSAEncryption
                DerObjectIdentifier signingAlgo = new DerObjectIdentifier("1.2.840.113549.1.1.11");
                ISigner             signer      = SignerUtilities.GetSigner(signingAlgo);
                signer.Init(true, key.Key);
                signer.BlockUpdate(tobesigned, 0, tobesigned.Length);
                byte[] signed = signer.GenerateSignature();
                s.SetSignature(signed);
                signedxml = s.GetXml();
            }
            catch (Exception)
            {
                Console.WriteLine("error signing xml");
                Environment.Exit(-1);
                return(false);
            }

            filename += ".sig";

            File.WriteAllText(filename, signedxml);
            return(true);
        }
Ejemplo n.º 53
0
		private void GetSig()
        {
            this.sig = SignerUtilities.GetSigner(
				PgpUtilities.GetSignatureName(sigPck.KeyAlgorithm, sigPck.HashAlgorithm));
        }
Ejemplo n.º 54
0
        public IStreamCalculator CreateCalculator()
        {
            ISigner signer = SignerUtilities.InitSigner(algorithm, true, privateKey, random);

            return(new DefaultSignatureCalculator(signer));
        }
Ejemplo n.º 55
0
 internal static void SetSignatureParameters(ISigner signature, Asn1Encodable parameters)
 {
     if (parameters != null && derNull.Equals(parameters))
     {
     }
 }
Ejemplo n.º 56
0
        public override Script GenerateScriptSig(Network network, Script scriptPubKey, IKeyRepository keyRepo, ISigner signer)
        {
            KeyId parameters = PayToPubkeyHashTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey);
            Key   key        = keyRepo.FindKey(parameters.ScriptPubKey);

            if (key == null)
            {
                return(null);
            }
            TransactionSignature sig = signer.Sign(key);

            return(PayToPubkeyHashTemplate.Instance.GenerateScriptSig(sig, key.PubKey));
        }
Ejemplo n.º 57
0
        /**
        * Verifies a signature using the sub-filter adbe.x509.rsa_sha1.
        * @param contentsKey the /Contents key
        * @param certsKey the /Cert key
        * @param provider the provider or <code>null</code> for the default provider
        */    
        public PdfPKCS7(byte[] contentsKey, byte[] certsKey) {

            X509CertificateParser cf = new X509CertificateParser();
            certs = new ArrayList();
            foreach (X509Certificate cc in cf.ReadCertificates(certsKey)) {
                certs.Add(cc);
            }
            signCerts = certs;
            signCert = (X509Certificate)certs[0];
            crls = new ArrayList();
            Asn1InputStream inp = new Asn1InputStream(new MemoryStream(contentsKey));
            digest = ((DerOctetString)inp.ReadObject()).GetOctets();
            sig = SignerUtilities.GetSigner("SHA1withRSA");
            sig.Init(false, signCert.GetPublicKey());
        }
Ejemplo n.º 58
0
 IVerifier_ApplicationCode IVerifier_Signer.WithSigner(ISigner signer)
 {
     mySigner = signer ?? throw new ArgumentNullException(nameof(signer));
     return(this);
 }
Ejemplo n.º 59
0
        /**
        * Generates a signature.
        * @param privKey the private key
        * @param certChain the certificate chain
        * @param crlList the certificate revocation list
        * @param hashAlgorithm the hash algorithm
        * @param provider the provider or <code>null</code> for the default provider
        * @param hasRSAdata <CODE>true</CODE> if the sub-filter is adbe.pkcs7.sha1
        * @throws SecurityException on error
        * @throws InvalidKeyException on error
        * @throws NoSuchProviderException on error
        * @throws NoSuchAlgorithmException on error
        */    
        public PdfPKCS7(ICipherParameters privKey, X509Certificate[] certChain, object[] crlList,
                        String hashAlgorithm, bool hasRSAdata) {
            this.privKey = privKey;
            
            digestAlgorithm = (String)allowedDigests[hashAlgorithm.ToUpper(CultureInfo.InvariantCulture)];
            if (digestAlgorithm == null)
                throw new ArgumentException("Unknown Hash Algorithm "+hashAlgorithm);
            
            version = signerversion = 1;
            certs = new ArrayList();
            crls = new ArrayList();
            digestalgos = new Hashtable();
            digestalgos[digestAlgorithm] = null;
            
            //
            // Copy in the certificates and crls used to sign the private key.
            //
            signCert = certChain[0];
            for (int i = 0;i < certChain.Length;i++) {
                certs.Add(certChain[i]);
            }
            
//            if (crlList != null) {
//                for (int i = 0;i < crlList.length;i++) {
//                    crls.Add(crlList[i]);
//                }
//            }
            
            if (privKey != null) {
                //
                // Now we have private key, find out what the digestEncryptionAlgorithm is.
                //
                if (privKey is RsaKeyParameters)
                    digestEncryptionAlgorithm = ID_RSA;
                else if (privKey is DsaKeyParameters)
                    digestEncryptionAlgorithm = ID_DSA;
                else
                    throw new ArgumentException("Unknown Key Algorithm "+privKey.ToString());

            }
            if (hasRSAdata) {
                RSAdata = new byte[0];
                messageDigest = GetHashClass();
            }

            if (privKey != null) {
                sig = SignerUtilities.GetSigner(GetDigestAlgorithm());
                sig.Init(true, privKey);
            }
        }
Ejemplo n.º 60
0
        /// <summary>
        /// Instantiate a Pkcs10CertificationRequest object with the necessary credentials.
        /// </summary>
        ///<param name="signatureAlgorithm">Name of Sig Alg.</param>
        /// <param name="subject">X509Name of subject eg OU="My unit." O="My Organisatioin" C="au" </param>
        /// <param name="publicKey">Public Key to be included in cert reqest.</param>
        /// <param name="attributes">ASN1Set of Attributes.</param>
        /// <param name="signingKey">Matching Private key for nominated (above) public key to be used to sign the request.</param>
        public Pkcs10CertificationRequest(
            string signatureAlgorithm,
            X509Name subject,
            AsymmetricKeyParameter publicKey,
            Asn1Set attributes,
            AsymmetricKeyParameter signingKey)
        {
            if (signatureAlgorithm == null)
            {
                throw new ArgumentNullException("signatureAlgorithm");
            }
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }
            if (publicKey == null)
            {
                throw new ArgumentNullException("publicKey");
            }
            if (publicKey.IsPrivate)
            {
                throw new ArgumentException("expected public key", "publicKey");
            }
            if (!signingKey.IsPrivate)
            {
                throw new ArgumentException("key for signing must be private", "signingKey");
            }

//			DerObjectIdentifier sigOid = SignerUtilities.GetObjectIdentifier(signatureAlgorithm);
            string algorithmName       = signatureAlgorithm.ToUpper(CultureInfo.InvariantCulture);
            DerObjectIdentifier sigOid = (DerObjectIdentifier)algorithms[algorithmName];

            if (sigOid == null)
            {
                try
                {
                    sigOid = new DerObjectIdentifier(algorithmName);
                }
                catch (Exception e)
                {
                    throw new ArgumentException("Unknown signature type requested", e);
                }
            }

            if (noParams.Contains(sigOid))
            {
                this.sigAlgId = new AlgorithmIdentifier(sigOid);
            }
            else if (exParams.Contains(algorithmName))
            {
                this.sigAlgId = new AlgorithmIdentifier(sigOid, (Asn1Encodable)exParams[algorithmName]);
            }
            else
            {
                this.sigAlgId = new AlgorithmIdentifier(sigOid, DerNull.Instance);
            }

            SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

            this.reqInfo = new CertificationRequestInfo(subject, pubInfo, attributes);

            ISigner sig = SignerUtilities.GetSigner(signatureAlgorithm);

            sig.Init(true, signingKey);

            try
            {
                // Encode.
                byte[] b = reqInfo.GetDerEncoded();
                sig.BlockUpdate(b, 0, b.Length);
            }
            catch (Exception e)
            {
                throw new ArgumentException("exception encoding TBS cert request", e);
            }

            // Generate Signature.
            sigBits = new DerBitString(sig.GenerateSignature());
        }