Exemplo n.º 1
0
        private async Task SynchronizeAsync(string localSigName, string localSigSigName, string remoteSigName,
                                            string remoteSigSigName, CancellationToken token)
        {
            using (var needListGenerator = new NeedListGenerator(localSignatureRepository, remoteCacheSignatureRepository))
            {
                var source   = new RemoteSignaturePartialAccess(synchronizationServerClient, remoteSigName);
                var seed     = new SignaturePartialAccess(localSigName, localSignatureRepository);
                var needList = needListGenerator.CreateNeedsList(SignatureInfo.Parse(localSigSigName),
                                                                 SignatureInfo.Parse(remoteSigSigName), token);

                using (var output = remoteCacheSignatureRepository.CreateContent(remoteSigName))
                {
                    await NeedListParser.ParseAsync(source, seed, output, needList, token);
                }
            }
        }
Exemplo n.º 2
0
        public void GetSigner()
        {
            String[] testFiles =
            {
                "hyperlink-example-signed.docx",
                "hello-world-signed.docx",
                "hello-world-signed.pptx",
                "hello-world-signed.xlsx",
                "hello-world-office-2010-technical-preview.docx",
                "ms-office-2010-signed.docx",
                "ms-office-2010-signed.pptx",
                "ms-office-2010-signed.xlsx",
                "Office2010-SP1-XAdES-X-L.docx",
                "signed.docx",
            };

            foreach (String testFile in testFiles)
            {
                OPCPackage pkg = OPCPackage.Open(testdata.GetFileInfo(testFile), PackageAccess.READ);
                try {
                    SignatureConfig sic = new SignatureConfig();
                    sic.SetOpcPackage(pkg);
                    SignatureInfo si = new SignatureInfo();
                    si.SetSignatureConfig(sic);
                    List <X509Certificate> result = new List <X509Certificate>();
                    foreach (SignatureInfo.SignaturePart sp in si.GetSignatureParts())
                    {
                        if (sp.Validate())
                        {
                            result.Add(sp.GetSigner());
                        }
                    }

                    Assert.IsNotNull(result);
                    Assert.AreEqual(1, result.Count, "test-file: " + testFile);
                    X509Certificate signer = result[0];
                    //LOG.Log(POILogger.DEBUG, "signer: " + signer.SubjectX500Principal);

                    bool b = si.VerifySignature();
                    Assert.IsTrue(b, "test-file: " + testFile);
                    pkg.Revert();
                } finally {
                    pkg.Close();
                }
            }
        }
 public TemporaryExposureKeyService(IConfiguration config)
 {
     AppBundleId = config["AppBundleId"];
     AndroidPackage = config["AndroidPackage"];
     SignatureAlgorithm = config["SignatureAlgorithm"];
     VerificationKeyIds = config["VerificationKeyIds"].Split(' ');
     VerificationKeyVersions = config["VerificationKeyVersions"].Split(' ');
     Signature = Convert.FromBase64String(config["Signature"]);
     Region = config["Region"];
     var sig = new SignatureInfo();
     sig.AppBundleId = AppBundleId;
     sig.AndroidPackage = AndroidPackage;
     sig.SignatureAlgorithm = SignatureAlgorithm;
     sig.VerificationKeyId = VerificationKeyIds.Last();
     sig.VerificationKeyVersion = VerificationKeyVersions.Last();
     SigInfo = sig;               
 }
        public void EqualsMethodWithSetValue()
        {
            // preparation
            var instance = new SignatureInfo();

            instance.AndroidPackage         = "AndroidPackage";
            instance.AppBundleId            = "AppBundleId";
            instance.SignatureAlgorithm     = "SignatureAlgorithm";
            instance.VerificationKeyId      = "VerificationKeyId";
            instance.VerificationKeyVersion = "VerificationKeyVersion";
            // action
            var actual1 = instance.Clone();
            var actual2 = new SignatureInfo(instance);
            var actual3 = new SignatureInfo();
            var actual4 = new SignatureInfo();

            using var memory   = new MemoryStream();
            using var codedOut = new CodedOutputStream(memory, true);
            instance.WriteTo(codedOut);
            codedOut.Flush();
            memory.Position   = 0;
            using var codedIn = new CodedInputStream(memory, true);
            actual3.MergeFrom(codedIn);
            actual4.MergeFrom(actual3);
            // assert
            Assert.AreEqual(instance, actual1);
            Assert.AreEqual(instance, actual2);
            Assert.AreEqual(instance, actual3);
            Assert.AreEqual(instance, actual4);
            Assert.AreEqual(instance.GetHashCode(), actual1.GetHashCode());
            Assert.AreEqual(instance.GetHashCode(), actual2.GetHashCode());
            Assert.AreEqual(instance.GetHashCode(), actual3.GetHashCode());
            Assert.AreEqual(instance.GetHashCode(), actual4.GetHashCode());
            Assert.AreEqual(instance.CalculateSize(), actual1.CalculateSize());
            Assert.AreEqual(instance.CalculateSize(), actual2.CalculateSize());
            Assert.AreEqual(instance.CalculateSize(), actual3.CalculateSize());
            Assert.AreEqual(instance.CalculateSize(), actual4.CalculateSize());
            Assert.AreEqual(instance.ToString(), actual1.ToString());
            Assert.AreEqual(instance.ToString(), actual2.ToString());
            Assert.AreEqual(instance.ToString(), actual3.ToString());
            Assert.AreEqual(instance.ToString(), actual4.ToString());
        }
Exemplo n.º 5
0
        public void EqualsMethodWithClear()
        {
            // preparation
            var instance = new SignatureInfo();

            instance.SignatureAlgorithm     = "SignatureAlgorithm";
            instance.VerificationKeyId      = "VerificationKeyId";
            instance.VerificationKeyVersion = "VerificationKeyVersion";
            var actual = instance.Clone();

            // action assert
            actual.ClearSignatureAlgorithm();
            Assert.AreNotEqual(instance, actual);
            actual = instance.Clone();
            actual.ClearVerificationKeyId();
            Assert.AreNotEqual(instance, actual);
            actual = instance.Clone();
            actual.ClearVerificationKeyVersion();
            Assert.AreNotEqual(instance, actual);
        }
Exemplo n.º 6
0
        private async Task <SynchronizationReport> SynchronizeTo(IAsyncFilesSynchronizationCommands destination,
                                                                 ISignatureRepository localSignatureRepository,
                                                                 ISignatureRepository remoteSignatureRepository,
                                                                 SignatureManifest sourceSignatureManifest,
                                                                 SignatureManifest destinationSignatureManifest)
        {
            var seedSignatureInfo   = SignatureInfo.Parse(destinationSignatureManifest.Signatures.Last().Name);
            var sourceSignatureInfo = SignatureInfo.Parse(sourceSignatureManifest.Signatures.Last().Name);

            using (var localFile = StorageStream.Reading(Storage, FileName))
            {
                IList <RdcNeed> needList;
                using (var needListGenerator = new NeedListGenerator(remoteSignatureRepository, localSignatureRepository))
                {
                    needList = needListGenerator.CreateNeedsList(seedSignatureInfo, sourceSignatureInfo, Cts.Token);
                }

                return(await PushByUsingMultipartRequest(destination, localFile, needList));
            }
        }
            protected async Task <bool> TryFinishInitializingStateAsync(TService service, SemanticDocument document, CancellationToken cancellationToken)
            {
                cancellationToken.ThrowIfCancellationRequested();
                TypeToGenerateIn = await SymbolFinder.FindSourceDefinitionAsync(TypeToGenerateIn, document.Project.Solution, cancellationToken).ConfigureAwait(false) as INamedTypeSymbol;

                if (TypeToGenerateIn.IsErrorType())
                {
                    return(false);
                }

                if (!service.ValidateTypeToGenerateIn(document.Project.Solution, TypeToGenerateIn,
                                                      IsStatic, ClassInterfaceModuleStructTypes))
                {
                    return(false);
                }

                if (!CodeGenerator.CanAdd(document.Project.Solution, TypeToGenerateIn, cancellationToken))
                {
                    return(false);
                }

                // Ok.  It either didn't bind to any symbols, or it bound to a symbol but with
                // errors.  In the former case we definitely want to offer to generate a method.  In
                // the latter case, we want to generate a method *unless* there's an existing method
                // with the same signature.
                var existingMethods = TypeToGenerateIn.GetMembers(IdentifierToken.ValueText)
                                      .OfType <IMethodSymbol>();

                var destinationProvider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language);
                var syntaxFacts         = destinationProvider.GetService <ISyntaxFactsService>();
                var syntaxFactory       = destinationProvider.GetService <SyntaxGenerator>();

                IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn);
                var generatedMethod = SignatureInfo.GenerateMethod(syntaxFactory, false, cancellationToken);

                return(!existingMethods.Any(m => SignatureComparer.Instance.HaveSameSignature(m, generatedMethod, caseSensitive: syntaxFacts.IsCaseSensitive, compareParameterName: true, isParameterCaseSensitive: syntaxFacts.IsCaseSensitive)));
            }
Exemplo n.º 8
0
        private void AddSpecialCaseDetails(InnerError error)
        {
            if (!error.Data.ContainsKey(Error.KnownDataKeys.ExtraProperties))
            {
                return;
            }

            var extraProperties = error.Data.GetValue <Dictionary <string, object> >(Error.KnownDataKeys.ExtraProperties);

            if (extraProperties == null)
            {
                return;
            }

            if (extraProperties.ContainsKey("Number"))
            {
                SignatureInfo.Add("Number", extraProperties["Number"].ToString());
            }

            if (extraProperties.ContainsKey("ErrorCode"))
            {
                SignatureInfo.Add("ErrorCode", extraProperties["ErrorCode"].ToString());
            }
        }
Exemplo n.º 9
0
        private void AddSpecialCaseDetails(ErrorInfo error)
        {
            if (!error.ExtendedData.ContainsKey(ExtendedDataDictionary.EXCEPTION_INFO_KEY))
            {
                return;
            }

            var extraProperties = error.ExtendedData.GetValue <Dictionary <string, object> >(ExtendedDataDictionary.EXCEPTION_INFO_KEY);

            if (extraProperties == null)
            {
                return;
            }

            if (extraProperties.ContainsKey("Number"))
            {
                SignatureInfo.Add("Number", extraProperties["Number"].ToString());
            }

            if (extraProperties.ContainsKey("ErrorCode"))
            {
                SignatureInfo.Add("ErrorCode", extraProperties["ErrorCode"].ToString());
            }
        }
Exemplo n.º 10
0
        private void Parse()
        {
            SignatureInfo.Clear();

            // start at the inner most exception and work our way out until we find a user method
            InnerError current    = Error;
            var        errorStack = new List <InnerError> {
                current
            };

            while (current.Inner != null)
            {
                current = current.Inner;
                errorStack.Add(current);
            }

            errorStack.Reverse();

            // reset all flags before we figure out which method to tag as the new target.
            if (ShouldFlagSignatureTarget)
            {
                errorStack.ForEach(es => es.StackTrace.ForEach(st => st.IsSignatureTarget = false));
            }

            foreach (InnerError e in errorStack)
            {
                StackFrameCollection stackTrace = e.StackTrace;
                if (stackTrace == null)
                {
                    continue;
                }

                foreach (StackFrame stackFrame in stackTrace.Where(IsUserFrame))
                {
                    SignatureInfo.AddItemIfNotEmpty("ExceptionType", e.Type);
                    SignatureInfo.AddItemIfNotEmpty("Method", GetStackFrameSignature(stackFrame));
                    if (ShouldFlagSignatureTarget)
                    {
                        stackFrame.IsSignatureTarget = true;
                    }
                    AddSpecialCaseDetails(e);
                    UpdateInfo(true);
                    return;
                }
            }

            // We haven't found a user method yet, try some alternatives with the inner most error.
            InnerError innerMostError = errorStack[0];

            if (innerMostError.TargetMethod != null)
            {
                // Use the target method if it exists.
                SignatureInfo.AddItemIfNotEmpty("ExceptionType", innerMostError.Type);
                SignatureInfo.AddItemIfNotEmpty("Method", GetStackFrameSignature(innerMostError.TargetMethod));
                if (ShouldFlagSignatureTarget)
                {
                    innerMostError.TargetMethod.IsSignatureTarget = true;
                }
            }
            else if (innerMostError.StackTrace != null && innerMostError.StackTrace.Count > 0)
            {
                // Use the topmost stack frame.
                SignatureInfo.AddItemIfNotEmpty("ExceptionType", innerMostError.Type);
                SignatureInfo.AddItemIfNotEmpty("Method", GetStackFrameSignature(innerMostError.StackTrace[0]));
                if (ShouldFlagSignatureTarget)
                {
                    innerMostError.StackTrace[0].IsSignatureTarget = true;
                }
            }
            else
            {
                // All else failed, use the type.
                SignatureInfo.AddItemIfNotEmpty("ExceptionType", innerMostError.Type);
            }

            AddSpecialCaseDetails(innerMostError);
            if (SignatureInfo.Count == 0)
            {
                SignatureInfo.Add("NoStackingInformation", Guid.NewGuid().ToString());
            }

            UpdateInfo(false);
        }
 public void CreateMethod()
 {
     // preparation
     var instance = new SignatureInfo();
 }
Exemplo n.º 12
0
        public override void Emit(CodeGen cg)
        {
            cg.EmitPosition(start, header);
            SignatureInfo sigInfo = SignatureInfo.Get(this, cg);

            FlowChecker.Check(this);

            string mname = name.GetString() + "$f" + counter++;

            // create the new method & setup it's locals
            CodeGen impl = cg.DefineMethod(mname, typeof(object), sigInfo.ParamTypes, sigInfo.ParamNames);

            impl.Names   = CodeGen.CreateLocalNamespace(impl);
            impl.Context = cg.Context;

            for (int arg = sigInfo.HasContext ? 1 : 0; arg < sigInfo.ParamNames.Length; arg++)
            {
                impl.Names.SetSlot(sigInfo.ParamNames[arg], impl.GetArgumentSlot(arg));
            }

            // then generate the actual method
            EmitFunctionImplementation(cg, impl, sigInfo.HasContext);
            if (NeedsWrapperMethod())
            {
                impl = MakeWrapperMethodN(cg, impl.MethodInfo, sigInfo.HasContext);
            }

            //  Create instance of the Function? object
            Type funcType, targetType;

            using (impl) {
                GetFunctionType(out funcType, out targetType);
                cg.EmitModuleInstance();
                cg.EmitString(name.GetString());

                cg.EmitDelegate(impl, targetType, sigInfo.ContextSlot);
            }

            int first = sigInfo.HasContext ? 1 : 0;

            //  Emit string array (minus the first environment argument)
            cg.EmitInt(sigInfo.ParamNames.Length - first);
            cg.Emit(OpCodes.Newarr, typeof(string));
            for (int i = first; i < sigInfo.ParamNames.Length; i++)
            {
                cg.Emit(OpCodes.Dup);
                cg.EmitInt(i - first);
                cg.EmitStringOrNull(sigInfo.ParamNames[i].GetString());
                cg.Emit(OpCodes.Stelem_Ref);
            }
            cg.EmitObjectArray(defaults);

            if (flags == FuncDefType.None)
            {
                cg.Emit(OpCodes.Newobj, funcType.GetConstructor(
                            new Type[] { typeof(PythonModule), typeof(string), targetType, typeof(string[]), typeof(object[]) }));
            }
            else
            {
                cg.EmitInt((int)flags);
                cg.Emit(OpCodes.Newobj, funcType.GetConstructor(
                            new Type[] { typeof(PythonModule), typeof(string), targetType, typeof(string[]), typeof(object[]), typeof(FuncDefType) }));
            }

            string doc = body.GetDocString();

            if (doc != null)
            {
                cg.Emit(OpCodes.Dup);
                cg.EmitString(doc);
                cg.EmitCall(typeof(PythonFunction).GetProperty("Documentation").GetSetMethod());
            }

            // update func_code w/ appropriate state.
            cg.Emit(OpCodes.Dup);

            cg.EmitCall(typeof(PythonFunction).GetProperty("FunctionCode").GetGetMethod());
            cg.Emit(OpCodes.Castclass, typeof(FunctionCode));
            cg.Emit(OpCodes.Dup);
            cg.EmitInt(this.start.line);
            cg.EmitCall(typeof(FunctionCode), "SetLineNumber");

            cg.EmitString(this.filename);
            cg.EmitCall(typeof(FunctionCode), "SetFilename");

            cg.EmitSet(name);

            if (decorators != null)
            {
                decorators.Emit(cg);
                cg.EmitSet(name);
            }
        }
 /// <summary>
 /// Replaces the "|" in the signature string with new lines.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 string GetSignature(SignatureInfo info)
 {
     return(info.Signature.Replace("|", "\r\n"));
 }
Exemplo n.º 14
0
        public override void TextInput(TextCompositionEventArgs args)
        {
            if ((args.Handled) || (!Session.Current.Settings.EnableXmlDocumentation))
            {
                return;
            }

            if (args.Text != "/")
            {
                return;
            }

            CurrentLineInformation lineInformation = this.KeyProcessor.CurrentLineInformation;

            if ((lineInformation.LineText == "//") && (lineInformation.CaretColumn == 2))
            {
                IMethod activeMethod = this.KeyProcessor.MethodManager.ActiveMethod;
                if (activeMethod != null)
                {
                    Tuple <SnapshotPoint, SnapshotPoint> methodInterval = activeMethod.GetCodeInterval();
                    int size = lineInformation.CaretPosition - methodInterval.Item1.Position;
                    //we don't want to process too long texts, let's assume that max. indent is 30 characters and it doc. shoudl always start in the first line
                    if (size == 2)
                    {
                        IEnumerable <string> methodLines = activeMethod.GetLines();
                        if (CanGenerateXmlDocumentation(methodLines))
                        {
                            int moveUp = 2;

                            this.KeyProcessor.EditorOperations.InsertText("/ <summary>");
                            this.KeyProcessor.EditorOperations.InsertNewLine();
                            this.KeyProcessor.EditorOperations.InsertText("/// ");
                            this.KeyProcessor.EditorOperations.InsertNewLine();
                            this.KeyProcessor.EditorOperations.InsertText("/// </summary>");
                            this.KeyProcessor.EditorOperations.InsertNewLine();

                            //try to find current method
                            try
                            {
                                List <SignatureInfo> signatures = this.KeyProcessor.NavConnector.TypeInfoManager.GetSignatures(activeMethod.Name).ToList();

                                if (signatures.Count > 0)
                                {
                                    SignatureInfo signature = signatures[0];
                                    foreach (ParameterInfo parameterInfo in signature.Parameters)
                                    {
                                        this.KeyProcessor.EditorOperations.InsertText($"/// <param name=\"{parameterInfo.ParameterName}\"></param>");
                                        this.KeyProcessor.EditorOperations.InsertNewLine();
                                        moveUp++;
                                    }
                                    if ((signature.ReturnType != null) && (!String.IsNullOrWhiteSpace(signature.ReturnType.TypeName)))
                                    {
                                        this.KeyProcessor.EditorOperations.InsertText("/// <returns></returns>");
                                        this.KeyProcessor.EditorOperations.InsertNewLine();
                                        moveUp++;
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                DebugLog.WriteLogEntry(e.Message);
                                DebugLog.WriteLogEntry(e.Source);
                                DebugLog.WriteLogEntry(e.StackTrace);
                            }

                            for (int i = 0; i < moveUp; i++)
                            {
                                this.KeyProcessor.EditorOperations.MoveLineUp(false);
                            }
                            this.KeyProcessor.EditorOperations.MoveToEndOfLine(false);

                            args.Handled = true;
                        }
                    }
                }
            }
        }
Exemplo n.º 15
0
 public async Task SetSignatureAsync(SignatureInfo info)
 {
     Logger.LogInformation($"start {nameof(SetSignatureAsync)}");
     info.VerificationKeyId      = "DebugKey";
     info.VerificationKeyVersion = "DebugVersion";
 }
Exemplo n.º 16
0
        private static ISignatureInfo ParseSignature(string functionName, ParseContext context)
        {
            var info = new SignatureInfo(functionName);
            var signatureArguments = new List <IArgumentInfo>();

            // RD data may contain function name(s) without braces
            if (context.Tokens.CurrentToken.TokenType == RTokenType.OpenBrace)
            {
                var functionCall = new FunctionCall();
                functionCall.Parse(context, context.AstRoot);

                for (var i = 0; i < functionCall.Arguments.Count; i++)
                {
                    var arg = functionCall.Arguments[i];

                    string argName         = null;
                    string argDefaultValue = null;
                    var    isEllipsis      = false;
                    var    isOptional      = false;

                    var expArg = arg as ExpressionArgument;
                    if (expArg != null)
                    {
                        argName = context.TextProvider.GetText(expArg.ArgumentValue);
                    }
                    else
                    {
                        if (arg is NamedArgument nameArg)
                        {
                            argName         = context.TextProvider.GetText(nameArg.NameRange);
                            argDefaultValue = nameArg.DefaultValue != null?
                                              RdText.CleanRawRdText(context.TextProvider.GetText(nameArg.DefaultValue)) : string.Empty;
                        }
                        else
                        {
                            if (arg is MissingArgument)
                            {
                                argName = string.Empty;
                            }
                            else
                            {
                                if (arg is EllipsisArgument)
                                {
                                    argName    = "...";
                                    isEllipsis = true;
                                }
                            }
                        }
                    }

                    var argInfo = new ArgumentInfo(argName)
                    {
                        DefaultValue = argDefaultValue,
                        IsEllipsis   = isEllipsis,
                        IsOptional   = isOptional
                    };
                    // TODO: actually parse

                    signatureArguments.Add(argInfo);
                }
            }

            info.Arguments = signatureArguments;
            return(info);
        }
Exemplo n.º 17
0
        private void DoTest(GenericAsyncClient client, TimeStampAuthorityClient tsaClient)
        {
            //Create common input with info about the requestor, must match SAML
            CommonInputType commonInput = new CommonInputType();

            commonInput.InputReference                         = "TADM1234567890";
            commonInput.Request                                = new RequestType();
            commonInput.Request.IsTest                         = true;
            commonInput.Origin                                 = new OrigineType();
            commonInput.Origin.Package                         = new PackageType();
            commonInput.Origin.Package.Name                    = "eH-I Test";
            commonInput.Origin.Package.License                 = new LicenseType();
            commonInput.Origin.Package.License.Username        = "******";      //provide you own license
            commonInput.Origin.Package.License.Password        = "******"; //provide your own password
            commonInput.Origin.SiteID                          = "01";       //CareNet Gateway ID.
            commonInput.Origin.CareProvider                    = new CareProviderType();
            commonInput.Origin.CareProvider.Nihii              = new NihiiType();
            commonInput.Origin.CareProvider.Nihii.Quality      = "hospital";
            commonInput.Origin.CareProvider.Nihii.Value        = "71022212000";
            commonInput.Origin.CareProvider.Organization       = new IdType();
            commonInput.Origin.CareProvider.Organization.Nihii = commonInput.Origin.CareProvider.Nihii;

            //create blob value
            Stream        raw      = new MemoryStream(Encoding.ASCII.GetBytes(RandomString(1024 * 1024))); //you might use a file instead
            MemoryStream  deflated = new MemoryStream();
            DeflateStream deflater = new DeflateStream(deflated, CompressionMode.Compress, true);

            raw.CopyTo(deflater);
            deflater.Flush();
            deflater.Close();

            //create blob
            Blob blob = new Blob();

            blob.MessageName = "ADM";
            blob.Id          = "_" + Guid.NewGuid().ToString();
            blob.ContentType = "text/plain";
            blob.Value       = deflated.ToArray();

            //Create Xml with the blob inside it to sign.
            XmlDocument signDoc;

            using (MemoryStream signDocStream = new MemoryStream()) {
                XmlWriter signDocWriter = XmlWriter.Create(signDocStream);
                signDocWriter.WriteStartElement("root");

                XmlSerializer serializer = new XmlSerializer(typeof(Blob), new XmlRootAttribute("Detail"));
                serializer.Serialize(signDocWriter, blob);

                signDocWriter.WriteEndElement();
                signDocWriter.Flush();

                signDocStream.Seek(0, SeekOrigin.Begin);
                signDoc = new XmlDocument();
                signDoc.PreserveWhitespace = true;
                signDoc.Load(signDocStream);
            }

            //create the xades-t
            var xigner = new XadesCreator(sign);

            xigner.TimestampProvider = new EHealthTimestampProvider(tsaClient);
            xigner.DataTransforms.Add(new XmlDsigBase64Transform());
            xigner.DataTransforms.Add(new OptionalDeflateTransform());
            XmlElement xades = xigner.CreateXadesT(signDoc, blob.Id);

            //conver the xades-t to byte array
            MemoryStream xadesSteam = new MemoryStream();

            using (var writer = XmlWriter.Create(xadesSteam))
            {
                xades.WriteTo(writer);
            }

            //Create the Base64 structure
            base64Binary xadesParam = new base64Binary();

            xadesParam.contentType = "text/xml";
            xadesParam.Value       = xadesSteam.ToArray();

            //Send the message
            Thread.Sleep(1000); //sleep to let the eID recover :(
            TAck nipAck = client.post(commonInput, blob, xadesParam);

            //check if the messages was correctly send
            Assert.AreEqual("urn:nip:tack:result:major:success", nipAck.ResultMajor);

            //Get any waiting responses
            MsgQuery msgQuery = new MsgQuery();

            msgQuery.Max     = 1; //best to specify to avoid quota exceeds or memory issues
            msgQuery.Include = true;
            Query tackQuery = new Query();

            tackQuery.Max     = 10; //best to specify, but since they are smaller we can handle more
            tackQuery.Include = true;

            //Get the messages & tACK
            Thread.Sleep(1000); //sleep to let the eID recover :(
            Responses rsp = client.get(commonInput.Origin, msgQuery, tackQuery);

            //Collect the hash values of the messages & the tack
            //Should be a list of bytes arrays, but WCF isn't that smart so you need to do the encoding (base64, sperated by spaces)
            StringBuilder msgHashValues = new StringBuilder();

            if (rsp.MsgResponse != null)
            {
                foreach (MsgResponse msgRsp in rsp.MsgResponse)
                {
                    //Parse the xades, and rework it to a doc that contains the detail & xades.
                    XmlDocument verifyDoc;
                    using (MemoryStream verifyDocStream = new MemoryStream())
                    {
                        //Create new doc with element root
                        XmlWriter verifyDocWriter = XmlWriter.Create(verifyDocStream);
                        verifyDocWriter.WriteStartElement("root", "urn:dummy");

                        //Add blob (detail)
                        XmlSerializer serializer = new XmlSerializer(typeof(Blob), "urn:be:cin:types:v1");
                        serializer.Serialize(verifyDocWriter, msgRsp.Detail);

                        //Add xades-T
                        XmlDocument xadesDoc = new XmlDocument();
                        xadesDoc.PreserveWhitespace = true;
                        xadesDoc.Load(new MemoryStream(msgRsp.Xadest.Value));
                        xadesDoc.DocumentElement.WriteTo(verifyDocWriter);

                        verifyDocWriter.WriteEndElement();
                        verifyDocWriter.Flush();

                        //Reload the result
                        verifyDocStream.Seek(0, SeekOrigin.Begin);
                        verifyDoc = new XmlDocument();
                        verifyDoc.PreserveWhitespace = true;
                        verifyDoc.Load(verifyDocStream);

                        //Validate the doc
                        XmlElement    prop     = (XmlElement)XadesTools.FindXadesProperties(verifyDoc.DocumentElement)[0];
                        XadesVerifier verifier = new XadesVerifier();
                        verifier.RevocationMode = X509RevocationMode.NoCheck; //only for testing
                        verifier.TrustedTsaCerts.Add(tsaTrust);
                        SignatureInfo info = verifier.Verify(verifyDoc, prop);

                        //check info (time & certificate) to your own rules.
                    }

                    if (msgHashValues.Length != 0)
                    {
                        msgHashValues.Append(" ");
                    }
                    msgHashValues.Append(Convert.ToBase64String(msgRsp.Detail.HashValue));
                }
            }
            List <String> resend       = new List <string>();
            StringBuilder tackContents = new StringBuilder();

            if (rsp.TAckResponse != null)
            {
                foreach (TAckResponse tackRsp in rsp.TAckResponse)
                {
                    //Parse the xades, and rework it to a doc that contains the detail & xades.
                    XmlDocument verifyDoc;
                    using (MemoryStream verifyDocStream = new MemoryStream())
                    {
                        //Create new doc with element root
                        XmlWriter verifyDocWriter = XmlWriter.Create(verifyDocStream);
                        verifyDocWriter.WriteStartElement("root", "urn:dummy");

                        //Add blob (detail)
                        XmlSerializer serializer = new XmlSerializer(typeof(TAck), "urn:be:cin:nip:async:generic");
                        serializer.Serialize(verifyDocWriter, tackRsp.TAck);

                        //Add xades-T
                        XmlDocument xadesDoc = new XmlDocument();
                        xadesDoc.PreserveWhitespace = true;
                        xadesDoc.Load(new MemoryStream(tackRsp.Xadest.Value));
                        xadesDoc.DocumentElement.WriteTo(verifyDocWriter);

                        verifyDocWriter.WriteEndElement();
                        verifyDocWriter.Flush();

                        //Reload the result
                        verifyDocStream.Seek(0, SeekOrigin.Begin);
                        verifyDoc = new XmlDocument();
                        verifyDoc.PreserveWhitespace = true;
                        verifyDoc.Load(verifyDocStream);

                        //Validate the doc
                        XmlElement    prop     = (XmlElement)XadesTools.FindXadesProperties(verifyDoc.DocumentElement)[0];
                        XadesVerifier verifier = new XadesVerifier();
                        verifier.RevocationMode = X509RevocationMode.NoCheck; //only for testing
                        verifier.TrustedTsaCerts.Add(tsaTrust);
                        SignatureInfo info = verifier.Verify(verifyDoc, prop);

                        //check info (time & certificate) to your own rules.
                    }

                    //send failed, resend later.
                    if ("urn:nip:tack:result:major:success" != tackRsp.TAck.ResultMajor)
                    {
                        resend.Add(tackRsp.TAck.AppliesTo);
                    }

                    if (tackContents.Length != 0)
                    {
                        tackContents.Append(" ");
                    }
                    tackContents.Append(Convert.ToBase64String(tackRsp.TAck.Value)); //the content of the tAck is already a hash...
                }
            }

            //Confirm the received messages & tack
            Thread.Sleep(1000); //sleep to let the eID recover :(
            client.confirm(commonInput.Origin, msgHashValues.ToString(), tackContents.ToString());

            //We should not have anything to resend
            Assert.AreEqual(0, resend.Count);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Create user access
        /// </summary>
        /// <returns>access id</returns>
        public string CreateUserAccess(string userTitle, string userName, string userFirstname, string userPhoneNumber, string backUrl)
        {
            try
            {
                //#3- Ouverture d'un acces pour utilisateur
                //Data from certificate
                UserDN userDN = new UserDN()
                {
                    countryName = "FR",
                    organizationName = "UPSIDEO",
                    organizationalUnitName = "0002 538 768 003",
                    //emailAddress = "<Ne pas valoriser>",
                    commonName = "UPSIDEO", //<Prénom Nom>
                };

                SignatureInfo signatureInfo = new SignatureInfo()
                {
                    title = userTitle,
                    lastName = (!string.IsNullOrEmpty(userName)) ? userName : "******",
                    firstName = (!string.IsNullOrEmpty(userFirstname)) ? userFirstname : " ",
                    userDN = userDN
                };

                AuthenticationInfo authenticationInfo = new AuthenticationInfo()
                {
                    phoneNumber = this.GetCorrectDictaoMobile(userPhoneNumber),
                };

                string userId = System.Guid.NewGuid().ToString();

                PersonalInfo personalInfo = new PersonalInfo()
                {
                    userId = userId,
                    signatureInfo = signatureInfo,
                    authenticationInfo = authenticationInfo                    
                };

                //string consent = "J'ai bien lu les documents ci-contre que j'accepte de signer selon les termes des conditions générales et de la convention de preuve. J'ai connaissance du fait que la signature des documents au moyen d'une signature électronique manifeste mon consentement aux droits et obligations qui en découlent, au même titre qu'une signature manuscrite. J'accepte la ${TermAndConditionsUrl}."; // et la convention de preuve
                //Appendix doc
                List<string> appendixDocs = new List<string>();
                for (int i = 1; i <= AppendixCount; i++)
                {
                    appendixDocs.Add(string.Format("{0}{1}", APPENDIX, i));
                }

                createUserAccess createUserAccess = new createUserAccess()
                {
                    transactionId = TransactionId,
                    userInfo = personalInfo,
                    timeout = (long)3600000, //ms
                    userType = userId,
                    //authorizedDocTypes = new List<string>() { DocumentTypes.CONTRACT.ToString(), DocumentTypes.APPENDIX1.ToString(), DocumentTypes.APPENDIX2.ToString(), DocumentTypes.APPENDIX3.ToString() }.ToArray(), //TODO => list of appendixes : 3 appendixes
                    authorizedDocTypes = new List<string>() { DocumentTypes.CONTRACT.ToString() }.Concat(appendixDocs).ToArray(),
                    metadata = null
                };

                createUserAccessResponse createUserAccessResponse = _TransactionPortClient.createUserAccess(createUserAccess);
                string accessId = createUserAccessResponse.accessId;

                return accessId;
            }
            catch (Exception ex)
            {
                //string errorMessage = "Il est impossible de signer électroniquement votre document car le numéro de mobile indiqué n'est pas valide.";
                string errorMessage = ex.Message;

                if (!string.IsNullOrEmpty(errorMessage) && !errorMessage.Contains("mobile"))
                {
                    errorMessage = "Une erreur inattendue est survenue lors de la signature. Veuillez réessayer ultérieurement.";
                }
                              
                throw new Exception(errorMessage);
            }
        }
Exemplo n.º 19
0
        private static ISignatureInfo ParseSignature(string functionName, ParseContext context, IReadOnlyDictionary <string, string> argumentsDescriptions = null)
        {
            SignatureInfo        info = new SignatureInfo(functionName);
            List <IArgumentInfo> signatureArguments = new List <IArgumentInfo>();

            // RD data may contain function name(s) without braces
            if (context.Tokens.CurrentToken.TokenType == RTokenType.OpenBrace)
            {
                FunctionCall functionCall = new FunctionCall();
                functionCall.Parse(context, context.AstRoot);

                for (int i = 0; i < functionCall.Arguments.Count; i++)
                {
                    IAstNode arg = functionCall.Arguments[i];

                    string argName         = null;
                    string argDefaultValue = null;
                    bool   isEllipsis      = false;
                    bool   isOptional      = false;

                    ExpressionArgument expArg = arg as ExpressionArgument;
                    if (expArg != null)
                    {
                        argName = context.TextProvider.GetText(expArg.ArgumentValue);
                    }
                    else
                    {
                        NamedArgument nameArg = arg as NamedArgument;
                        if (nameArg != null)
                        {
                            argName         = context.TextProvider.GetText(nameArg.NameRange);
                            argDefaultValue = RdText.CleanRawRdText(context.TextProvider.GetText(nameArg.DefaultValue));
                        }
                        else
                        {
                            MissingArgument missingArg = arg as MissingArgument;
                            if (missingArg != null)
                            {
                                argName = string.Empty;
                            }
                            else
                            {
                                EllipsisArgument ellipsisArg = arg as EllipsisArgument;
                                if (ellipsisArg != null)
                                {
                                    argName    = "...";
                                    isEllipsis = true;
                                }
                            }
                        }
                    }

                    ArgumentInfo argInfo = new ArgumentInfo(argName);
                    argInfo.DefaultValue = argDefaultValue;
                    argInfo.IsEllipsis   = isEllipsis;
                    argInfo.IsOptional   = isOptional; // TODO: actually parse

                    if (argumentsDescriptions != null)
                    {
                        string description;
                        if (argumentsDescriptions.TryGetValue(argName, out description))
                        {
                            argInfo.Description = description;
                        }
                    }
                    signatureArguments.Add(argInfo);
                }
            }

            info.Arguments = signatureArguments;
            return(info);
        }
Exemplo n.º 20
0
        public override void WindowDidLoad()
        {
            base.WindowDidLoad();

            textKeytool.StringValue = helper.FindKeytool();

            buttonKeytool.Activated += (sender, e) => {
                NSOpenPanel panelOpen = new NSOpenPanel();

                var result = panelOpen.RunModal();

                if (result != 0)
                {
                    textKeytool.StringValue = panelOpen.Url.Path.Replace("keytool", "").TrimEnd('/');
                }
            };

            buttonOpenKeystore.Activated += (sender, e) => {
                NSOpenPanel panelOpen = new NSOpenPanel();
                panelOpen.Title            = "Choose a .keystore file";
                panelOpen.AllowedFileTypes = new string[] { "keystore" };

                var result = panelOpen.RunModal();

                if (result != 0)
                {
                    textCustomKeystore.StringValue = panelOpen.Url.Path;
                }
            };

            buttonGenerate.Activated += (sender, e) => {
                SignatureInfo sig = null;

                var keytool = helper.FindKeytool();

                if (string.IsNullOrEmpty(keytool))
                {
                    ShowAlert("Unable to locate keytool", "Java Keytool is needed to generate signatures.  We were unable to automatically locate keytool.  Please enter the location manually.");
                    return;
                }


                if (radioSource.SelectedRow == 0)
                {
                    try {
                        sig = helper.GetSignaturesFromKeystore();
                    } catch (Exception ex) {
                        ShowAlert("Error Generating Signatures", ex.ToString());
                    }
                }
                else
                {
                    if (!File.Exists(textCustomKeystore.StringValue ?? ""))
                    {
                        ShowAlert("Invalid .Keystore File", "The .keystore file you selected was invalid or not found");
                        return;
                    }

                    var keystore  = textCustomKeystore.StringValue;
                    var alias     = textCustomAlias.StringValue ?? "";
                    var storepass = textCustomStorePass.StringValue ?? "";
                    var keypass   = textCustomKeyPass.StringValue ?? "";

                    try {
                        sig = helper.GetSignaturesFromKeystore(keytool, keystore, alias, storepass, keypass);
                    } catch (Exception ex) {
                        ShowAlert("Error Generating Signatures", ex.ToString());
                    }
                }

                if (sig != null)
                {
                    textMd5.StringValue  = sig.MD5;
                    textSha1.StringValue = sig.SHA1;
                }
            };

            radioSource.Activated += (sender, e) => {
                var enabled = radioSource.SelectedRow == 1;

                buttonOpenKeystore.Enabled  = enabled;
                textCustomAlias.Enabled     = enabled;
                textCustomKeyPass.Enabled   = enabled;
                textCustomKeystore.Enabled  = enabled;
                textCustomStorePass.Enabled = enabled;
            };

            textMd5.Editable  = false;
            textSha1.Editable = false;

            buttonCopyMd5.Activated += (sender, e) => {
                NSPasteboard.GeneralPasteboard.SetStringForType(textMd5.StringValue, NSPasteboard.NSStringType);
            };

            buttonCopySha1.Activated += (sender, e) => {
                NSPasteboard.GeneralPasteboard.SetStringForType(textSha1.StringValue, NSPasteboard.NSStringType);
            };
        }
        private void BuildHeader(BuildState state)
        {
            var blob = state.HeaderBlob;
            int pos  = 1;

            var method     = (BuildMethod)state.Method;
            var methodBody = state.MethodBody;
            var ownerType  = (BuildType)method.GetOwnerType();

            // Name
            {
                int index;

                string typeName = (ownerType.NameChanged) ? ownerType.NewName : ownerType.Name;
                _strings.TryAdd(typeName, out index);
                blob.Write7BitEncodedInt(ref pos, index);

                string methodName = (method.NameChanged) ? method.NewName : method.Name;
                _strings.TryAdd(methodName, out index);
                blob.Write7BitEncodedInt(ref pos, index);
            }

            var cryptoMethod = method.ILCrypto;

            // Owner type
            {
                if (!ownerType.IsGlobal())
                {
                    var ownerTypeSig = ownerType.ToSignature(_module);
                    var sigInfo      = new SignatureInfo(ownerTypeSig, pos);
                    state.HeaderSignatures.Add(sigInfo);
                }

                blob.Write(ref pos, (int)0);
            }

            // Delegate type
            {
                var delegateTypeSig = GetDelegateTypeSig(cryptoMethod);
                var sigInfo         = new SignatureInfo(delegateTypeSig, pos);
                state.HeaderSignatures.Add(sigInfo);
                blob.Write(ref pos, (int)0);
            }

            // Return type
            {
                if (method.ReturnType.TypeCode != PrimitiveTypeCode.Void)
                {
                    state.Flags |= BlobFlags.HasReturnType;

                    var sigInfo = new SignatureInfo(method.ReturnType.Type, pos);
                    state.HeaderSignatures.Add(sigInfo);
                    blob.Write(ref pos, (int)0);
                }
            }

            // Parameters
            {
                var parameters = method.Parameters;

                int parameterCount = parameters.Count;

                if (method.HasThis)
                {
                    parameterCount++;
                }

                if (parameterCount > 0)
                {
                    state.Flags |= BlobFlags.HasParameters;

                    blob.Write7BitEncodedInt(ref pos, parameterCount);

                    if (method.HasThis)
                    {
                        var typeSig = TypeReference.GetPrimitiveType(PrimitiveTypeCode.Object, method.Assembly);
                        var sigInfo = new SignatureInfo(typeSig, pos);
                        state.HeaderSignatures.Add(sigInfo);
                        blob.Write(ref pos, (int)0);
                    }

                    for (int i = 0; i < parameters.Count; i++)
                    {
                        var typeSig = parameters[i].Type;
                        var sigInfo = new SignatureInfo(typeSig, pos);
                        state.HeaderSignatures.Add(sigInfo);
                        blob.Write(ref pos, (int)0);
                    }
                }
            }

            // Local variables
            if (methodBody.LocalVariables.Count > 0)
            {
                state.Flags |= BlobFlags.HasLocalVariables;

                var localVariables = methodBody.LocalVariables;

                blob.Write7BitEncodedInt(ref pos, localVariables.Count);

                // Check if pinned variable is present.
                bool hasPinned = false;
                for (int i = 0; i < localVariables.Count; i++)
                {
                    var typeSig = localVariables[i];
                    if (typeSig.ElementCode == TypeElementCode.Pinned)
                    {
                        hasPinned    = true;
                        state.Flags |= BlobFlags.HasPinnedLocalVariables;
                        break;
                    }
                }

                for (int i = 0; i < localVariables.Count; i++)
                {
                    var typeSig = localVariables[i];

                    if (hasPinned)
                    {
                        if (typeSig.ElementCode == TypeElementCode.Pinned)
                        {
                            blob.Write(ref pos, (byte)1);
                            typeSig = typeSig.ElementType;
                        }
                        else
                        {
                            blob.Write(ref pos, (byte)0);
                        }
                    }

                    var sigInfo = new SignatureInfo(typeSig, pos);
                    state.HeaderSignatures.Add(sigInfo);
                    blob.Write(ref pos, (int)0);
                }
            }

            // Sizes
            blob.Write7BitEncodedInt(ref pos, state.CodeSize);
            blob.Write7BitEncodedInt(ref pos, methodBody.MaxStackSize);

            if (state.EHSize > 0)
            {
                blob.Write7BitEncodedInt(ref pos, state.EHSize);
            }

            // Flags
            pos = 0;
            blob.Write(ref pos, (byte)state.Flags);
        }