/// <summary>
		/// Sender rejects signer's attachment requirement with a comment.
		/// </summary>
		/// <param name="packageId">Package identifier.</param>
		/// <param name="signer">Signer.</param>
		/// <param name="attachmentId">Attachment identifier.</param>
		/// <param name="senderComment">Sender comment.</param>
        public void RejectAttachment(PackageId packageId, Signer signer, String attachmentId, String senderComment)
        {
            signer.Attachments[attachmentId].SenderComment = senderComment;
            signer.Attachments[attachmentId].Status = RequirementStatus.REJECTED;
            Role apiRole = new SignerConverter(signer).ToAPIRole(System.Guid.NewGuid().ToString());
            
            apiClient.RejectAttachment(packageId.Id, apiRole);
        }
		/// <summary>
		/// Sender accepts signer's attachment requirement.
		/// </summary>
		/// <param name="packageId">Package identifier.</param>
		/// <param name="signer">Signer.</param>
		/// <param name="attachmentId">Attachment identifier.</param>
		public void AcceptAttachment(PackageId packageId, Signer signer, String attachmentId)
        {
            signer.Attachments[attachmentId].SenderComment = "";
            signer.Attachments[attachmentId].Status = Silanis.ESL.SDK.RequirementStatus.COMPLETE;
            
            Role apiRole = new SignerConverter(signer).ToAPIRole(System.Guid.NewGuid().ToString());
            
            apiClient.AcceptAttachment(packageId.Id, apiRole);
        }
        public void can_sign_and_unsign_value() {
            var signer = new Signer("testing");

            var signed = signer.Sign("hello world");

            var unsigned = signer.Unsign(signed);

            unsigned.ShouldBe("hello world");
        }
        public void tampered_value_throws() {
            var signer = new Signer("testing");

            var signed = signer.Sign("hello world");

            signed = "!" + signed;

            Assert.Throws<BadSignatureException>(() => {
                var unsigned = signer.Unsign(signed);
                Assert.False(true);
            });
        }
 public void TestSignImport([Values("rsa", "dsa")] String keyType, [Values("pem", "der")] String fileFormat)
 {
     using (var signer = new Signer(Util.TestDataPath(TEST_DATA, keyType + "-sign")))
     {
         var signature = signer.Sign(input);
         using (
             var keyset = ImportedKeySet.Import.X509Certificate(KeyPurpose.Verify,
                                                                Util.TestDataPath(TEST_DATA,
                                                                                  keyType + "-sign-crt." +
                                                                                  fileFormat)))
         using (var verifier = new Verifier(keyset))
         {
             Expect(verifier.Verify(input, signature), Is.True);
         }
     }
 }
示例#6
0
        public void TestBadSigs(String subDir, string nestDir)
        {
            using (var signer = new Signer(Util.TestDataPath(TEST_DATA, subDir, nestDir)))
            {
                byte[] sig = signer.Sign(inputBytes);

                // Another input string should not verify
                Assert.That(signer.Verify(Encoding.UTF8.GetBytes("Some other string"), sig), Is.False);
                Expect(() => signer.Verify(inputBytes, new byte[0]), Throws.TypeOf<InvalidCryptoDataException>());
                sig[0] ^= 23;
                Expect(() => signer.Verify(inputBytes, sig), Throws.TypeOf<InvalidCryptoVersionException>());
                Expect(() => signer.Verify(inputBytes, sig), Throws.TypeOf<InvalidCryptoVersionException>());
                sig[0] ^= 23;
                sig[1] ^= 45;
                Expect(signer.Verify(inputBytes, sig), Is.False);
            }
        }
示例#7
0
        internal static EnvelopeTemplate CreateDefaultTemplate(string templateName = null)
        {
            // Read a file from disk to use as a document.

            EnvelopeTemplate templateDef = new EnvelopeTemplate();
            byte[] fileBytes = File.ReadAllBytes(TestConfig.SignTest1File);

            templateDef.EmailSubject = "Template " + DateTime.Now.ToString();
            templateDef.EnvelopeTemplateDefinition = new EnvelopeTemplateDefinition();

            string tempName = templateName;
            if (tempName == null) tempName = "Template Name " + DateTime.Now.ToString();
            templateDef.EnvelopeTemplateDefinition.Name = tempName;

            Document doc = new Document();
            doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes);
            doc.Name = "TestFile.pdf";
            doc.DocumentId = "1";

            templateDef.Documents = new List<Document>();
            templateDef.Documents.Add(doc);

            // Add a recipient to sign the documeent
            Signer signer = new Signer();
            signer.RoleName = "Signer1";
            signer.RecipientId = "1";

            // Create a SignHere tab somewhere on the document for the signer to sign
            signer.Tabs = new Tabs();
            signer.Tabs.SignHereTabs = new List<SignHere>();
            SignHere signHere = new SignHere();
            signHere.DocumentId = "1";
            signHere.PageNumber = "1";
            signHere.RecipientId = "1";
            signHere.XPosition = "200";
            signHere.YPosition = "100";
            signer.Tabs.SignHereTabs.Add(signHere);

            templateDef.Recipients = new Recipients();
            templateDef.Recipients.Signers = new List<Signer>();
            templateDef.Recipients.Signers.Add(signer);
            return templateDef;
        }
示例#8
0
        /// <summary>
        /// Verify the certificates signature using the nominated public key.
        /// </summary>
        /// <param name="key">An appropriate public key parameter object, RSAPublicKeyParameters, DSAPublicKeyParameters or ECDSAPublicKeyParameters</param>
        /// <returns>True if the signature is valid.</returns>
        /// <exception cref="Exception">If key submitted is not of the above nomiated types.</exception>
        public bool verify(AsymmetricKeyParameter key)
        {
            Signer signature = null;

            try
            {
                signature = SignerUtil.getSigner(xStruct.getSignatureAlgorithm().getObjectId());
            }
            catch
            {
                throw new Exception("Signature not recognised.");
            }

            signature.init(false, key);
            byte[] b = this.getTBSCertificate();
            signature.update(b, 0, b.Length);

            if (!signature.verifySignature(this.getSignature()))
            {
                throw new Exception("Public key presented not for certificate signature");
            }
            return(true);
        }
示例#9
0
        override public void Execute()
        {
            Signer signer1 = SignerBuilder.NewSignerWithEmail(email1)
                             .WithCustomId("signer1")
                             .WithFirstName("John1")
                             .WithLastName("Smith1").Build();

            DocumentPackage superDuperPackage = PackageBuilder.NewPackageNamed(PackageName)
                                                .WithSettings(DocumentPackageSettingsBuilder.NewDocumentPackageSettings().WithInPerson())
                                                .WithSigner(signer1)
                                                .WithDocument(DocumentBuilder.NewDocumentNamed("First Document")
                                                              .FromStream(fileStream1, DocumentType.PDF)
                                                              .WithSignature(SignatureBuilder.SignatureFor(email1)
                                                                             .OnPage(0)
                                                                             .AtPosition(100, 100)))
                                                .Build();

            packageId = eslClient.CreatePackage(superDuperPackage);
            eslClient.SendPackage(packageId);

            eslClient.SignatureImageService.GetSignatureImageForSender(senderUID, SignatureImageFormat.GIF);
            eslClient.SignatureImageService.GetSignatureImageForPackageRole(packageId, signer1.Id, SignatureImageFormat.JPG);
        }
示例#10
0
        public void GetAggregateFeatureTest()
        {
            string ID     = "testid";
            Origin origin = new Origin();
            Signer signer = new Signer();

            Signature signature = new Signature(ID, origin, signer);

            FeatureDescriptor featureDescriptor = FeatureDescriptor.Get <String>("Desc");

            signature[featureDescriptor] = "desc";

            FeatureDescriptor featureDescriptor2 = FeatureDescriptor.Get <String>("Desc2");

            signature[featureDescriptor2] = "desc2";

            List <FeatureDescriptor> fs = new List <FeatureDescriptor>();

            fs.Add(featureDescriptor);
            fs.Add(featureDescriptor2);

            //    Assert.AreEqual(signature.GetAggregateFeature, featureDescriptor);
        }
        public void validSignature()
        {
            Mock <Clock> clock    = new Mock <Clock>();
            DateTime     mockDate = getDate(2011, 9, 9, 23, 36, 0);

            clock.Setup(Clock => Clock.Now()).Returns(mockDate);

            Signer signer = new Signer(new AuthenticationHeaderParser(), clock.Object);

            Credential credential = new Credential("SECRETKEY", "KEYID");

            Request request = new Request("http://amazon.com", Request.Method.Get, "application/json")
            {
                Body = "body"
            };

            signer.Sign(request, credential);

            Assert.AreEqual("20110909T233600Z", request.GetHeader("x-amz-date"));
            Assert.AreEqual("DTA1-HMAC-SHA256 " + "SignedHeaders=content-type;x-amz-date, " + "Credential=KEYID/20110909, "
                            + "Signature=4d2f81ea2cf8d6963f8176a22eec4c65ae95c63502326a7c148686da7d50f47e",
                            request.GetHeader("Authorization"));
        }
示例#12
0
        /// <summary>
        /// When overridden in a descendant class, serializes the object into XML according to Aadhaar API specification.
        /// </summary>
        /// <param name="name">The name of the element.</param>
        /// <returns>An instance of <see cref="XElement"/>.</returns>
        /// <exception cref="System.ArgumentNullException"><see cref="DeviceInfo"/>, <see cref="KeyInfo"/> or <see cref="Data"/> is null.</exception>
        /// <exception cref="System.ArgumentException"><see cref="AadhaarNumber"/> or <see cref="Hmac"/> is empty.</exception>
        protected override XElement SerializeXml(XName name)
        {
            ValidateNull(DeviceInfo, nameof(DeviceInfo));
            ValidateNull(KeyInfo, nameof(KeyInfo));
            ValidateNull(Data, nameof(Data));
            ValidateEmptyString(AadhaarNumber, nameof(AadhaarNumber));
            ValidateEmptyString(Hmac, nameof(Hmac));

            var bfdRequest = base.SerializeXml(BfdXmlNamespace + name.LocalName);
            var meta       = DeviceInfo.ToXml("Meta");

            meta.Attribute("idc").Remove();
            bfdRequest.Add(new XAttribute("uid", AadhaarNumber),
                           new XAttribute("ver", BfdVersion),
                           meta,
                           KeyInfo.ToXml("Skey"),
                           Data.ToXml("Data"),
                           new XElement("Hmac", Hmac));

            Signer?.ComputeSignature(bfdRequest);

            return(bfdRequest);
        }
示例#13
0
        public void TestSignAndVerify(String subDir)
        {
            var subPath = Util.TestDataPath(TEST_DATA, subDir);

            using (var signer = new Signer(subPath))
            {
                var streamInput = new MemoryStream();
                streamInput.Write(new byte[ExtraDataLength], 0, ExtraDataLength);
                using (Utility.ResetStreamWhenFinished(streamInput))
                {
                    InputStream.CopyTo(streamInput);
                    streamInput.Write(new byte[ExtraDataLength], 0, ExtraDataLength);
                }

                Expect(streamInput.Position, Is.EqualTo(ExtraDataLength));
                byte[] sig;
                using (Utility.ResetStreamWhenFinished(streamInput))
                    sig = signer.Sign(streamInput, InputStream.Length);
                Expect(streamInput.Position, Is.EqualTo(10));
                Expect(signer.Verify(streamInput, sig, InputStream.Length), Is.True);
                Expect(streamInput.Position, Is.EqualTo(InputStream.Length + ExtraDataLength));
            }
        }
        public string Sign(string message)
        {
            if (null == message)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (AuthenticationMethod.KeeperClassic != _authenticationSettings.AuthenticationMethod)
            {
                throw new InvalidOperationException(
                          "AuthenticationMethod.KeeperClassic != _authenticationSettings.AuthenticationMethod");
            }

            lock (Anchor)
            {
                if (null == _signer)
                {
                    _signer = ObtainSigner(_authenticationSettings.KeeperKey);
                }

                return(_signer.Sign(message));
            }
        }
示例#15
0
        internal RawTransaction ToRawTransaction(bool includeSign)
        {
            var rawTx = new RawTransaction(
                signer: Signer.ToByteArray(),
                updatedAddresses: UpdatedAddresses.Select(a =>
                                                          a.ToByteArray()).ToArray(),
                publicKey: PublicKey.Format(false),
                timestamp: Timestamp.ToString(TimestampFormat),
                actions: Actions.Select(a =>
                                        a.PlainValue.ToDictionary(
                                            kv => kv.Key,
                                            kv => kv.Value
                                            )
                                        )
                );

            if (includeSign)
            {
                rawTx = rawTx.AddSignature(Signature);
            }

            return(rawTx);
        }
        override public void Execute()
        {
            SignerBuilder signerBuilder = SignerBuilder.NewSignerWithEmail("*****@*****.**")
                                          .WithFirstName("John")
                                          .WithLastName("Smith")
                                          .WithTitle("Managing Director")
                                          .WithCompany("Acme Inc.");

            Signer signer = null;

            try
            {
                signer = signerBuilder.Build();
            }
            catch (EslException eslException)
            {
                Console.Out.WriteLine(eslException.Message);
                return;
            }

            try
            {
                eslClient.PackageService.AddSigner(new PackageId("myPackageId"), signer);
            }
            catch (EslServerException eslServerException)
            {
                Console.Out.WriteLine(eslServerException.Message);
                Console.Out.WriteLine(eslServerException.ServerError.Code);
                Console.Out.WriteLine(eslServerException.ServerError.Message);
                Console.Out.WriteLine(eslServerException.ServerError.Technical);
            }
            catch (EslException eslException)
            {
                Console.Out.WriteLine(eslException.Message);
                return;
            }
        }
        override public void Execute()
        {
            Signer signer1 = SignerBuilder.NewSignerWithEmail(email1)
                             .WithFirstName(TEMPLATE_SIGNER_FIRST)
                             .WithLastName(TEMPLATE_SIGNER_LAST).Build();
            Signer signer2 = SignerBuilder.NewSignerPlaceholder(new Placeholder(PLACEHOLDER_ID)).Build();

            DocumentPackage template = PackageBuilder.NewPackageNamed(PackageName)
                                       .DescribedAs(TEMPLATE_DESCRIPTION)
                                       .WithEmailMessage(TEMPLATE_EMAIL_MESSAGE)
                                       .WithSigner(signer1)
                                       .WithSigner(signer2)
                                       .WithDocument(DocumentBuilder.NewDocumentNamed(DOCUMENT_NAME)
                                                     .WithId(DOCUMENT_ID)
                                                     .FromStream(fileStream1, DocumentType.PDF)
                                                     .WithSignature(SignatureBuilder.SignatureFor(email1)
                                                                    .OnPage(0)
                                                                    .AtPosition(100, 100))
                                                     .WithSignature(SignatureBuilder.SignatureFor(new Placeholder(PLACEHOLDER_ID))
                                                                    .OnPage(0)
                                                                    .AtPosition(400, 100))
                                                     .Build())
                                       .Build();

            templateId = eslClient.CreateTemplate(template);

            FastTrackSigner signer = FastTrackSignerBuilder.NewSignerWithId(signer2.Id)
                                     .WithEmail(GetRandomEmail())
                                     .WithFirstName(FAST_TRACK_SIGNER_FIRST)
                                     .WithLastName(FAST_TRACK_SIGNER_LAST)
                                     .Build();

            List <FastTrackSigner> signers = new List <FastTrackSigner>();

            signers.Add(signer);
            signingUrl = eslClient.PackageService.StartFastTrack(templateId, signers);
        }
示例#18
0
        public resData postMedicalRecord(string userId, string verb, string value)
        {
            var obj = CBORObject.NewMap()
                      .Add("Name", userId)
                      .Add("Verb", verb)
                      .Add("Value", value);
            var prefix = "intkey".ToByteArray().ToSha512().ToHexString().Substring(0, 6);
            var signer = new Signer();

            var settings = new EncoderSettings()
            {
                BatcherPublicKey = signer.GetPublicKey().ToHexString(),
                SignerPublickey  = signer.GetPublicKey().ToHexString(),
                FamilyName       = "intkey",
                FamilyVersion    = "1.0"
            };

            settings.Inputs.Add(prefix);
            settings.Outputs.Add(prefix);
            var encoder = new Sawtooth.Sdk.Client.Encoder(settings, signer.GetPrivateKey());

            var payload = encoder.EncodeSingleTransaction(obj.EncodeToBytes());
            //var payload = obj.EncodeToBytes();

            var content = new ByteArrayContent(payload);

            content.Headers.Add("Content-Type", "application/octet-stream");

            var httpClient = new HttpClient();

            var response = httpClient.PostAsync("http://localhost:8008/batches", content).Result;

            return(new resData()
            {
                response = response, encoderSettings = settings, obj = obj
            });
        }
示例#19
0
        public void TestSign()
        {
            txManager = new TransactionManager(rpcClientMock.Object);

            Signer[] signers = new Signer[1]
            {
                new Signer
                {
                    Account = sender,
                    Scopes  = WitnessScope.Global
                }
            };

            byte[] script = new byte[1];
            txManager.MakeTransaction(script, signers)
            .AddSignature(keyPair1)
            .Sign();

            // get signature from Witnesses
            var tx = txManager.Tx;

            byte[] signature = tx.Witnesses[0].InvocationScript.Skip(2).ToArray();

            Assert.IsTrue(Crypto.VerifySignature(tx.GetHashData(), signature, keyPair1.PublicKey));
            // verify network fee and system fee
            long networkFee = tx.Size * (long)1000 + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHDATA1] + ApplicationEngine.OpCodePrices[OpCode.PUSHNULL] + ApplicationEngine.ECDsaVerifyPrice * 1;

            Assert.AreEqual(networkFee, tx.NetworkFee);
            Assert.AreEqual(100, tx.SystemFee);

            // duplicate sign should not add new witness
            txManager.AddSignature(keyPair1).Sign();
            Assert.AreEqual(1, txManager.Tx.Witnesses.Length);

            // throw exception when the KeyPair is wrong
            Assert.ThrowsException <Exception>(() => txManager.AddSignature(keyPair2).Sign());
        }
示例#20
0
        public void GetObjectData(
            SerializationInfo info,
            StreamingContext context
            )
        {
            info.AddValue("nonce", Nonce);
            info.AddValue("signer", Signer.ToArray());

            // SerializationInfo.AddValue() doesn't seem to work well with
            // 2d arrays.  Concat addresses before encode them (fortunately,
            // addresses all have 20 bytes, fixed-length).
            var updatedAddresses =
                new byte[UpdatedAddresses.Length * Address.Size];
            int i = 0;

            foreach (ImmutableArray <byte> address in UpdatedAddresses)
            {
                address.CopyTo(updatedAddresses, i);
                i += Address.Size;
            }

            info.AddValue("updated_addresses", updatedAddresses);

            info.AddValue("public_key", PublicKey.ToArray());
            info.AddValue("timestamp", Timestamp);
            info.AddValue("actions", Actions.Select(a =>
                                                    a.ToDictionary(
                                                        kv => kv.Key,
                                                        kv => kv.Value
                                                        )
                                                    ));

            if (Signature != ImmutableArray <byte> .Empty)
            {
                info.AddValue("signature", Signature.ToArray());
            }
        }
示例#21
0
        public override void Connect()
        {
            _publicKey = ((ServerParameterString)ServerParameters[0]).Value;
            _secretKey = ((ServerParameterPassword)ServerParameters[1]).Value;

            _urlBuilder        = new PublicUrlBuilder(_host);
            _privateUriBuilder = new PrivateUrlBuilder(_publicKey, _secretKey, _host);

            _cancelTokenSource = new CancellationTokenSource();

            StartMessageReader();

            StartMarketDataReader();

            _signer = new Signer(_secretKey);

            _wsSource = new WsSource("wss://" + _host + _path);
            _wsSource.MessageEvent += WsSourceOnMessageEvent;
            _wsSource.Start();

            _marketDataSource = new WsSource("wss://" + _host + "/ws");
            _marketDataSource.ByteDataEvent += MarketDataSourceOnMessageEvent;
            _marketDataSource.Start();
        }
        private bool InterceptRequest(IRestRequest request)
        {
            bool   isOk = false;
            string body = null;

            foreach (Parameter param in request.Parameters)
            {
                if (param.Name == "application/json")
                {
                    body = (string)param.Value;
                }
            }
            Debug.WriteLine("payload: " + body);
            string xSignature = Signer.GetPayloadSignature(body);

            Debug.WriteLine("x-signature: " + xSignature);
            if (xSignature != null)
            {
                isOk = true;
                request.AddHeader("x-signature", xSignature);
            }

            return(isOk);
        }
示例#23
0
 //audit
 void Audit(HttpContext context)
 {
     if (!context.User.Identity.IsAuthenticated) {
         context.Response.Write("无操作权限");
         return;
     }
     string signerId = context.User.Identity.Name;
     string doId = context.Request["todoId"];
     string tag = context.Request["tag"];
     string result = context.Request["result"];
     try {
         using (WFContext db=new WFContext()) {
             Signer s = new Signer {
                 Id = signerId ,
                 signResult = (SignResult)int.Parse(result) ,
                 SignTime = DateTime.Now ,
                 Tag = context.Server.UrlDecode(tag)
             };
             RepositoryFactory<WFInstanceRepository>.Get().Sign(doId , s , db);
         }
     } catch (Exception ex) {
         context.Response.Write(ex.Message);
     }
 }
示例#24
0
        public void additionalHeadersAreSigned()
        {
            Mock <Clock> clock    = new Mock <Clock>();
            DateTime     mockDate = getDate(2011, 9, 9, 23, 36, 0);

            clock.Setup(Clock => Clock.Now()).Returns(() => mockDate);

            Signer signer = new Signer(new AuthenticationHeaderParser(), clock.Object);

            Credential credential = new Credential("SECRETKEY", "KEYID");

            var         mockDTARequest = createRequestMock("http://amazon.com", "GET", "application/json", "body");
            IDTARequest request        = mockDTARequest.Object;

            request.Headers["aaa"] = "aaa";
            request.Headers["zzz"] = "zzz";

            signer.Sign(request, credential);

            Assert.AreEqual("20110909T233600Z", request.Headers["x-amz-date"].ToString());
            Assert.AreEqual("DTA1-HMAC-SHA256 SignedHeaders=aaa;content-type;x-amz-date;zzz, Credential=KEYID/20110909, " +
                            "Signature=16ec5ffa0e33e8ec8f87f14bb5fd8a03545dbffe99eb3a89f5de450e791ef262",
                            request.Headers["Authorization"].ToString());
        }
示例#25
0
        /// <inheritdoc/>
        public override IEnumerable <Signer> EnumerateSigners(Predicate <Signer> signerFilter)
        {
            //TODO: EnumerateSigners should ba able to operate with a directory path, not just a zip file
            signerFilter = signerFilter ?? SignerFilter;

            var signatureGroups = Directory.GetFileSystemEntries(DatabasePath, "*.TXT", SearchOption.AllDirectories).Select(f => new SignatureFile(f)).GroupBy(sf => sf.SignerID);

            this.LogTrace(signatureGroups.Count().ToString() + " signers found in database");
            foreach (var group in signatureGroups)
            {
                Signer signer = new Signer {
                    ID = group.Key
                };

                if (signerFilter != null && !signerFilter(signer))
                {
                    continue;
                }
                foreach (var signatureFile in group)
                {
                    Signature signature = new Signature
                    {
                        Signer = signer,
                        ID     = signatureFile.SignatureID
                    };
                    this.LoadSignature(signature, (signatureFile.File).GetPath(), StandardFeatures);

                    signature.Origin = int.Parse(signature.ID) < 21 ? Origin.Genuine : Origin.Forged;
                    signer.Signatures.Add(signature);
                }
                signer.Signatures = signer.Signatures.OrderBy(s => s.ID).ToList();
                yield return(signer);
            }

            this.LogInformation("Enumerating signers finished.");
        }
示例#26
0
        public void RefreshSignParameters()
        {
            RoaSignatureComposer.ClearComposer();
            RoaSignatureComposer        instance   = new RoaSignatureComposer();
            Dictionary <string, string> parameters = new Dictionary <string, string>
            {
                { "foo", "bar" },
                { "a", "A" },
                { "nullValue", null }
            };
            var mock = new Mock <Signer>();

            mock.Setup(foo => foo.GetSignerType()).Returns("MockSigner");
            Signer signer = mock.Object;
            UnmarshallerContext context = new UnmarshallerContext();

            context.ResponseDictionary = instance.RefreshSignParameters(parameters, signer, "accessKeyId", FormatType.JSON);
            Assert.Equal("MockSigner", context.StringValue("x-acs-signature-type"));

            HmacSHA1Signer hmacSHA1Signer = new HmacSHA1Signer();

            context.ResponseDictionary = instance.RefreshSignParameters(parameters, hmacSHA1Signer, "accessKeyId", null);
            Assert.Null(context.StringValue("x-acs-signature-type"));
        }
示例#27
0
        public void VerifyResult()
        {
            IdvAuthExample example = new IdvAuthExample();

            example.Run();

            DocumentPackage retrievedPackage = example.RetrievedPackage;

            AssertIdvWorkflowConfigs(new List <IdvWorkflowConfig>(), example.idvWorkflowConfigsBeforeCreating);
            AssertIdvWorkflowConfigs(example.idvWorkflowConfigsToBeCreated, example.idvWorkflowConfigsAfterCreating);
            AssertIdvWorkflowConfigs(example.idvWorkflowConfigsToBeUpdated, example.idvWorkflowConfigsAfterUpdating);
            AssertIdvWorkflowConfigs(new List <IdvWorkflowConfig>(), example.idvWorkflowConfigsAfterDeleting);

            Signer signer = retrievedPackage.GetSigner(example.email1);

            Assert.AreEqual(AuthenticationMethod.IDV, signer.AuthenticationMethod);
            Assert.AreEqual(0, signer.ChallengeQuestion.Count);
            Assert.AreEqual(IdvAuthExample.PHONE_NUMBER, signer.PhoneNumber);

            IdvWorkflow idvWorkflow = signer.Authentication.IdvWorkflow;

            Assert.AreEqual(IdvAuthExample.IDV_WORKFLOW_ID1, idvWorkflow.Id);
            Assert.AreEqual(IdvAuthExample.TENANT, idvWorkflow.Tenant);
        }
        public void SetKeeperKey(byte[] keeperKey)
        {
            if (null == keeperKey)
            {
                throw new ArgumentNullException(nameof(keeperKey));
            }

            if (AuthenticationMethod.KeeperClassic != _authenticationSettings.AuthenticationMethod)
            {
                throw new InvalidOperationException(
                          "AuthenticationMethod.KeeperClassic != _authenticationSettings.AuthenticationMethod");
            }

            lock (Anchor)
            {
                if (!keeperKey.SequenceEqual(_authenticationSettings.KeeperKey))
                {
                    _authenticationSettings.KeeperKey = keeperKey;
                    Save();

                    _signer = null;
                }
            }
        }
            public void Converts_signer_successfully()
            {
                //Arrange
                const string personalIdentificationNumber = "0123456789";

                var source   = new Signer(new PersonalIdentificationNumber(personalIdentificationNumber));
                var expected = new directsigner
                {
                    ItemElementName     = ItemChoiceType.personalidentificationnumber,
                    Item                = personalIdentificationNumber,
                    onbehalfof          = signingonbehalfof.SELF,
                    onbehalfofSpecified = true
                };

                //Act
                var result = DataTransferObjectConverter.ToDataTransferObject(source);

                //Assert
                var comparator = new Comparator();
                IEnumerable <IDifference> differences;

                comparator.AreEqual(expected, result, out differences);
                Assert.Empty(differences);
            }
示例#30
0
        static void Main(string[] args)
        {
            var owner = new KeysPair(
                Base58.Decode("5eGEt2wuDrvEt1d7zUDdqZEF9u2sYiVXg6jJEk5G1ytJ"),
                Base58.Decode("QXuwUXRhANuouMkHTc2tbcZhkcucShZQKEhs7XSfseSd6Rq8q2G3sSZc1Q1z5jdj4Nz8dQuieiiyDVLiKWDmtJVp"));

            Console.WriteLine("Leyendo White Paper");
            var content    = File.ReadAllText("white-paper.md");
            var whitePaper = new Document(content);

            Console.WriteLine("Inicializando Firmador");
            var signer = new Signer(CryptoService.Instance);

            Console.WriteLine("Firmando White Paper");
            signer.Sign(whitePaper, owner);

            Console.WriteLine("Construyendo bloque Génesis");
            var block = new Block(Array.Empty <byte>(), 0);

            block.Documents.Add(whitePaper);

            byte dificulty = 3;

            Console.WriteLine($"Minando bloque Génesis con una dificultad de {dificulty}");
            var miner = new Miner(owner.PublicKey);

            miner.Mine(block, dificulty);

            Console.WriteLine("Serializando bloque Génesis");
            var json = JsonSerializer.Serialize(block, JsonDefaultSettings.Options);

            Console.WriteLine("Guardando bloque minado");
            File.WriteAllText("genesis.block", json, Encoding.UTF8);

            Console.WriteLine("Listo ;)");
        }
示例#31
0
        public Bencodex.Types.Dictionary ToBencodex()
        {
            var updatedAddresses =
                UpdatedAddresses.Select(addr => (IValue)(Binary)addr.ToArray());
            var dict = Bencodex.Types.Dictionary.Empty
                       .Add(NonceKey, Nonce)
                       .Add(SignerKey, Signer.ToArray())
                       .Add(UpdatedAddressesKey, updatedAddresses)
                       .Add(PublicKeyKey, PublicKey.ToArray())
                       .Add(TimestampKey, Timestamp)
                       .Add(ActionsKey, Actions);

            if (GenesisHash != ImmutableArray <byte> .Empty)
            {
                dict = dict.Add(GenesisHashKey, GenesisHash.ToArray());
            }

            if (Signature != ImmutableArray <byte> .Empty)
            {
                dict = dict.Add(SignatureKey, Signature.ToArray());
            }

            return(dict);
        }
        public void roundTripWithCredentialStore()
        {
            Mock <Clock> clock    = new Mock <Clock>();
            DateTime     mockDate = getDate(2011, 9, 9, 23, 36, 0);

            clock.Setup(Clock => Clock.Now()).Returns(() => mockDate);

            Signer signer = new Signer(new AuthenticationHeaderParser(), clock.Object);

            Credential credential = new Credential("SECRETKEY", "KEYID");

            Request request = new Request("http://amazon.com", Request.Method.Get, "application/json");

            request.Body = "body";
            request.SetHeader("aaa", "aaa");
            request.SetHeader("zzz", "zzz");

            signer.Sign(request, credential);

            string authorization = request.GetHeader(AUTHORIZATION_HEADER);

            // NOTE: HttpServletRequest always seems to put a trailing slash on bare urls so the test mimics this
            Request verificationRequest = new Request("http://amazon.com/", Request.Method.Get, "application/json");

            verificationRequest.Body = "body";
            verificationRequest.SetHeader("aaa", "aaa");
            verificationRequest.SetHeader("zzz", "zzz");
            verificationRequest.SetHeader(X_AMZ_DATE_HEADER, "20110909T233600Z");
            verificationRequest.SetHeader(AUTHORIZATION_HEADER, authorization);

            CredentialStore store = new CredentialStore();

            store.LoadFromContents("AUXKEY AUXKEYID\nSECRETKEY KEYID\n");

            Assert.IsTrue(signer.Verify(verificationRequest, store));
        }
        public void before15MinuteWindowFailsValidation()
        {
            Mock <Clock> clock  = new Mock <Clock>();
            Signer       signer = new Signer(new AuthenticationHeaderParser(), clock.Object);

            DateTime mockDate = getDate(2011, 9, 9, 23, 36 - 16, 59); // Go 15 Minutes Before

            clock.Setup(Clock => Clock.Now()).Returns(() => mockDate);

            Credential credential = new Credential("SECRETKEY", "KEYID");

            Request verificationRequest = new Request("http://amazon.com", Request.Method.Get, "application/json");

            verificationRequest.Body = "body";
            verificationRequest.SetHeader("aaa", "aaa");
            verificationRequest.SetHeader("zzz", "zzz");
            verificationRequest.SetHeader(X_AMZ_DATE_HEADER, "20110909T233600Z");
            verificationRequest
            .SetHeader(
                AUTHORIZATION_HEADER,
                "DTA1-HMAC-SHA256 SignedHeaders=aaa;content-type;x-amz-date;zzz, Credential=KEYID/20110909, Signature=87729cb3475859a18b5d9cead0bba82f0f56a85c2a13bed3bc229c6c35e06628");

            Assert.IsFalse(signer.Verify(verificationRequest, credential));
        }
示例#34
0
        public void Sets_clique_block_producer_properly()
        {
            CliqueConfig        cliqueConfig = new CliqueConfig();
            IBlockTree          blockTree    = Substitute.For <IBlockTree>();
            Signer              signer       = new Signer(ChainId.Ropsten, TestItem.PrivateKeyA);
            CliqueBlockProducer producer     = new CliqueBlockProducer(
                Substitute.For <ITxSource>(),
                Substitute.For <IBlockchainProcessor>(),
                Substitute.For <IStateProvider>(),
                blockTree,
                Substitute.For <ITimestamper>(),
                Substitute.For <ICryptoRandom>(),
                Substitute.For <ISnapshotManager>(),
                new CliqueSealer(signer, cliqueConfig, Substitute.For <ISnapshotManager>(), LimboLogs.Instance), cliqueConfig, LimboLogs.Instance);

            SnapshotManager snapshotManager = new SnapshotManager(CliqueConfig.Default, new MemDb(), Substitute.For <IBlockTree>(), NullEthereumEcdsa.Instance, LimboLogs.Instance);

            CliqueBridge bridge = new CliqueBridge(producer, snapshotManager, blockTree);

            Assert.DoesNotThrow(() => bridge.CastVote(TestItem.AddressB, true));
            Assert.DoesNotThrow(() => bridge.UncastVote(TestItem.AddressB));
            Assert.DoesNotThrow(() => bridge.CastVote(TestItem.AddressB, false));
            Assert.DoesNotThrow(() => bridge.UncastVote(TestItem.AddressB));
        }
        public void fiveMinutesBeforeValidates()
        {
            Mock <Clock> clock  = new Mock <Clock>();
            Signer       signer = new Signer(new AuthenticationHeaderParser(), clock.Object);

            DateTime mockDate = getDate(2011, 9, 9, 23, 36 - 5, 0); // Go 5 minutes before

            clock.Setup(Clock => Clock.Now()).Returns(() => mockDate);

            Credential credential = new Credential("SECRETKEY", "KEYID");

            Request verificationRequest = new Request("http://amazon.com", Request.Method.Get, "application/json");

            verificationRequest.Body = "body";
            verificationRequest.SetHeader("aaa", "aaa");
            verificationRequest.SetHeader("zzz", "zzz");
            verificationRequest.SetHeader(X_AMZ_DATE_HEADER, "20110909T233600Z");
            verificationRequest
            .SetHeader(
                AUTHORIZATION_HEADER,
                "DTA1-HMAC-SHA256 SignedHeaders=aaa;content-type;x-amz-date;zzz, Credential=KEYID/20110909, Signature=16ec5ffa0e33e8ec8f87f14bb5fd8a03545dbffe99eb3a89f5de450e791ef262");

            Assert.IsTrue(signer.Verify(verificationRequest, credential));
        }
        public void when_CreateTransaction_is_called_with_invalid_email_then_we_should_get_a_BadRequestException()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp
            .Expect(HttpMethod.Post, "http://localhost/api/transaction")
            .WithHeaders("Content-Type", "application/json")
            .Respond(HttpStatusCode.BadRequest, new StringContent(" { 'message': 'Bad Request' }"));

            using (var httpClient = mockHttp.ToHttpClient()) {
                var signhostApiClient = new SignHostApiClient(settings, httpClient);

                Signer testSigner = new Signer();
                testSigner.Email = "firstname.lastnamegmail.com";

                Transaction testTransaction = new Transaction();
                testTransaction.Signers.Add(testSigner);

                Func <Task> getTransaction = () => signhostApiClient.CreateTransactionAsync(testTransaction);
                getTransaction.Should().Throw <ErrorHandling.BadRequestException>();
            }

            mockHttp.VerifyNoOutstandingExpectation();
        }
        public async Task TestSign()
        {
            Signer[] signers = new Signer[1]
            {
                new Signer
                {
                    Account = sender,
                    Scopes  = WitnessScope.Global
                }
            };

            byte[] script = new byte[1];
            txManager = await TransactionManager.MakeTransactionAsync(rpcClientMock.Object, script, signers);

            await txManager
            .AddSignature(keyPair1)
            .SignAsync();

            // get signature from Witnesses
            var tx = txManager.Tx;

            byte[] signature = tx.Witnesses[0].InvocationScript.Skip(2).ToArray();

            Assert.IsTrue(Crypto.VerifySignature(tx.GetHashData(), signature, keyPair1.PublicKey));
            // verify network fee and system fee
            Assert.AreEqual(100000000 /*Mock*/, tx.NetworkFee);
            Assert.AreEqual(100, tx.SystemFee);

            // duplicate sign should not add new witness
            await txManager.AddSignature(keyPair1).SignAsync();

            Assert.AreEqual(1, txManager.Tx.Witnesses.Length);

            // throw exception when the KeyPair is wrong
            await ThrowsAsync <Exception>(async() => await txManager.AddSignature(keyPair2).SignAsync());
        }
        public async Task when_a_CreateTransaction_is_called_then_we_should_have_called_the_transaction_Post_once()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp
            .Expect(HttpMethod.Post, "http://localhost/api/transaction")
            .Respond(HttpStatusCode.OK, new StringContent(APIResponses.AddTransaction));

            using (var httpClient = mockHttp.ToHttpClient()) {
                var signhostApiClient = new SignHostApiClient(settings, httpClient);

                Signer testSigner = new Signer();
                testSigner.Email = "*****@*****.**";

                Transaction testTransaction = new Transaction();
                testTransaction.Signers.Add(testSigner);

                var result = await signhostApiClient.CreateTransactionAsync(testTransaction);

                result.Id.Should().Be("c487be92-0255-40c7-bd7d-20805a65e7d9");
            }

            mockHttp.VerifyNoOutstandingExpectation();
        }
示例#39
0
        public void TestSignImport(
            [Values("rsa", "dsa")] string keyType,
            [Values("pem", "der")] string format)
        {
            using (var keystream = HelperOpenPkcsStream(keyType, format, "sign"))
            using (
                var keyset = ImportedKeySet.Import.PkcsKey(KeyPurpose.SignAndVerify, keystream, () => "pass"
                    /* hard coding for test only!!!!*/))
            using (var signer = new Signer(keyset))

            {
                var signature = signer.Sign(input);
                using (var verifier = new Verifier(Util.TestDataPath(TEST_DATA, keyType + "-sign-pub")))
                {
                    Expect(verifier.Verify(input, signature), Is.True);
                }
            }
        }
示例#40
0
        public void TestSignAndVerify(String subDir, string nestDir)
        {
            var subPath = Util.TestDataPath(TEST_DATA, subDir, nestDir);
            using (var signer = new Signer(subPath))
            {
                var sig = signer.Sign(input);

                Expect(signer.Verify(input, sig), Is.True);
                Expect(signer.Verify("Wrong string", sig), Is.False);
            }
        }
示例#41
0
        private Signer BuildGroupSigner()
        {            
            Signer result = new Signer(groupId);
            result.SigningOrder = signingOrder;
            result.CanChangeSigner = canChangeSigner;
            result.Message = message;
            result.Id = id;
            result.Locked = locked;
			result.Attachments = attachments;
            
            return result;
        }
 public static Signer Decode(IByteReader stream) {
   Signer decodedSigner = new Signer();
   decodedSigner.PubKey = AccountID.Decode(stream);
   decodedSigner.Weight = Uint32.Decode(stream);
   return decodedSigner;
 }
示例#43
0
        internal static EnvelopeDefinition CreateDraftEnvelopeDefinition()
        {
            // Read a file from disk to use as a document.
            byte[] fileBytes = File.ReadAllBytes(TestConfig.SignTest1File);

            EnvelopeDefinition envDef = new EnvelopeDefinition();
            envDef.EmailSubject = "Please Sign my C# SDK Envelope";

            Document doc = new Document();
            doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes);
            doc.Name = "TestFile.pdf";
            doc.DocumentId = "1";

            envDef.Documents = new List<Document>();
            envDef.Documents.Add(doc);

            // Add a recipient to sign the documeent
            Signer signer = new Signer();
            signer.Email = TestConfig.UserName;  // use name is same as my email
            signer.Name = "Pat Developer";
            signer.RecipientId = "1";

            // Create a SignHere tab somewhere on the document for the signer to sign
            signer.Tabs = new Tabs();
            signer.Tabs.SignHereTabs = new List<SignHere>();
            SignHere signHere = new SignHere();
            signHere.DocumentId = "1";
            signHere.PageNumber = "1";
            signHere.RecipientId = "1";
            signHere.XPosition = "100";
            signHere.YPosition = "100";
            signer.Tabs.SignHereTabs.Add(signHere);

            envDef.Recipients = new Recipients();
            envDef.Recipients.Signers = new List<Signer>();
            envDef.Recipients.Signers.Add(signer);
            return envDef;
        }
示例#44
0
 public void signerInit()
 {
     if (!Connected) Connect();
     signer = new Signer(proxy);
 }
示例#45
0
 public void TestBadVerify(String subDir, string nestDir)
 {
     var subPath = Util.TestDataPath(TEST_DATA, subDir, nestDir);
     using (var verifier = new Signer(subPath))
     {
         var activeSignature = (WebBase64) File.ReadAllLines(Path.Combine(subPath, "1.out")).First();
         var primarySignature = (WebBase64) File.ReadAllLines(Path.Combine(subPath, "2.out")).First();
         Expect(verifier.Verify("Wrong String", activeSignature), Is.False);
         Expect(verifier.Verify("Wrong String", primarySignature), Is.False);
         Expect(
             verifier.Verify(input,
                             (WebBase64)
                             (primarySignature.ToString().Substring(0, primarySignature.ToString().Length - 4) +
                              "junk")), Is.False);
     }
 }
        static void Main(string[] args)
        {
            // Enter your DocuSign credentials
            string Username = "******";
            string Password = "******";
            string IntegratorKey = "[INTEGRATOR_KEY]";

            // specify the document (file) we want signed
            string SignTest1File = @"[PATH/TO/DOCUMENT/TEST.PDF]";

            // Enter recipient (signer) name and email address
            string recipientName = "[SIGNER_NAME]";
            string recipientEmail = "[SIGNER_EMAIL]";

            // instantiate api client with appropriate environment (for production change to www.docusign.net/restapi)
            string basePath = "https://demo.docusign.net/restapi";

            // instantiate a new api client
            ApiClient apiClient = new ApiClient(basePath);

            // set client in global config so we don't need to pass it to each API object
            Configuration.Default.ApiClient = apiClient;

            string authHeader = "{\"Username\":\"" + Username + "\", \"Password\":\"" + Password + "\", \"IntegratorKey\":\"" + IntegratorKey + "\"}";
            Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);

            // we will retrieve this from the login() results
            string accountId = null;

            // the authentication api uses the apiClient (and X-DocuSign-Authentication header) that are set in Configuration object
            AuthenticationApi authApi = new AuthenticationApi();
            LoginInformation loginInfo = authApi.Login();

			// user might be a member of multiple accounts
            accountId = loginInfo.LoginAccounts[0].AccountId;

            Console.WriteLine("LoginInformation: {0}", loginInfo.ToJson());

            // Read a file from disk to use as a document
            byte[] fileBytes = File.ReadAllBytes(SignTest1File);

            EnvelopeDefinition envDef = new EnvelopeDefinition();
            envDef.EmailSubject = "[DocuSign C# SDK] - Please sign this doc";

            // Add a document to the envelope
            Document doc = new Document();
            doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes);
            doc.Name = "TestFile.pdf";
            doc.DocumentId = "1";

            envDef.Documents = new List<Document>();
            envDef.Documents.Add(doc);

            // Add a recipient to sign the documeent
            Signer signer = new Signer();
            signer.Name = recipientName;
            signer.Email = recipientEmail;            
            signer.RecipientId = "1";

            // Create a |SignHere| tab somewhere on the document for the recipient to sign
            signer.Tabs = new Tabs();
            signer.Tabs.SignHereTabs = new List<SignHere>();
            SignHere signHere = new SignHere();
            signHere.DocumentId = "1";
            signHere.PageNumber = "1";
            signHere.RecipientId = "1";
            signHere.XPosition = "100";
            signHere.YPosition = "150";
            signer.Tabs.SignHereTabs.Add(signHere);

            envDef.Recipients = new Recipients();
            envDef.Recipients.Signers = new List<Signer>();
            envDef.Recipients.Signers.Add(signer);

            // set envelope status to "sent" to immediately send the signature request
            envDef.Status = "sent";

            // Use the EnvelopesApi to send the signature request!
            EnvelopesApi envelopesApi = new EnvelopesApi();
            EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);

            // print the JSON response
            Console.WriteLine("EnvelopeSummary:\n{0}", JsonConvert.SerializeObject(envelopeSummary));
            Console.Read();
        }
示例#47
0
        private Signer BuildRegularSigner()
        {            
            Asserts.NotEmptyOrNull (firstName, "firstName");
            Asserts.NotEmptyOrNull (lastName, "lastName");
                        
            if (authentication == null)
            {
                authentication = authenticationBuilder.Build();
            }

            Signer result = new Signer (signerEmail, firstName, lastName, authentication);
            result.Title = title;
            result.Company = company;
            result.DeliverSignedDocumentsByEmail = deliverSignedDocumentsByEmail;

            result.SigningOrder = signingOrder;
            result.CanChangeSigner = canChangeSigner;
            result.Message = message;
            result.Id = id;
            result.Locked = locked;
			result.Attachments = attachments;
			            
            return result;
        }
 public static void Encode(IByteWriter stream, Signer encodedSigner) {
   AccountID.Encode(stream, encodedSigner.PubKey);
   Uint32.Encode(stream, encodedSigner.Weight);
 }
示例#49
0
 public void default_key_works() {
     var signer = new Signer("some key");
     var signed = signer.Sign("test");
     signer.Unsign(signed).ShouldBe("test");
 }
 public void TestVerify(String subDir)
 {
     var subPath = Util.TestDataPath(TEST_DATA, subDir);
     using (var verifier = new Signer(subPath))
     {
         var signature = (WebBase64) File.ReadAllLines(Path.Combine(subPath, "1.out")).First();
         Expect(verifier.Verify(plaintext, signature), Is.True);
     }
 }
示例#51
0
 public void TestSignerVerify(String subDir)
 {
     var subPath = Util.TestDataPath(TEST_DATA, subDir);
     using (var verifier = new Signer(subPath))
     {
         var activeSignature = (WebBase64) File.ReadAllLines(Path.Combine(subPath, "1.out")).First();
         var primarySignature = (WebBase64) File.ReadAllLines(Path.Combine(subPath, "2.out")).First();
         Expect(verifier.Verify(input, activeSignature), Is.True);
         Expect(verifier.Verify(input, primarySignature), Is.True);
     }
 }
示例#52
0
        private Signer BuildPlaceholderSigner()
        {    
            Asserts.NotEmptyOrNull( id, "No placeholder set for this signer!" );
                    
            Signer result = new Signer(id);
            result.SigningOrder = signingOrder;
            result.CanChangeSigner = canChangeSigner;
            result.Message = message;
            result.Locked = locked;
			result.Attachments = attachments;
			            
            return result;
        }
        public static void Execute()
        {
            // Enter your DocuSign credentials
            var credentials = new DocusignQuickStart.DocusignCredentials
            {
                Username = "******",
                Password = "******",
                IntegratorKey = "81f3bae3-f472-4a51-8d5f-e966f74cb0ab"
            };

            // specify the document (file) we want signed
            string SignTest1File = @"C:\Users\callu_000\Documents\UD Group\Docusign\CNG\CNG Contract.pdf";

            // Enter recipient (signer) name and email address
            string recipientName = "Callum Rigby";
            string recipientEmail = "*****@*****.**";

            string recipientName2 = "John Smith";
            string recipientEmail2 = "*****@*****.**";

            // instantiate api client with appropriate environment (for production change to www.docusign.net/restapi)
            string basePath = "https://demo.docusign.net/restapi";

            // instantiate a new api client
            var apiClient = new ApiClient(basePath);

            // set client in global config so we don't need to pass it to each API object
            Configuration.Default.ApiClient = apiClient;

            string authHeader = JsonConvert.SerializeObject(credentials);
            //DocusignCredentials cred = JsonConvert.DeserializeObject<DocusignCredentials>(authHeader);
            Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);

            // we will retrieve this from the login() results
            string accountId = null;

            // the authentication api uses the apiClient (and X-DocuSign-Authentication header) that are set in Configuration object
            var authApi = new AuthenticationApi();
            LoginInformation loginInfo = authApi.Login();

            // user might be a member of multiple accounts
            accountId = loginInfo.LoginAccounts[0].AccountId;

            Console.WriteLine("LoginInformation: {0}", loginInfo.ToJson());

            // Read a file from disk to use as a document
            byte[] fileBytes = File.ReadAllBytes(SignTest1File);

            var envDef = new EnvelopeDefinition();
            envDef.EmailSubject = "[DocuSign C# SDK] - Please sign this doc";

            // Add a document to the envelope
            var doc = new Document();
            doc.DocumentBase64 = Convert.ToBase64String(fileBytes);
            doc.Name = "TestFile.pdf";
            doc.DocumentId = "1";

            envDef.Documents = new List<Document>();
            envDef.Documents.Add(doc);

            // Add a recipient to sign the documeent
            var signer = new Signer();
            signer.Name = recipientName;
            signer.Email = recipientEmail;
            signer.RecipientId = "1";
            signer.RoutingOrder = "1";

            var signer2 = new Signer();
            signer2.Name = recipientName2;
            signer2.Email = recipientEmail2;
            signer2.RecipientId = "2";
            signer.RoutingOrder = "2";

            // Create a |SignHere| tab somewhere on the document for the recipient to sign
            signer.Tabs = new Tabs();
            signer.Tabs.SignHereTabs = new List<SignHere>();
            var signHere = new SignHere();
            signHere.DocumentId = "1";
            signHere.PageNumber = "1";
            signHere.RecipientId = "1";
            signHere.XPosition = "100";
            signHere.YPosition = "150";
            signer.Tabs.SignHereTabs.Add(signHere);

            signer2.Tabs = new Tabs();
            signer2.Tabs.SignHereTabs = new List<SignHere>();
            var signHere2 = new SignHere();
            signHere.DocumentId = "1";
            signHere.PageNumber = "1";
            signHere.RecipientId = "2";
            signHere.XPosition = "100";
            signHere.YPosition = "200";
            signer2.Tabs.SignHereTabs.Add(signHere);

            envDef.Recipients = new Recipients();
            envDef.Recipients.Signers = new List<Signer>();
            envDef.Recipients.Signers.Add(signer);
            envDef.Recipients.Signers.Add(signer2);

            // set envelope status to "sent" to immediately send the signature request
            envDef.Status = "sent";

            // Use the EnvelopesApi to send the signature request!
            var envelopesApi = new EnvelopesApi();
            EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);

            // print the JSON response
            Console.WriteLine("EnvelopeSummary:\n{0}", JsonConvert.SerializeObject(envelopeSummary));
            Console.Read();
        }
示例#54
0
		public PackageBuilder WithSigner(Signer signer)
		{
			if (signer.IsGroupSigner())
			{
				signers[signer.GroupId.Id] = signer;
			}
			else
			{
				signers [signer.Email] = signer;
			}
			return this;
		}
示例#55
0
		public Signer Build ()
		{
			Support.LogMethodEntry();

            Signer signer;
            if (isGroupSigner())
            {
                signer = new Signer(groupId);
            }
            else
            {
                Asserts.NotEmptyOrNull (firstName, "firstName");
                Asserts.NotEmptyOrNull (lastName, "lastName");
                Authentication authentication = authenticationBuilder.Build();
                signer = new Signer (signerEmail, firstName, lastName, authentication);
                signer.Title = title;
                signer.Company = company;
                signer.DeliverSignedDocumentsByEmail = deliverSignedDocumentsByEmail;
            }


			signer.SigningOrder = signingOrder;
            signer.CanChangeSigner = canChangeSigner;
			signer.Message = message;
			signer.Id = id;
			signer.Locked = locked;

			Support.LogMethodExit(signer);
			return signer;
		}