public async Task <byte[]> Sign(byte[] source, SigningProperties signingProperties) { using (var inputStream = new MemoryStream(source)) using (var reader = new PdfReader(inputStream)) using (var outputStream = new MemoryStream()) { var stampProps = new StampingProperties(); var signer = new PdfSigner(reader, outputStream, stampProps); signer.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED); var sap = signer.GetSignatureAppearance(); sap.SetLocation(signingProperties.Location); sap.SetReason(signingProperties.Reason); sap.SetReuseAppearance(false); var certData = await s3Repository.GetDocument(signingProperties.Bucket, signingProperties.Key); // code from https://stackoverflow.com/questions/12470498/how-to-read-the-pfx-file using (var keyStream = new MemoryStream(certData)) { var passphrase = signingProperties.Password; if (signingProperties.KMSData != null) { // key is encrypted with KSM var key = await kSMRepository.GetKey(signingProperties.KMSData); passphrase = kSMRepository.DecryptData(passphrase, key); } var store = new Pkcs12Store(keyStream, signingProperties.Password.ToCharArray()); string alias = store.Aliases.OfType <string>().First(x => store.IsKeyEntry(x)); var privateKey = store.GetKey(alias).Key; var keyChain = store.GetCertificateChain(alias) .Select(x => x.Certificate).ToArray(); IExternalSignature externalSignature = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256); signer.SignDetached(externalSignature, keyChain, null, null, null, 0, PdfSigner.CryptoStandard.CADES); return(outputStream.ToArray()); } } }
public async Task <IActionResult> Post([FromBody] Input input) { if (!CanDoThings(input)) { return(BadRequest(":(")); } var source = await s3Repository.GetDocument(input.SourceBucket, input.SourceFile); var output = documentRepository.Transform(input, source); if (input.DoSign) { output = await documentRepository.Sign(output, input.SigningProperties); } return(File(output, "application/pdf", Guid.NewGuid().ToString() + ".pdf")); }