/// <summary> /// Sign pdf document with form-field signature /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Basic Usage] # SignPdfWithFormField : Sign pdf document with form-field signature\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_PDF; string fileName = Path.GetFileName(filePath); string outputFilePath = Path.Combine(Constants.OutputPath, "SignPdfWithFormField", "SignedWithFormField.pdf"); using (Signature signature = new Signature(filePath)) { // instantiate text form field signature FormFieldSignature textSignature = new TextFormFieldSignature("FieldText", "Value1"); // instantiate options based on text form field signature FormFieldSignOptions options = new FormFieldSignOptions(textSignature) { Top = 150, Left = 50, Height = 50, Width = 200 }; // sign document to file SignResult result = signature.Sign(outputFilePath, options); Console.WriteLine($"\nSource document signed successfully with {result.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); } }
public async Task SignLocalVerifyRoundTripFramework([Fields(nameof(SignatureAlgorithm.PS256), nameof(SignatureAlgorithm.PS384), nameof(SignatureAlgorithm.PS512))] SignatureAlgorithm algorithm) { #if !NETFRAMEWORK // RSA-PSS is not supported on .NET Framework so recorded tests will fall back to the remote client. Assert.Ignore("RSA-PSS is supported on .NET Core so local tests will pass. This test method is to test that on .NET Framework RSA-PSS sign/verify attempts fall back to the remote client."); #endif Key key = await CreateTestKey(algorithm); RegisterForCleanup(key.Name); CryptographyClient client = GetCryptoClient(key.Properties.Id); byte[] data = new byte[32]; Recording.Random.NextBytes(data); using HashAlgorithm hashAlgo = algorithm.GetHashAlgorithm(); byte[] digest = hashAlgo.ComputeHash(data); // Should sign remotely... SignResult signResult = await client.SignAsync(algorithm, digest); Assert.AreEqual(algorithm, signResult.Algorithm); Assert.AreEqual(key.KeyMaterial.KeyId, signResult.KeyId); Assert.NotNull(signResult.Signature); // ...and verify locally. VerifyResult verifyResult = await client.VerifyAsync(algorithm, digest, signResult.Signature); Assert.AreEqual(algorithm, verifyResult.Algorithm); Assert.AreEqual(key.KeyMaterial.KeyId, verifyResult.KeyId); Assert.IsTrue(verifyResult.IsValid); }
public SignResult SignIn(SignInViewModel user) { var request = new RestSharp.RestRequest(AccountAPI.SignIn) { //JsonSerializer = new NewtonsoftJsonSerializer() }; request.AddQueryParameter("userId", user.UserId); request.AddQueryParameter("password", user.Password); IRestResponse response = _client.Get(request); var apiResponse = JsonConvert.DeserializeObject <GenericAPIResponse>(response.Content); var res = new SignResult() { Succeed = apiResponse.Success, ErrorMessage = apiResponse.Error }; if (apiResponse.Success) { var authResult = JsonConvert.DeserializeObject <AuthenticateResultModel>(apiResponse.Result.ToString()); res.User = new User() { UserId = authResult.UserId }; res.AccessToken = authResult.AccessToken; } return(res); }
/// <summary> /// Sign document with text signature applying Image implementation type /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Advanced Usage] # SignWithTextImage : Sign document with text signature applying Image implementation type\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_WORDPROCESSING; string fileName = Path.GetFileName(filePath); string outputFilePath = Path.Combine(Constants.OutputPath, "SignWithTextImage", fileName); using (Signature signature = new Signature(filePath)) { TextSignOptions options = new TextSignOptions("John Smith") { // set alternative signature implementation on document page SignatureImplementation = TextSignatureImplementation.Image, // set alignment VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, // set margin with 20 pixels for all sides Margin = new Padding(20), // add special background as an image text implementation advantage Background = new Background() { Color = Color.LimeGreen, Transparency = 0.5, Brush = new RadialGradientBrush(Color.LimeGreen, Color.DarkGreen) }, }; // sign document to file SignResult signResult = signature.Sign(outputFilePath, options); Console.WriteLine($"\nSource document signed successfully with {signResult.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); } }
/// <summary> /// Sign document with digital signature /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Basic Usage] # SignWithDigital : Sign document with digital certificate\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_PDF; string fileName = Path.GetFileName(filePath); string imagePath = Constants.ImageHandwrite; string certificatePath = Constants.CertificatePfx; string outputFilePath = Path.Combine(Constants.OutputPath, "SignWithDigital", fileName); using (Signature signature = new Signature(filePath)) { DigitalSignOptions options = new DigitalSignOptions(certificatePath) { // optional: setup image file path ImageFilePath = imagePath, // Left = 50, Top = 50, PageNumber = 1, Password = "******" }; // sign document to file SignResult result = signature.Sign(outputFilePath, options); Console.WriteLine($"\nSource document signed successfully with {result.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); } }
public async Task <Response> SignFile(string fileName, string folderName, string signType, string signText, string signImagePath, string signLocation, string signSize) { string logMsg = "ControllerName: GroupDocsSignatureController FileName: " + fileName + " FolderName: " + folderName; try { string fileExt = Path.GetExtension(fileName).Substring(1).ToLower(); return(await ProcessTask(fileName, folderName, "." + fileExt, false, "", delegate(string inFilePath, string outPath, string zipOutFolder) { if (!Directory.Exists(zipOutFolder)) { Directory.CreateDirectory(zipOutFolder); } using (Signature signature = new Signature(inFilePath)) { var options = GetSignOptions(signType, signText, signImagePath, signLocation, signSize); SignResult signResult = signature.Sign(outPath, options); } })); } catch (Exception exc) { return(new Response { FileName = fileName, FolderName = folderName, OutputType = signType, Status = exc.Message, StatusCode = 500, Text = exc.ToString() }); } }
/// <summary> /// Sign document and make it password-protected /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Advanced Usage] # SaveDocumentWithPassword : Sign document and make it password-protected\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_PDF; string fileName = Path.GetFileName(filePath); string outputFilePath = Path.Combine(Constants.OutputPath, "SaveSignedWithPassword", fileName); using (Signature signature = new Signature(filePath)) { // create QRCode option with predefined QRCode text QrCodeSignOptions signOptions = new QrCodeSignOptions("JohnSmith") { // setup QRCode encoding type EncodeType = QrCodeTypes.QR, // set signature position Left = 100, Top = 100 }; SaveOptions saveOptions = new SaveOptions() { Password = "******", UseOriginalPassword = false }; // sign document to file SignResult result = signature.Sign(outputFilePath, signOptions, saveOptions); Console.WriteLine($"\nSource document signed successfully with {result.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); } }
/// <summary> /// Sign image and save it to different output type /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Advanced Usage] # SaveSignedImageWithDifferentOutputFileType : Sign image and save it to different output type\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_IMAGE; string fileName = Path.GetFileName(filePath); string outputFilePath = Path.Combine(Constants.OutputPath, "SaveSignedOutputType", "Sample_PngToJpg.jpg"); using (Signature signature = new Signature(filePath)) { // create QRCode option with predefined QRCode text QrCodeSignOptions signOptions = new QrCodeSignOptions("JohnSmith") { // setup QRCode encoding type EncodeType = QrCodeTypes.QR, // set signature position Left = 100, Top = 100 }; ImageSaveOptions saveOptions = new ImageSaveOptions() { FileFormat = ImageSaveFileFormat.Jpg, OverwriteExistingFiles = true }; // sign document to file SignResult result = signature.Sign(outputFilePath, signOptions, saveOptions); Console.WriteLine($"\nSource document signed successfully with {result.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); } }
public EMHSignResult SetSignatureValue(SignResult Status, IEMHSignature EMHSignature) { this.Status = Status; this.EMHSignature = EMHSignature; return(this); }
public EMHSignResult SetError(SignResult Status, String ErrorMessage) { this.Status = Status; this.ErrorMessage = ErrorMessage; return(this); }
private List <SignResult> FindSign(Image <Bgr, byte> image, Contour <Point> contours) { List <SignResult> results = new List <SignResult>(); for (; contours != null; contours = contours.HNext) { contours.ApproxPoly(contours.Perimeter * 0.02, 0, contours.Storage); if (contours.Area > 200) { double ratio = CvInvoke.cvMatchShapes(octagonContour, contours, Emgu.CV.CvEnum.CONTOURS_MATCH_TYPE.CV_CONTOURS_MATCH_I3, 0); if (ratio > 0.05) //not a good match of contour shape { results.AddRange(FindSignInChildren(image, contours)); } else { SignResult result = DetectSignInCurrentContour(image, contours); if (result != null) { results.Add(result); } } } } return(results); }
/// <summary> /// Sign document with text signature /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Basic Usage] # SignWithText : Sign document with text signature\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_PDF; string fileName = Path.GetFileName(filePath); string outputFilePath = Path.Combine(Constants.OutputPath, "SignWithText", fileName); using (Signature signature = new Signature(filePath)) { TextSignOptions options = new TextSignOptions("John Smith") { // set signature position Left = 50, Top = 200, // set signature rectangle Width = 100, Height = 30, // set Text color and Font ForeColor = Color.Red, Font = new SignatureFont { Size = 14, FamilyName = "Comic Sans MS" } }; // sign document to file SignResult result = signature.Sign(outputFilePath, options); Console.WriteLine($"\nSource document signed successfully with {result.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); } }
public async Task SignLocalVerifyRoundTrip([Fields(nameof(SignatureAlgorithm.ES256), nameof(SignatureAlgorithm.ES384), nameof(SignatureAlgorithm.ES512))] SignatureAlgorithm algorithm) { Key key = await CreateTestKey(algorithm); RegisterForCleanup(key); CryptographyClient client = GetCryptoClient(key.Id); byte[] data = new byte[32]; Recording.Random.NextBytes(data); using HashAlgorithm hashAlgo = algorithm.GetHashAlgorithm(); byte[] digest = hashAlgo.ComputeHash(data); // Should sign remotely... SignResult signResult = await client.SignAsync(algorithm, digest); Assert.AreEqual(algorithm, signResult.Algorithm); Assert.AreEqual(key.KeyMaterial.KeyId, signResult.KeyId); Assert.NotNull(signResult.Signature); // ...and verify locally. VerifyResult verifyResult = await client.VerifyAsync(algorithm, digest, signResult.Signature); Assert.AreEqual(algorithm, verifyResult.Algorithm); Assert.AreEqual(key.KeyMaterial.KeyId, verifyResult.KeyId); Assert.IsTrue(verifyResult.IsValid); }
protected void CheckResponse(SignResult result, TestFile testFile) { Assert.NotNull(result, "Result is empty."); Assert.NotNull(result.FileInfo, "FileInfo is null."); Assert.NotNull(String.IsNullOrEmpty(result.FileInfo?.FilePath), "FileInfo FilePath is empty."); Assert.AreNotEqual(testFile.Path, result.FileInfo?.FilePath, "FileInfo FilePath is wrong."); }
/// <summary> /// Sign document with image signature /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Basic Usage] # SignWithImage : Sign document with image\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_PDF; string fileName = Path.GetFileName(filePath); string imagePath = Constants.ImageHandwrite; string outputFilePath = Path.Combine(Constants.OutputPath, "SignWithImage", fileName); using (Signature signature = new Signature(filePath)) { ImageSignOptions options = new ImageSignOptions(imagePath) { // set signature position Left = 50, Top = 50, AllPages = true }; // sign document to file SignResult result = signature.Sign(outputFilePath, options); Console.WriteLine($"\nSource document signed successfully with {result.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); } }
/// <summary> /// Sign image document with metadata signature /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Basic Usage] # SignImageWithMetadata : Sign image document with metadata signature\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_IMAGE; string outputFilePath = Path.Combine(Constants.OutputPath, "SignImageWithMetadata", "SignedWithMetadata.png"); using (Signature signature = new Signature(filePath)) { // create Metadata option with predefined Metadata text MetadataSignOptions options = new MetadataSignOptions(); // Specify different Metadata Signatures and add them to options signature collection ushort imgsMetadataId = 41996; // Create several Image Metadata signatures with different types ImageMetadataSignature[] signatures = new ImageMetadataSignature[] { new ImageMetadataSignature(imgsMetadataId++, "Mr.Scherlock Holmes"), // String value new ImageMetadataSignature(imgsMetadataId++, DateTime.Now), // Date Time value new ImageMetadataSignature(imgsMetadataId++, 123456), // Integer value new ImageMetadataSignature(imgsMetadataId++, 123.456D), // Double value new ImageMetadataSignature(imgsMetadataId++, 123.456M), // Decimal value new ImageMetadataSignature(imgsMetadataId++, 123.456F), // Float value }; options.Signatures.AddRange(signatures); // sign document to file SignResult result = signature.Sign(outputFilePath, options); Console.WriteLine($"\nSource document signed successfully with {result.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); } }
/// <summary> /// Sign spreadsheets document with metadata signature /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Basic Usage] # SignSpreadsheetWithMetadata : Sign spreadsheets document with metadata signature\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_SPREADSHEET; string outputFilePath = Path.Combine(Constants.OutputPath, "SignSpreadsheetWithMetadata", "SignedWithMetadata.xlsx"); using (Signature signature = new Signature(filePath)) { // create Metadata option with predefined Metadata text MetadataSignOptions options = new MetadataSignOptions(); // Create few Spreadsheet Metadata signatures SpreadsheetMetadataSignature[] signatures = new SpreadsheetMetadataSignature[] { new SpreadsheetMetadataSignature("Author", "Mr.Scherlock Holmes"), // String value new SpreadsheetMetadataSignature("CreatedOn", DateTime.Now), // DateTime values new SpreadsheetMetadataSignature("DocumentId", 123456), // Integer value new SpreadsheetMetadataSignature("SignatureId", 123.456D), // Double value new SpreadsheetMetadataSignature("Amount", 123.456M), // Decimal value new SpreadsheetMetadataSignature("Total", 123.456F) // Float value }; options.Signatures.AddRange(signatures); // sign document to file SignResult result = signature.Sign(outputFilePath, options); Console.WriteLine($"\nSource document signed successfully with {result.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); } }
/// <summary> /// Sign document with barcode signature /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Basic Usage] # SignWithBarcode : Sign document with Barcode\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_PDF; string fileName = Path.GetFileName(filePath); string outputFilePath = Path.Combine(Constants.OutputPath, "SignWithBarcode", fileName); using (Signature signature = new Signature(filePath)) { // create barcode option with predefined barcode text BarcodeSignOptions options = new BarcodeSignOptions("JohnSmith") { // setup Barcode encoding type EncodeType = BarcodeTypes.Code128, // set signature position Left = 50, Top = 150, Width = 200, Height = 50 }; // sign document to file SignResult result = signature.Sign(outputFilePath, options); Console.WriteLine($"\nSource document signed successfully with {result.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); } }
/// <summary> /// Sign document with text signature applying Stamp implementation type (this is default value) /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Advanced Usage] # SignWithTextStamp : Sign document with text signature applying Stamp implementation type (this is default value)\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_WORDPROCESSING; string fileName = Path.GetFileName(filePath); string outputFilePath = Path.Combine(Constants.OutputPath, "SignWithTextStamp", fileName); using (Signature signature = new Signature(filePath)) { TextSignOptions options = new TextSignOptions("John Smith") { // set alternative signature implementation on document page SignatureImplementation = TextSignatureImplementation.Native, // set alignment VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, // set margin with 20 pixels for all sides Margin = new Padding(20) }; // sign document to file SignResult signResult = signature.Sign(outputFilePath, options); Console.WriteLine($"\nSource document signed successfully with {signResult.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); } }
/// <summary> /// Sign Image document with metadata signature with customer object and encryption /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Advanced Usage] # SignImageWithCustomMetadata : Sign Image document with metadata signature with customer object and encryption\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_IMAGE; string fileName = Path.GetFileName(filePath); string outputFilePath = Path.Combine(Constants.OutputPath, "SignImageWithCustomMetadata", fileName); using (Signature signature = new Signature(filePath)) { // setup key and passphrase string key = "1234567890"; string salt = "1234567890"; // create data encryption IDataEncryption encryption = new SymmetricEncryption(SymmetricAlgorithmType.Rijndael, key, salt); // setup options with text of signature MetadataSignOptions options = new MetadataSignOptions(); // create custom object DocumentSignatureData documentSignature = new DocumentSignatureData() { ID = Guid.NewGuid().ToString(), Author = Environment.UserName, Signed = DateTime.Now, DataFactor = 11.22M }; // Specify different Metadata Signatures and add them to options signature collection ushort imgsMetadataId = 41996; // Specify different Metadata Signatures and add them to options signature collection // setup Author property ImageMetadataSignature mdDocument = new ImageMetadataSignature(imgsMetadataId++, documentSignature); // set encryption mdDocument.DataEncryption = encryption; // setup Author property ImageMetadataSignature mdAuthor = new ImageMetadataSignature(imgsMetadataId++, "Mr.Scherlock Holmes"); // set encryption mdAuthor.DataEncryption = encryption; // setup data of document id ImageMetadataSignature mdDocId = new ImageMetadataSignature(imgsMetadataId++, Guid.NewGuid().ToString()); // set encryption mdDocId.DataEncryption = encryption; // add signatures to options options.Signatures.Add(mdDocument); options.Signatures.Add(mdAuthor); options.Signatures.Add(mdDocId); // sign document to file SignResult signResult = signature.Sign(outputFilePath, options); Console.WriteLine($"\nSource document signed successfully with {signResult.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); } }
public void SignReturnsNullOnUnsupported() { JsonWebKey jwk = KeyModelFactory.JsonWebKey(KeyType.Ec, curveName: "invalid", keyOps: new[] { KeyOperation.Sign }); EcCryptographyProvider client = new EcCryptographyProvider(new KeyVaultKey { Key = jwk }); SignResult result = client.Sign(default, new byte[] { 0xff }, default);
/// <summary> /// Sign document with digital signature applying specific options /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Advanced Usage] # SignWithDigitalAdvanced : Sign document with digital signature applying specific options\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_PDF; string fileName = Path.GetFileName(filePath); string imagePath = Constants.ImageStamp; string certificatePath = Constants.CertificatePfx; string outputFilePath = Path.Combine(Constants.OutputPath, "SignWithDigitalAdvanced", fileName); using (Signature signature = new Signature(filePath)) { DigitalSignOptions options = new DigitalSignOptions(certificatePath) { // certificate password Password = "******", // digital certificate details Reason = "Approved", Contact = "John Smith", Location = "New York", // image as digital certificate appearance on document pages ImageFilePath = imagePath, // AllPages = true, Width = 160, Height = 80, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Left, Margin = new Padding() { Bottom = 10, Right = 10 }, // setup signature border Border = new Border() { Visible = true, Color = Color.Red, DashStyle = DashStyle.DashDot, Weight = 2 }, }; SignResult signResult = signature.Sign(outputFilePath, options); Console.WriteLine($"\nSource document signed successfully with {signResult.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); Console.WriteLine("\nList of newly created signatures:"); int number = 1; foreach (BaseSignature temp in signResult.Succeeded) { Console.WriteLine($"Signature #{number++}: Type: {temp.SignatureType} Id:{temp.SignatureId}, Location: {temp.Left}x{temp.Top}. Size: {temp.Width}x{temp.Height}"); } } }
public async Task <SignResult> Sign(Guid transferId) { var signResult = new SignResult(); var transfer = _transferRepository.GetById(transferId); if (transfer == null) { signResult.ValidationResult.Messages.Add("The transfer that you want to sign doesn't exist"); return(signResult); } var account = _accountService.GetByUserId(transfer.UserId); var transferValidation = _transferValidator.Validate(transfer); if (transferValidation.Succeded) { var transaction = _mapper.Map <Transaction>(transfer); var exchangeRate = await _exchangeRateService.GetExchangeRate(DateTime.Today, transfer.DestinationCurrencyCode, account.CurrencyCode); if (exchangeRate == null) { signResult.ValidationResult.Messages.Add("There is no exchange rate available for the selected currencies."); return(signResult); } transaction.UsedRate = exchangeRate.Rate; transaction.UsedRateDate = exchangeRate.RateDate; transaction.IsBaseCurrencySameAsTo = exchangeRate.IsBaseCurrencySameAsTo; var transactionValidation = _transactionValidator.Validate(transaction); if (transactionValidation.Succeded) { transfer.Status = Status.Signed; transfer.UpdatedOn = DateTime.UtcNow; if (exchangeRate.IsBaseCurrencySameAsTo) { account.Balance -= transaction.Amount / transaction.UsedRate; } else { account.Balance -= transaction.Amount * transaction.UsedRate; } signResult.TransactionId = _transferRepository.SignTransfer(transfer, transaction, account); } else { signResult.ValidationResult.Messages.AddRange(transactionValidation.Messages); } } else { signResult.ValidationResult.Messages.AddRange(transferValidation.Messages); } return(signResult); }
public async Task DownloadECDsaCertificateSignRemoteVerifyLocal([EnumValues] CertificateContentType contentType, [EnumValues] CertificateKeyCurveName keyCurveName) { #if NET461 Assert.Ignore("ECC is not supported before .NET Framework 4.7"); #endif if (keyCurveName == CertificateKeyCurveName.P256K && RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Assert.Ignore("https://github.com/Azure/azure-sdk-for-net/issues/25472"); } string name = Recording.GenerateId(); CertificatePolicy policy = new CertificatePolicy { IssuerName = WellKnownIssuerNames.Self, Subject = "CN=default", KeyType = CertificateKeyType.Ec, KeyCurveName = keyCurveName, Exportable = true, KeyUsage = { CertificateKeyUsage.DigitalSignature, }, ContentType = contentType, }; CertificateOperation operation = await Client.StartCreateCertificateAsync(name, policy); RegisterForCleanup(name); await operation.WaitForCompletionAsync(DefaultCertificateOperationPollingInterval, default); // Sign data remotely. byte[] plaintext = Encoding.UTF8.GetBytes(nameof(DownloadECDsaCertificateSignRemoteVerifyLocal)); CryptographyClient cryptoClient = GetCryptographyClient(operation.Value.KeyId); SignResult result = await cryptoClient.SignDataAsync(keyCurveName.GetSignatureAlgorithm(), plaintext); // Download the certificate and verify data locally. X509Certificate2 certificate = null; try { certificate = await Client.DownloadCertificateAsync(name, operation.Value.Properties.Version); using ECDsa publicKey = certificate.GetECDsaPublicKey(); Assert.IsTrue(publicKey.VerifyData(plaintext, result.Signature, keyCurveName.GetHashAlgorithmName())); } catch (Exception ex) when(IsExpectedP256KException(ex, keyCurveName)) { Assert.Ignore("The curve is not supported by the current platform"); } finally { certificate?.Dispose(); } }
public void SignReturnsNullOnUnsupported() { JsonWebKey jwk = new JsonWebKey { CurveName = "invalid", KeyOps = new[] { KeyOperation.Sign }, }; EcCryptographyProvider client = new EcCryptographyProvider(jwk); SignResult result = client.Sign(default, new byte[] { 0xff }, default);
public override async Task RunAsync(CancellationToken cancellationToken) { SignResult result = await CryptographyClient.SignAsync(s_algorithm, _digest); byte[] signature = result.Signature; #if DEBUG Assert.AreEqual(256, signature.Length); #endif }
/// <summary> /// Sign document with text signature applying specific options /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Advanced Usage] # SignWithPdfTextAnnotation : Sign document with text signature applying specific options\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_PDF; string outputFilePath = Path.Combine(Constants.OutputPath, "SignWithAppearances", "PdfAnnotation.pdf"); using (Signature signature = new Signature(filePath)) { TextSignOptions options = new TextSignOptions("John Smith") { // set signature position Left = 50, Top = 200, // set signature rectangle Width = 100, Height = 30, // setup proper signature implementation SignatureImplementation = TextSignatureImplementation.Annotation, Appearance = new PdfTextAnnotationAppearance() { Border = new Border() { Color = Color.Blue, DashStyle = DashStyle.Dash, Weight = 2, }, BorderEffect = PdfTextAnnotationBorderEffect.Cloudy, BorderEffectIntensity = 2, HCornerRadius = 10, // text content of an annotation Contents = "Sample", Subject = "Sample subject", Title = "Sample Title", }, Margin = new Padding() { Bottom = 20, Right = 20 }, // set text color and Font ForeColor = Color.Red, Font = new SignatureFont { Size = 12, FamilyName = "Comic Sans MS" }, }; // sign document to file SignResult signResult = signature.Sign(outputFilePath, options); Console.WriteLine($"\nSource document signed successfully with {signResult.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); } }
/// <summary> /// Sign pdf document with metadata signature with customer object and encryption /// </summary> public static void Run() { Console.WriteLine("\n--------------------------------------------------------------------------------------------------------------------"); Console.WriteLine("[Example Advanced Usage] # SignWithMetadataEncryptedObject : Sign pdf document with metadata signature with customer object and encryption\n"); // The path to the documents directory. string filePath = Constants.SAMPLE_WORDPROCESSING; string outputFilePath = Path.Combine(Constants.OutputPath, "SignWithMetadataSecureCustom", "MetadataEncryptedObject.docx"); using (Signature signature = new Signature(filePath)) { // setup key and passphrase string key = "1234567890"; string salt = "1234567890"; // create data encryption IDataEncryption encryption = new SymmetricEncryption(SymmetricAlgorithmType.Rijndael, key, salt); // setup options with text of signature MetadataSignOptions options = new MetadataSignOptions() { // set encryption for all metadata signatures for this options // if you need separate encryption use own MetadataSignature.DataEncryption property DataEncryption = encryption }; // create custom object DocumentSignatureData documentSignatureData = new DocumentSignatureData() { ID = Guid.NewGuid().ToString(), Author = Environment.UserName, Signed = DateTime.Now, DataFactor = 11.22M }; // setup signature metadata WordProcessingMetadataSignature mdSignature = new WordProcessingMetadataSignature("Signature", documentSignatureData); // setup signature metadata WordProcessingMetadataSignature mdAuthor = new WordProcessingMetadataSignature("Author", "Mr.Scherlock Holmes"); // setup data of document id WordProcessingMetadataSignature mdDocId = new WordProcessingMetadataSignature("DocumentId", Guid.NewGuid().ToString()); // add signatures to options options.Signatures.Add(mdSignature); options.Signatures.Add(mdAuthor); options.Signatures.Add(mdDocId); // sign document to file SignResult signResult = signature.Sign(outputFilePath, options); Console.WriteLine($"\nSource document signed successfully with {signResult.Succeeded.Count} signature(s).\nFile saved at {outputFilePath}."); } }
public async Task SignDataStreamVerifyDataStreamRoundtrip([EnumValues(Exclude = new[] { nameof(SignatureAlgorithm.PS256), nameof(SignatureAlgorithm.PS384), nameof(SignatureAlgorithm.PS512) })] SignatureAlgorithm algorithm) { JsonWebKey jwk = KeyUtilities.CreateKey(algorithm, includePrivateParameters: true); LocalCryptographyClient client = CreateClient <LocalCryptographyClient>(jwk); SignResult signed = await client.SignDataAsync(algorithm, TestStream); VerifyResult verified = await client.VerifyDataAsync(algorithm, TestStream, signed.Signature); Assert.IsTrue(verified.IsValid); }
public async Task SignVerifyRoundtrip([EnumValues(Exclude = new[] { nameof(SignatureAlgorithm.PS256), nameof(SignatureAlgorithm.PS384), nameof(SignatureAlgorithm.PS512) })] SignatureAlgorithm algorithm) { JsonWebKey jwk = KeyUtilities.CreateKey(algorithm, includePrivateParameters: true); LocalCryptographyClient client = CreateClient <LocalCryptographyClient>(jwk); byte[] digest = algorithm.GetHashAlgorithm().ComputeHash(TestData); SignResult signed = await client.SignAsync(algorithm, digest); VerifyResult verified = await client.VerifyAsync(algorithm, digest, signed.Signature); Assert.IsTrue(verified.IsValid); }
private SignResult DetectSignInCurrentContour(Image<Bgr, byte> image, Contour<Point> contours) { SignResult result = null; Rectangle contourBoundingRectangle = contours.BoundingRectangle; Image<Gray, Byte> contourImage = GetGrayScaleImage(image, contourBoundingRectangle); contourImage = SetPixelsOutsideContourAreaToZero(contourImage, contourBoundingRectangle, contours); int matchedFeatureCount = GetMatchedFeatureCount(contourImage); if (matchedFeatureCount >= 3) { result = new SignResult(contourImage, contourBoundingRectangle); } return result; }