Ejemplo n.º 1
0
 public AcquirerTrxRes()
 {
     this._signature   = new SignatureType();
     this._transaction = new AcquirerTrxResTransaction();
     this._issuer      = new AcquirerTrxResIssuer();
     this._acquirer    = new AcquirerTrxResAcquirer();
 }
 public SignatureVerificationSummary(
     SignatureType signatureType,
     SignatureVerificationStatus status,
     SignatureVerificationStatusFlags flags)
     : this(signatureType, status, flags, timestamp : null, expirationTime : null)
 {
 }
Ejemplo n.º 3
0
 private static HashSet <Signature> BuildSignatureCache(SignatureType signatureType)
 {
     return(FileTypeDatabase.Definitions
            .SelectMany(x => x.Signatures)
            .Where(x => x.Type == signatureType)
            .ToHashSet());
 }
Ejemplo n.º 4
0
        public void ValidarSelloXML()
        {
            // NOTA: el servidor de desarrollo devuelve java.lang.NullPointerException, en producción funciona correctamente

            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(SignatureType));
                SignatureType sello      = (SignatureType)serializer.Deserialize(ObtenerStreamRecurso("IntegraAfirmaNet.Test.SellosTiempo.Sello.xml"));

                DocumentHash documentHash = new DocumentHash();
                documentHash.DigestMethod           = new DigestMethodType();
                documentHash.DigestMethod.Algorithm = "http://www.w3.org/2001/04/xmlenc#sha256";
                documentHash.DigestValue            = CrearHashTexto("TEXTODEPRUEBA");

                TestContext.WriteLine(string.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), "Validando sello de tiempo"));

                Timestamp timeStamp = new Timestamp();
                timeStamp.Item = sello;

                VerifyResponse resultado = _tsaService.VerifyTimestamp(documentHash, timeStamp);

                Assert.AreEqual(ResultType.Success.Uri, resultado.Result.ResultMajor);

                TestContext.WriteLine(string.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), "Sello válido"));
            }
            catch (AfirmaResultException afirmaEx)
            {
                Assert.Fail(string.Format("Error devuelto por @firma: {0}", afirmaEx.Message));
            }
            catch (Exception ex)
            {
                Assert.Fail(string.Format("Unexpected exception of type {0} caught: {1}", ex.GetType(), ex.Message));
            }
        }
Ejemplo n.º 5
0
 public void AssertFound(SignatureType type)
 {
     if (!signatureTypes.Contains(type))
     {
         throw new SignatureException("Found no signature of type " + type + " in message");
     }
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Generates the authorization signatures for a B* REST API request
 /// </summary>
 /// <param name="request">The HTTP request object</param>
 /// <param name="signatureType">The type of signature to apply.</param>
 /// <param name="secret">The shared secret used to generate the signature</param>
 /// <returns></returns>
 public static string GenerateSignature(HttpWebRequest request, SignatureType signatureType, string secret)
 {
     if(signatureType == SignatureType.Unknown) throw new ArgumentException("Invalid signature type", "signatureType");
     if (signatureType == SignatureType.PlainText)
     {
         // Just passes back the shared secret key in plain text
         return secret;
     }
     var stringToSign = new StringBuilder();
     stringToSign.AppendLine(request.Method.ToUpperInvariant())
         .AppendLine(request.Headers[HttpRequestHeader.ContentEncoding])
         .AppendLine(request.Headers[HttpRequestHeader.ContentLanguage])
         .AppendLine(request.ContentLength >= 0 ? request.ContentLength.ToString(CultureInfo.InvariantCulture) : String.Empty)
         .AppendLine(request.Headers[HttpRequestHeader.ContentMd5])
         .AppendLine(request.Headers[HttpRequestHeader.ContentType])
         .AppendLine(request.Headers[HttpRequestHeader.Date])
         .AppendLine(request.Headers[HttpRequestHeader.IfModifiedSince])
         .AppendLine(request.Headers[HttpRequestHeader.IfMatch])
         .AppendLine(request.Headers[HttpRequestHeader.IfNoneMatch])
         .AppendLine(request.Headers[HttpRequestHeader.IfUnmodifiedSince])
         .AppendLine(request.Headers[HttpRequestHeader.Range])
         .Append(CanonicalizedResource(request.RequestUri));
     var key = Convert.FromBase64String(secret);
     var hmac = new HMACSHA256(key);
     var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign.ToString())));
     return signature;
 }
Ejemplo n.º 7
0
        /// <inheritdoc/>
        public async Task <bool> VerifyAsync(KeyHandle handle, byte[] hash,
                                             SignatureType algorithm, byte[] signature, CancellationToken ct)
        {
            var document = await _keys.GetAsync <KeyDocument>(KeyId.GetId(handle), ct);

            if (document.Value.IsDisabled)
            {
                throw new InvalidOperationException("Key is disabled");
            }
            var key = document.Value.KeyJson.ToKey();

            if (key == null)
            {
                throw new ResourceNotFoundException("Key not found");
            }
            switch (key.Type)
            {
            case KeyType.RSA:
                using (var rsa = key.ToRSA()) {
                    return(rsa.VerifyHash(hash, signature, algorithm.ToHashAlgorithmName(),
                                          algorithm.ToRSASignaturePadding()));
                }

            case KeyType.ECC:
                using (var ecc = key.ToECDsa()) {
                    return(ecc.VerifyHash(hash, signature));
                }

            default:
                throw new ArgumentException("Bad key type passed for signing");
            }
        }
Ejemplo n.º 8
0
        public static async Task RSASignedCrlCreateWith1Test(SignatureType signature)
        {
            using (var mock = Setup()) {
                IKeyStore   keys    = mock.Create <KeyDatabase>();
                ICrlFactory factory = mock.Create <CrlFactory>();

                using (var root = SignatureType.PS512.Create("CN=root", true))
                    using (var ca1 = root.Create(SignatureType.PS256, "CN=ca1", true))
                        using (var ca2 = root.Create(SignatureType.PS256, "CN=ca2", true))
                            using (var leaf1 = ca1.Create(SignatureType.RS256, "CN=leaf1"))
                                using (var leaf2 = ca1.Create(SignatureType.RS256, "CN=leaf2"))
                                    using (var leaf3 = ca1.Create(SignatureType.RS256, "CN=leaf3")) {
                                        var rootPrivateKey = root.ExportPrivateKey();
                                        var rootPublicKey  = rootPrivateKey.GetPublicKey();
                                        var rootKeyHandle  = await keys.ImportKeyAsync("ababa", rootPrivateKey,
                                                                                       new KeyStoreProperties { Exportable = true });

                                        var next = DateTime.UtcNow + TimeSpan.FromDays(4);
                                        next = next.Date;
                                        var rootCert = root.ToCertificate(new IssuerPolicies(), rootKeyHandle);

                                        var crl = await factory.CreateCrlAsync(rootCert, signature,
                                                                               ca1.ToCertificate().YieldReturn(), next);

                                        var privateKey = await keys.ExportKeyAsync(rootKeyHandle);

                                        Assert.True(rootPrivateKey.SameAs(privateKey));
                                        Assert.Equal(next, crl.NextUpdate);
                                        Assert.Equal(root.Subject, crl.Issuer);
                                        Assert.True(crl.IsRevoked(ca1.ToCertificate()));
                                        Assert.False(crl.IsRevoked(ca2.ToCertificate()));
                                        Assert.True(crl.HasValidSignature(rootCert));
                                    }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Generates the authorization signatures for a B* REST API request
        /// </summary>
        /// <param name="request">The HTTP request object</param>
        /// <param name="signatureType">The type of signature to apply.</param>
        /// <param name="secret">The shared secret used to generate the signature</param>
        /// <returns></returns>
        public static string GenerateSignature(HttpWebRequest request, SignatureType signatureType, string secret)
        {
            if (signatureType == SignatureType.Unknown)
            {
                throw new ArgumentException("Invalid signature type", "signatureType");
            }
            if (signatureType == SignatureType.PlainText)
            {
                // Just passes back the shared secret key in plain text
                return(secret);
            }
            var stringToSign = new StringBuilder();

            stringToSign.AppendLine(request.Method.ToUpperInvariant())
            .AppendLine(request.Headers[HttpRequestHeader.ContentEncoding])
            .AppendLine(request.Headers[HttpRequestHeader.ContentLanguage])
            .AppendLine(request.ContentLength >= 0 ? request.ContentLength.ToString(CultureInfo.InvariantCulture) : String.Empty)
            .AppendLine(request.Headers[HttpRequestHeader.ContentMd5])
            .AppendLine(request.Headers[HttpRequestHeader.ContentType])
            .AppendLine(request.Headers[HttpRequestHeader.Date])
            .AppendLine(request.Headers[HttpRequestHeader.IfModifiedSince])
            .AppendLine(request.Headers[HttpRequestHeader.IfMatch])
            .AppendLine(request.Headers[HttpRequestHeader.IfNoneMatch])
            .AppendLine(request.Headers[HttpRequestHeader.IfUnmodifiedSince])
            .AppendLine(request.Headers[HttpRequestHeader.Range])
            .Append(CanonicalizedResource(request.RequestUri));
            var key       = Convert.FromBase64String(secret);
            var hmac      = new HMACSHA256(key);
            var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign.ToString())));

            return(signature);
        }
Ejemplo n.º 10
0
 protected Signature(Signature s)
 {
     Type               = s.Type;
     Arguments          = s.Arguments;
     ReturnType         = s.ReturnType;
     ReturnValueIsConst = s.ReturnValueIsConst;
 }
Ejemplo n.º 11
0
 protected Signature(Signature s)
 {
     Type               = s.Type;
     Parameters         = s.Parameters;
     ReturnType         = s.ReturnType;
     ReturnValueIsConst = s.ReturnValueIsConst;
 }
        public X509Certificate2 ReadCertificateFromSignedFile(SignatureType signatureType, byte[] signedFileBytes, byte[] signatureFileBytes = null, string nodeId = null)
        {
            switch (signatureType)
            {
            case SignatureType.Smev2BaseDetached:
            case SignatureType.Smev2ChargeEnveloped:
            case SignatureType.Smev2SidebysideDetached:
            case SignatureType.Smev3BaseDetached:
            case SignatureType.Smev3SidebysideDetached:
            case SignatureType.Smev3Ack:
                var signedXmlFile = XDocument.Load(new MemoryStream(signedFileBytes));
                return(ReadCertificateFromXmlDocument(signedXmlFile, nodeId));

            case SignatureType.SigDetached:
            case SignatureType.SigDetachedAllCert:
            case SignatureType.SigDetachedNoCert:
            case SignatureType.Pkcs7String:
            case SignatureType.Pkcs7StringNoCert:
            case SignatureType.Pkcs7StringAllCert:
                return(ReadCertificateFromDetachedSignatureFile(signedFileBytes, signatureFileBytes));

            default:
                throw new InvalidOperationException(
                          $"Signed file from signature type {signatureType} is not supported");
            }
        }
Ejemplo n.º 13
0
        public async Task <bool> SignAsync(string packagePath,
                                           string outputPath,
                                           string timestampUrl,
                                           HashAlgorithmName signatureHashAlgorithm,
                                           HashAlgorithmName timestampHashAlgorithm,
                                           SignatureType signatureType,
                                           bool overwrite,
                                           Uri v3ServiceIndexUrl,
                                           IReadOnlyList <string> packageOwners,
                                           string keyVaultCertificateName,
                                           Uri keyVaultUrl,
                                           TokenCredential credential,
                                           CancellationToken cancellationToken = default)
        {
            var client = new CertificateClient(keyVaultUrl, credential);
            // We call this here to verify it's a valid cert
            // It also implicitly validates the access token or credentials
            var kvcert = await client.GetCertificateAsync(keyVaultCertificateName, cancellationToken)
                         .ConfigureAwait(false);

            var publicCertificate = new X509Certificate2(kvcert.Value.Cer);


            var rsa = RSAFactory.Create(credential, kvcert.Value.KeyId, publicCertificate);

            return(await SignAsync(packagePath, outputPath, timestampUrl, v3ServiceIndexUrl, packageOwners, signatureType, signatureHashAlgorithm, timestampHashAlgorithm, overwrite, publicCertificate, rsa, cancellationToken));
        }
Ejemplo n.º 14
0
 public Signature(SigningPayload signingPayload, PublicKey publicKey, SignatureType signatureType, string hexBytes)
 {
     SigningPayload = signingPayload;
     PublicKey      = publicKey;
     SignatureType  = signatureType;
     HexBytes       = hexBytes;
 }
Ejemplo n.º 15
0
        public MagicRecord(List <byte> fileData, NameTable nameTable) : base(fileData, false)
        {
            this.nameTable   = nameTable;
            ID               = rbc.ReadShort(fileData, Size);
            OwnerID          = rbc.ReadShort(fileData, Size);
            TargetingType    = rbc.GetNullTerminatedString(fileData, Size);
            type             = (MagicType)rbc.ReadByte(fileData, Size);
            ActionIntent     = (ActionIntentType)rbc.ReadByte(fileData, Size);
            Element          = (ElementType)rbc.ReadByte(fileData, Size);
            forAltAttackMode = rbc.ReadByte(fileData, Size);
            SelectionType    = (TargetSelectionType)rbc.ReadByte(fileData, Size);
            MaxRangeRadius   = rbc.ReadFloat(fileData, Size);
            SelectionRadius  = rbc.ReadByte(fileData, Size);
            unusedField2     = rbc.ReadInt(fileData, Size);
            signatureType    = (SignatureType)rbc.ReadLong(fileData, Size);
            ParseFieldEffects(fileData);
            CastTime      = rbc.ReadByte(fileData, Size);
            Delay         = rbc.ReadByte(fileData, Size);
            Cost          = rbc.ReadShort(fileData, Size);
            Unbalance     = rbc.ReadByte(fileData, Size);
            BreakDamage   = (BreakGrade)rbc.ReadShort(fileData, Size);
            LevelUnlocked = rbc.ReadByte(fileData, Size);
            MenuSortOrder = rbc.ReadShort(fileData, Size);
            AnimationName = rbc.GetNullTerminatedString(fileData, Size);
            Name          = rbc.GetNullTerminatedString(fileData, Size);
            string description = rbc.GetNullTerminatedString(fileData, Size);

            Description1stLine = description.Substring(0, Math.Max(description.IndexOf('\n'), 0));
            Description2ndLine = description.Substring(Math.Max(description.IndexOf('\n'), 0));
            Description2ndLine = Description2ndLine.Replace("\n  ", "");
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Verifica un file firmato e/o marcato
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="verifyDegree"></param>
        /// <param name="saveOptions"></param>
        /// <param name="saveTo"></param>
        /// <param name="signFormat"></param>
        /// <param name="timestampFormat"></param>
        /// <returns></returns>
        public VerifyResult Verify(string fileName, VerifyDegree verifyDegree = VerifyDegree.StandardVerify,
                                   SaveOption saveOptions              = SaveOption.DontSave, string saveTo = null,
                                   SignatureType signFormat            = SignatureType.EnvelopedDataSignature,
                                   TimeStampFileFormat timestampFormat = TimeStampFileFormat.UndefinedTimeStampFormat)
        {
            StringBuilder workPath = null;

            if (saveOptions != 0 || !string.IsNullOrEmpty(saveTo))
            {
                workPath = new StringBuilder(260);
            }

            if (!string.IsNullOrEmpty(saveTo))
            {
                workPath.Append(saveTo);
            }

            Violation tsViolation, signViolation;

            var success = NativeMethods.SvScVerifyCryptographicEnvelope(signSCHandle,
                                                                        timestampFormat, fileName, workPath,
                                                                        verifyDegree, signFormat, saveOptions,
                                                                        out tsViolation, out signViolation);

            CheckScResult(success || tsViolation != 0 || signViolation != 0);

            return(new VerifyResult
            {
                SignatureViolation = (signFormat == SignatureType.None && signViolation == Violation.Syntactic) ? (Violation?)null : signViolation,
                TimestampViolation = (timestampFormat == TimeStampFileFormat.UndefinedTimeStampFormat && tsViolation == Violation.Syntactic) ? (Violation?)null : tsViolation,
                ContentFileName = workPath?.ToString(),
            });
        }
Ejemplo n.º 17
0
 public AcquirerTrxReq()
 {
     this._signature   = new SignatureType();
     this._transaction = new AcquirerTrxReqTransaction();
     this._merchant    = new AcquirerTrxReqMerchant();
     this._issuer      = new AcquirerTrxReqIssuer();
 }
 public Signature(string signaturePath,
                  SignatureType signatureType,
                  string password,
                  string appearance,
                  string reason,
                  string contact,
                  string location,
                  bool visible,
                  Rectangle rectangle,
                  string formFieldName,
                  string authority,
                  DateTimeSignature date
                  )
 {
     SignaturePath = signaturePath;
     SignatureType = signatureType;
     Password      = password;
     Appearance    = appearance;
     Reason        = reason;
     Contact       = contact;
     Location      = location;
     Visible       = visible;
     Rectangle     = rectangle;
     FormFieldName = formFieldName;
     Authority     = authority;
     Date          = date;
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Generates the authorization signatures for a B* REST API request
        /// </summary>
        /// <param name="request">The HTTP request object</param>
        /// <param name="signatureType">The type of signature to apply.</param>
        /// <param name="secret">The shared secret used to generate the signature</param>
        /// <returns></returns>
        public static string GenerateSignature(HttpRequestBase request, SignatureType signatureType, string secret)
        {
            if (signatureType == SignatureType.Unknown)
            {
                throw new ArgumentException("Invalid signature type", "signatureType");
            }
            if (signatureType == SignatureType.PlainText)
            {
                return(secret);
            }
            var stringToSign = new StringBuilder();

            stringToSign.AppendLine(request.RequestType.ToUpperInvariant())
            .AppendLine(request.Headers["Content-Encoding"])
            .AppendLine(request.Headers["Content-Language"])
            .AppendLine(request.Headers["Content-Length"])
            .AppendLine(request.Headers["Content-MD5"])
            .AppendLine(request.Headers["Content-Type"])
            .AppendLine(request.Headers["Date"])
            .AppendLine(request.Headers["If-Modified-Since"])
            .AppendLine(request.Headers["If-Match"])
            .AppendLine(request.Headers["If-None-Match"])
            .AppendLine(request.Headers["If-Unmodified-Since"])
            .AppendLine(request.Headers["Range"])
            .Append(CanonicalizedResource(request.Url));
            var key       = Convert.FromBase64String(secret);
            var hmac      = new HMACSHA256(key);
            var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign.ToString())));

            return(signature);
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Create signature generator.
 /// </summary>
 /// <param name="signKey">The signing key</param>
 /// <param name="signer">Digest signer to use</param>
 /// <param name="signature"></param>
 public X509SignatureGeneratorAdapter(IDigestSigner signer, KeyHandle signKey,
                                      SignatureType signature)
 {
     _signKey   = signKey ?? throw new ArgumentNullException(nameof(signKey));
     _signer    = signer ?? throw new ArgumentNullException(nameof(signer));
     _signature = signature;
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Extracts and parses the Authorization header from a B* REST API request
        /// </summary>
        /// <param name="request">The incoming request</param>
        /// <param name="authType">The authentication type specified in the request</param>
        /// <param name="account">The account ID specified in the request</param>
        /// <param name="signature">The request signature</param>
        /// <returns>True if the request has an Authorization header that was parsed successfully, false otherwise.</returns>
        public static bool GetAuthorizationInfo(HttpRequestBase request, out SignatureType authType, out string account, out string signature)
        {
            authType = SignatureType.Unknown;
            string authHeader = request.Headers["Authorization"];

            if (!String.IsNullOrEmpty(authHeader))
            {
                var tokens = authHeader.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (tokens.Length == 2)
                {
                    if (tokens[0].Equals("SharedKey"))
                    {
                        authType = SignatureType.SharedKey;
                    }
                    if (tokens[0].Equals("PlainText"))
                    {
                        authType = SignatureType.PlainText;
                    }
                    if (authType != SignatureType.Unknown)
                    {
                        var keyAndSig = tokens[1].Split(':');
                        if (keyAndSig.Length == 2)
                        {
                            account   = keyAndSig[0];
                            signature = keyAndSig[1];
                            return(true);
                        }
                    }
                }
            }
            authType  = SignatureType.Unknown;
            account   = null;
            signature = null;
            return(false);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Returns a string representation of the packet. This is
        /// a human readable formated representation that has nothing
        /// to do with OpenPGP or RFC2440
        /// </summary>
        /// <returns>String representation of the packet.</returns>
        /// <remarks>No remarks</remarks>
        public override string ToString()
        {
            string strReturn = "";

            strReturn += "Signature Packet:\r\n";
            strReturn += "Version: " + Version.ToString() + "\r\n";
            strReturn += "Signaturetype: " + SignatureType.ToString() + "\r\n";
            strReturn += "Signaturealgorithm: " + SignatureAlgorithm.ToString() + "\r\n";
            strReturn += "Hashalgorithm: " + HashAlgorithm.ToString() + "\r\n";
            strReturn += "Time Created: " + TimeCreated.ToLocalTime() + "\r\n";
            strReturn += "KeyID: " + KeyID + "\r\n";
            strReturn += "Hashed Subpackets: " + HashedSubPackets.Length + "\r\n";

            for (int i = 0; i < HashedSubPackets.Length; i++)
            {
                strReturn += HashedSubPackets[i].ToString() + "\r\n";
            }

            strReturn += "\r\nUnhashed Subpackets: " + UnhashedSubPackets.Length + "\r\n";
            for (int i = 0; i < UnhashedSubPackets.Length; i++)
            {
                strReturn += UnhashedSubPackets[i].ToString() + "\r\n";
            }

            strReturn += "Key Material:\r\n";

            for (int i = 0; i < Signature.Length; i++)
            {
                strReturn += Signature[i].ToString(16) + "\r\n\r\n";
            }

            return(strReturn + "----\r\n\r\n");
        }
Ejemplo n.º 23
0
        private string Sign(
            SignatureType mode,
            GostFlavor gostFlavor,
            string certificateThumbprint,
            XmlDocument signThis,
            bool assignDs,
            string nodeToSign,
            bool ignoreExpiredCert = false,
            string stringToSign    = null,
            byte[] bytesToSign     = null,
            bool?isAddSigningTime  = null)
        {
            ICertificateProcessor cp          = new CertificateProcessor();
            X509Certificate2      certificate = cp.SearchCertificateByThumbprint(certificateThumbprint);

            if (!certificate.HasPrivateKey)
            {
                throw ExceptionFactory.GetException(ExceptionType.PrivateKeyMissing, certificate.Subject);
            }

            if (!ignoreExpiredCert &&
                cp.IsCertificateExpired(certificate))
            {
                throw ExceptionFactory.GetException(ExceptionType.CertExpired, certificate.Thumbprint);
            }

            return(Sign(mode, gostFlavor, certificate, signThis, assignDs, nodeToSign, stringToSign, bytesToSign, isAddSigningTime));
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Convert to service model
        /// </summary>
        /// <param name="signatureType"></param>
        /// <returns></returns>
        public static SignatureAlgorithm ToSignatureAlgorithm(this SignatureType signatureType)
        {
            switch (signatureType)
            {
            case SignatureType.RS256:
                return(SignatureAlgorithm.Rsa256);

            case SignatureType.RS384:
                return(SignatureAlgorithm.Rsa384);

            case SignatureType.RS512:
                return(SignatureAlgorithm.Rsa512);

            case SignatureType.PS256:
                return(SignatureAlgorithm.Rsa256Pss);

            case SignatureType.PS384:
                return(SignatureAlgorithm.Rsa384Pss);

            case SignatureType.PS512:
                return(SignatureAlgorithm.Rsa512Pss);

            case SignatureType.ES256:
            case SignatureType.ES384:
            case SignatureType.ES512:
            case SignatureType.ES256K:
                throw new NotSupportedException("Ecc not yet supported");

            default:
                throw new ArgumentException("Unknown signature type",
                                            nameof(signatureType));
            }
        }
Ejemplo n.º 25
0
        public GpgResult Sign(Stream input, Stream output, string localUser = null, SignatureType type = SignatureType.Sign, bool armor = false, string passphrase = null)
        {
            var args = new List <string>();

            if (localUser != null)
            {
                args.Add("--local-user " + localUser);
            }

            switch (type)
            {
            case SignatureType.Sign:
                args.Add("--sign");
                break;

            case SignatureType.ClearSign:
                args.Add("--clearsign");
                break;

            case SignatureType.DetachSign:
                args.Add("--detach-sign");
                break;

            default:
                throw new NotSupportedException();
            }

            if (armor)
            {
                args.Add("--armor");
            }

            return(ExecuteResult(input, output, passphrase, args.ToArray()));
        }
Ejemplo n.º 26
0
        public string Sign(
            SignatureType mode,
            GostFlavor gostFlavor,
            string certificateThumbprint,
            string signThisPath,
            bool assignDs,
            string nodeToSign,
            bool ignoreExpiredCert = false,
            bool?isAddSigningTime  = null)
        {
            XmlDocument xmlToSign    = null;
            string      stringToSign = null;

            byte[] bytesToSign = null;

            if (
                assignDs &&
                !new List <SignatureType>()
            {
                SignatureType.Smev3BaseDetached,
                SignatureType.Smev3SidebysideDetached,
                SignatureType.Smev3Ack
            }.Contains(mode))
            {
                throw ExceptionFactory.GetException(ExceptionType.DsAssignmentNotSupported);
            }

            if (mode == SignatureType.Pkcs7String ||
                mode == SignatureType.Pkcs7StringAllCert ||
                mode == SignatureType.Pkcs7StringNoCert

                || mode == SignatureType.Rsa2048Sha256String ||
                mode == SignatureType.RsaSha256String)
            {
                stringToSign = File.ReadAllText(signThisPath, Encoding.UTF8);
            }
            else if (mode == SignatureType.SigDetached ||
                     mode == SignatureType.SigDetachedAllCert ||
                     mode == SignatureType.SigDetachedNoCert)
            {
                bytesToSign = File.ReadAllBytes(signThisPath);
            }
            else
            {
                xmlToSign = new XmlDocument();
                xmlToSign.Load(signThisPath);
            }

            return(Sign(
                       mode,
                       gostFlavor,
                       certificateThumbprint,
                       xmlToSign,
                       assignDs,
                       nodeToSign,
                       ignoreExpiredCert,
                       stringToSign,
                       bytesToSign,
                       isAddSigningTime));
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Create self signed cert
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="subject"></param>
        /// <returns></returns>
        internal static AsymmetricAlgorithm CreateCsr(this SignatureType signature, string subject,
                                                      out CertificateRequest csr)
        {
            AsymmetricAlgorithm alg = null;

            try {
                if (signature.IsRSA())
                {
                    var rsa = RSA.Create();
                    alg = rsa;
                    csr = new CertificateRequest(X500DistinguishedNameEx.Create(subject),
                                                 rsa, signature.ToHashAlgorithmName(), signature.ToRSASignaturePadding());
                    return(alg);
                }
                if (signature.IsECC())
                {
                    var ecdsa = ECDsa.Create();
                    alg = ecdsa;
                    csr = new CertificateRequest(X500DistinguishedNameEx.Create(subject),
                                                 ecdsa, signature.ToHashAlgorithmName());
                    return(alg);
                }
                throw new ArgumentException("Bad signature");
            }
            catch {
                alg?.Dispose();
                throw;
            }
        }
Ejemplo n.º 28
0
        public override string ToString()
        {
            var result = new StringBuilder();

            result.AppendLine("I2PCertificate");
            result.AppendLine("CType            : " + CType.ToString());
            result.AppendLine("SignatureType    : " + SignatureType.ToString());

            if (Payload != null)
            {
                result.AppendLine("Payload          : " + Payload.Length + " bytes");
            }
            else
            {
                result.AppendLine("Payload          : (null)");
            }

            if (PayloadLength >= 4)
            {
                result.AppendLine("KEYSignatureType : " + KEYSignatureType.ToString());
                result.AppendLine("KEYPublicKeyType : " + KEYPublicKeyType.ToString());
            }

            return(result.ToString());
        }
Ejemplo n.º 29
0
 private void handleSigGenEvent(SignatureType type)
 {
     if (type == SignatureType.Pkcs1)
     {
         this.signature = (RsaSig)SignatureHandler.getInstance().getSignature();
         this.setEnabled();
         this.rbSigPkcs.IsEnabled = true;
         this.rbSigPkcs.IsChecked = true;
         this.rbSigPkcs.Content   = SigValCtrl.rsaSig;
         this.ResultEmpty();
     }
     else if (type == SignatureType.Bleichenbacher)
     {
         this.signature = (BleichenbacherSig)SignatureHandler.getInstance().getBleichenbSig();
         this.setEnabled();
         this.rbSigBlei.IsEnabled = true;
         this.rbSigBlei.IsChecked = true;
         this.rbSigBlei.Content   = SigValCtrl.bleichenbSig;
         this.ResultEmpty();
     }
     else if (type == SignatureType.Kuehn)
     {
         this.signature = (KuehnSig)SignatureHandler.getInstance().getKuehnSig();
         this.setEnabled();
         this.rbSigKuehn.IsEnabled = true;
         this.rbSigKuehn.IsChecked = true;
         this.rbSigKuehn.Content   = SigValCtrl.kuehnSig;
         this.ResultEmpty();
     }
 }
Ejemplo n.º 30
0
 // trigger
 protected void OnRaiseSigGenEvent(SignatureType type)
 {
     if (null != RaiseSigGenEvent)
     {
         RaiseSigGenEvent(type);
     }
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Extracts and parses the Authorization header from a B* REST API request
 /// </summary>
 /// <param name="request">The incoming request</param>
 /// <param name="authType">The authentication type specified in the request</param>
 /// <param name="account">The account ID specified in the request</param>
 /// <param name="signature">The request signature</param>
 /// <returns>True if the request has an Authorization header that was parsed successfully, false otherwise.</returns>
 public static bool GetAuthorizationInfo(HttpRequestBase request, out SignatureType authType, out string account, out string signature)
 {
     authType = SignatureType.Unknown;
     string authHeader = request.Headers["Authorization"];
     if (!String.IsNullOrEmpty(authHeader))
     {
         var tokens = authHeader.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
         if (tokens.Length == 2)
         {
             if (tokens[0].Equals("SharedKey"))
             {
                 authType = SignatureType.SharedKey;
             }
             if (tokens[0].Equals("PlainText"))
             {
                 authType = SignatureType.PlainText;
             }
             if (authType != SignatureType.Unknown)
             {
                 var keyAndSig = tokens[1].Split(':');
                 if (keyAndSig.Length == 2)
                 {
                     account = keyAndSig[0];
                     signature = keyAndSig[1];
                     return true;
                 }
             }
         }
     }
     authType = SignatureType.Unknown;
     account = null;
     signature = null;
     return false;
 }
Ejemplo n.º 32
0
 public Signature(SigningPayload signingPayload, PublicKey publicKey, SignatureType signatureType, byte[] bytes)
 {
     SigningPayload = signingPayload;
     PublicKey      = publicKey;
     SignatureType  = signatureType;
     Bytes          = bytes;
 }
 private static bool ValidateSignature(HttpRequestBase request, AccountDetails accessAccount, SignatureType sigType, string signature)
 {
     if (accessAccount != null)
     {
         if (signature.Equals(RestClientHelper.GenerateSignature(request, sigType,
                                                                 accessAccount.PrimaryKey)) ||
             signature.Equals(RestClientHelper.GenerateSignature(request, sigType,
                                                                 accessAccount.SecondaryKey)))
         {
             return true;
         }
     }
     return false;
 }
Ejemplo n.º 34
0
	public void Write (StringBuilder text, SignatureType type, GlobalInfo info)
	{
		if (IsConst && (type == SignatureType.Native || type == SignatureType.NativeC))
			text.Append ("const ");

		if (type != SignatureType.Native && type != SignatureType.NativeC) {
			if (IsRef && !IsReturnType)
				text.Append ("ref ");
			if (IsOut && !IsReturnType)
				text.Append ("out ");
		}

		if (type == SignatureType.NativeC && info.IsEnum (Value)) {
			text.Append (GetPrettyType ().Replace (Value.Replace ("*", ""), "int"));
		} else if (type == SignatureType.Native || type == SignatureType.NativeC) {
			text.Append (GetPrettyType ());
		} else {
			text.Append (GetManagedType ());
		}
	}
Ejemplo n.º 35
0
        // Initializes [signature] from the last consumed token.
        private Signature SignatureFromToken(SignatureType type)
        {
            Signature signature = new Signature();

            // Get the token for the method name.
            Token token = parser.previous;
            signature.Type = type;
            signature.Arity = 0;
            signature.Name = parser.source.Substring(token.start, token.length);
            signature.Length = token.length;

            if (signature.Length > MAX_METHOD_NAME)
            {
                Error(string.Format("Method names cannot be longer than {0} characters.", MAX_METHOD_NAME));
                signature.Length = MAX_METHOD_NAME;
            }

            return signature;
        }
Ejemplo n.º 36
0
 public Signature(string signaturePath,
  SignatureType signatureType,
  string password,
  string appearance,
  string reason,
  string contact,
  string location,
  bool visible,
  Rectangle rectangle,
  string formFieldName,
  string authority,
  DateTimeSignature date
      )
 {
     SignaturePath = signaturePath;
     SignatureType = signatureType;
     Password = password;
     Appearance = appearance;
     Reason = reason;
     Contact = contact;
     Location = location;
     Visible = visible;
     Rectangle = rectangle;
     FormFieldName = formFieldName;
     Authority = authority;
     Date = date;
 }
Ejemplo n.º 37
0
 public bool Open(Stream fs)
 {
     try
     {
         var intBytes = new byte[4];
         fs.Read(intBytes, 0, 4);
         SignatureType = (SignatureType)BitConverter.ToInt32(intBytes, 0);
         // Read the TMD RSA Type 
         if (SignatureType == SignatureType.RSA_2048_SHA256)
             Hash = new byte[256];
         else if (SignatureType == SignatureType.RSA_4096_SHA256)
             Hash = new byte[512];
         else
         {
             errorMessage = "This kind of TMD is unsupported.";
             return false;
         }
         fs.Read(Hash, 0, Hash.Length);
         //Continue reading header
         Head = MarshalUtil.ReadStructBE<TMDHeader>(fs); //read header
         ContentInfoRecords = new TMDContentInfoRecord[64];
         for (var i = 0; i < ContentInfoRecords.Length; i++)
             ContentInfoRecords[i] = MarshalUtil.ReadStructBE<TMDContentInfoRecord>(fs);
         Chunks = new TMDContentChunkRecord[Head.ContentCount]; // new ArrayList();
         for (var i = 0; i < Head.ContentCount; i++)
             Chunks[i] = MarshalUtil.ReadStructBE<TMDContentChunkRecord>(fs);
         //Check if certificates are next
         fs.Read(intBytes, 0, 4);
         switch ((SignatureType)BitConverter.ToInt32(intBytes, 0))
         {
             case SignatureType.RSA_2048_SHA1:
             case SignatureType.RSA_2048_SHA256:
             case SignatureType.RSA_4096_SHA1:
             case SignatureType.RSA_4096_SHA256:
                 fs.Seek(-4, SeekOrigin.Current); //go back
                 CertificatesContext = new CertificatesContext();
                 if (!CertificatesContext.Open(fs))
                 {
                     errorMessage = CertificatesContext.GetErrorMessage();
                     return false;
                 }
                 break;
         }
         return true;
     }
     catch
     {
         errorMessage = "Error opening the TMD file. may be corrupt.";
         return false;
     }
 }
 public ResponseMessageHeader(XmlNode xmlNode)
 : base(xmlNode)
 {
     XmlNode inReplyToNode = xmlNode.SelectSingleNode("inReplyTo");
     
     if (inReplyToNode != null)
     {
         if (inReplyToNode.Attributes["href"] != null || inReplyToNode.Attributes["id"] != null) 
         {
             if (inReplyToNode.Attributes["id"] != null) 
             {
                 inReplyToIDRef_ = inReplyToNode.Attributes["id"].Value;
                 MessageId ob = new MessageId(inReplyToNode);
                 IDManager.SetID(inReplyToIDRef_, ob);
             }
             else if (inReplyToNode.Attributes["href"] != null)
             {
                 inReplyToIDRef_ = inReplyToNode.Attributes["href"].Value;
             }
             else
             {
                 inReplyTo_ = new MessageId(inReplyToNode);
             }
         }
         else
         {
             inReplyTo_ = new MessageId(inReplyToNode);
         }
     }
     
 
     XmlNode sentByNode = xmlNode.SelectSingleNode("sentBy");
     
     if (sentByNode != null)
     {
         if (sentByNode.Attributes["href"] != null || sentByNode.Attributes["id"] != null) 
         {
             if (sentByNode.Attributes["id"] != null) 
             {
                 sentByIDRef_ = sentByNode.Attributes["id"].Value;
                 MessageAddress ob = new MessageAddress(sentByNode);
                 IDManager.SetID(sentByIDRef_, ob);
             }
             else if (sentByNode.Attributes["href"] != null)
             {
                 sentByIDRef_ = sentByNode.Attributes["href"].Value;
             }
             else
             {
                 sentBy_ = new MessageAddress(sentByNode);
             }
         }
         else
         {
             sentBy_ = new MessageAddress(sentByNode);
         }
     }
     
 
     XmlNodeList sendToNodeList = xmlNode.SelectNodes("sendTo");
     
     if (sendToNodeList != null)
     {
         this.sendTo_ = new List<MessageAddress>();
         foreach (XmlNode item in sendToNodeList)
         {
             if (item.Attributes["href"] != null || item.Attributes["id"] != null) 
             {
                 if (item.Attributes["id"] != null) 
                 {
                     sendToIDRef_ = item.Attributes["id"].Value;
                     sendTo_.Add(new MessageAddress(item));
                     IDManager.SetID(sendToIDRef_, sendTo_[sendTo_.Count - 1 ]);
                 }
                 else if (item.Attributes["href"] != null)
                 {
                     sendToIDRef_ = item.Attributes["href"].Value;
                 }
                 else
                 {
                 sendTo_.Add(new MessageAddress(item));
                 }
             }
             else
             {
                 sendTo_.Add(new MessageAddress(item));
             }
         }
     }
     
 
     XmlNodeList copyToNodeList = xmlNode.SelectNodes("copyTo");
     
     if (copyToNodeList != null)
     {
         this.copyTo_ = new List<MessageAddress>();
         foreach (XmlNode item in copyToNodeList)
         {
             if (item.Attributes["href"] != null || item.Attributes["id"] != null) 
             {
                 if (item.Attributes["id"] != null) 
                 {
                     copyToIDRef_ = item.Attributes["id"].Value;
                     copyTo_.Add(new MessageAddress(item));
                     IDManager.SetID(copyToIDRef_, copyTo_[copyTo_.Count - 1 ]);
                 }
                 else if (item.Attributes["href"] != null)
                 {
                     copyToIDRef_ = item.Attributes["href"].Value;
                 }
                 else
                 {
                 copyTo_.Add(new MessageAddress(item));
                 }
             }
             else
             {
                 copyTo_.Add(new MessageAddress(item));
             }
         }
     }
     
 
     XmlNode creationTimestampNode = xmlNode.SelectSingleNode("creationTimestamp");
     
     if (creationTimestampNode != null)
     {
         if (creationTimestampNode.Attributes["href"] != null || creationTimestampNode.Attributes["id"] != null) 
         {
             if (creationTimestampNode.Attributes["id"] != null) 
             {
                 creationTimestampIDRef_ = creationTimestampNode.Attributes["id"].Value;
                 XsdTypeDateTime ob = new XsdTypeDateTime(creationTimestampNode);
                 IDManager.SetID(creationTimestampIDRef_, ob);
             }
             else if (creationTimestampNode.Attributes["href"] != null)
             {
                 creationTimestampIDRef_ = creationTimestampNode.Attributes["href"].Value;
             }
             else
             {
                 creationTimestamp_ = new XsdTypeDateTime(creationTimestampNode);
             }
         }
         else
         {
             creationTimestamp_ = new XsdTypeDateTime(creationTimestampNode);
         }
     }
     
 
     XmlNode expiryTimestampNode = xmlNode.SelectSingleNode("expiryTimestamp");
     
     if (expiryTimestampNode != null)
     {
         if (expiryTimestampNode.Attributes["href"] != null || expiryTimestampNode.Attributes["id"] != null) 
         {
             if (expiryTimestampNode.Attributes["id"] != null) 
             {
                 expiryTimestampIDRef_ = expiryTimestampNode.Attributes["id"].Value;
                 XsdTypeDateTime ob = new XsdTypeDateTime(expiryTimestampNode);
                 IDManager.SetID(expiryTimestampIDRef_, ob);
             }
             else if (expiryTimestampNode.Attributes["href"] != null)
             {
                 expiryTimestampIDRef_ = expiryTimestampNode.Attributes["href"].Value;
             }
             else
             {
                 expiryTimestamp_ = new XsdTypeDateTime(expiryTimestampNode);
             }
         }
         else
         {
             expiryTimestamp_ = new XsdTypeDateTime(expiryTimestampNode);
         }
     }
     
 
     XmlNode implementationSpecificationNode = xmlNode.SelectSingleNode("implementationSpecification");
     
     if (implementationSpecificationNode != null)
     {
         if (implementationSpecificationNode.Attributes["href"] != null || implementationSpecificationNode.Attributes["id"] != null) 
         {
             if (implementationSpecificationNode.Attributes["id"] != null) 
             {
                 implementationSpecificationIDRef_ = implementationSpecificationNode.Attributes["id"].Value;
                 ImplementationSpecification ob = new ImplementationSpecification(implementationSpecificationNode);
                 IDManager.SetID(implementationSpecificationIDRef_, ob);
             }
             else if (implementationSpecificationNode.Attributes["href"] != null)
             {
                 implementationSpecificationIDRef_ = implementationSpecificationNode.Attributes["href"].Value;
             }
             else
             {
                 implementationSpecification_ = new ImplementationSpecification(implementationSpecificationNode);
             }
         }
         else
         {
             implementationSpecification_ = new ImplementationSpecification(implementationSpecificationNode);
         }
     }
     
 
     XmlNodeList partyMessageInformationNodeList = xmlNode.SelectNodes("partyMessageInformation");
     
     if (partyMessageInformationNodeList != null)
     {
         this.partyMessageInformation_ = new List<PartyMessageInformation>();
         foreach (XmlNode item in partyMessageInformationNodeList)
         {
             if (item.Attributes["href"] != null || item.Attributes["id"] != null) 
             {
                 if (item.Attributes["id"] != null) 
                 {
                     partyMessageInformationIDRef_ = item.Attributes["id"].Value;
                     partyMessageInformation_.Add(new PartyMessageInformation(item));
                     IDManager.SetID(partyMessageInformationIDRef_, partyMessageInformation_[partyMessageInformation_.Count - 1 ]);
                 }
                 else if (item.Attributes["href"] != null)
                 {
                     partyMessageInformationIDRef_ = item.Attributes["href"].Value;
                 }
                 else
                 {
                 partyMessageInformation_.Add(new PartyMessageInformation(item));
                 }
             }
             else
             {
                 partyMessageInformation_.Add(new PartyMessageInformation(item));
             }
         }
     }
     
 
     XmlNode SignatureNode = xmlNode.SelectSingleNode("Signature");
     
     if (SignatureNode != null)
     {
         if (SignatureNode.Attributes["href"] != null || SignatureNode.Attributes["id"] != null) 
         {
             if (SignatureNode.Attributes["id"] != null) 
             {
                 SignatureIDRef_ = SignatureNode.Attributes["id"].Value;
                 SignatureType ob = new SignatureType(SignatureNode);
                 IDManager.SetID(SignatureIDRef_, ob);
             }
             else if (SignatureNode.Attributes["href"] != null)
             {
                 SignatureIDRef_ = SignatureNode.Attributes["href"].Value;
             }
             else
             {
                 Signature_ = new SignatureType(SignatureNode);
             }
         }
         else
         {
             Signature_ = new SignatureType(SignatureNode);
         }
     }
     
 
 }
 public Signature(SignatureType type, string name)
 {
     Type = type;
     Name = name;
 }
Ejemplo n.º 40
0
        // Initializes [signature] from the last consumed token.
        private Signature SignatureFromToken(Signature signature, SignatureType type)
        {
            // Get the token for the method name.
            Token token = _parser.Previous;
            signature.Type = type;
            signature.Arity = 0;
            signature.Name = _parser.Source.Substring(token.Start, token.Length);
            signature.Length = token.Length;

            if (signature.Length > MaxMethodName)
            {
                Error(string.Format("Method names cannot be longer than {0} characters.", MaxMethodName));
                signature.Length = MaxMethodName;
            }

            return signature;
        }
 public NotificationMessageHeader(XmlNode xmlNode)
 : base(xmlNode)
 {
     XmlNodeList inReplyToNodeList = xmlNode.SelectNodes("inReplyTo");
     if (inReplyToNodeList.Count > 1 )
     {
             throw new Exception();
     }
     
     foreach (XmlNode item in inReplyToNodeList)
     {
         if (item.Attributes["href"] != null || item.Attributes["id"] == null) 
         {
             if (item.Attributes["id"] != null) 
             {
                 inReplyToIDRef = item.Attributes["id"].Name;
                 MessageId ob = MessageId();
                 IDManager.SetID(inReplyToIDRef, ob);
             }
             else if (item.Attributes.ToString() == "href")
             {
                 inReplyToIDRef = item.Attributes["href"].Name;
             }
             else
             {
                 inReplyTo = new MessageId(item);
             }
         }
     }
     
 
     XmlNodeList sentByNodeList = xmlNode.SelectNodes("sentBy");
     if (sentByNodeList.Count > 1 )
     {
             throw new Exception();
     }
     
     foreach (XmlNode item in sentByNodeList)
     {
         if (item.Attributes["href"] != null || item.Attributes["id"] == null) 
         {
             if (item.Attributes["id"] != null) 
             {
                 sentByIDRef = item.Attributes["id"].Name;
                 MessageAddress ob = MessageAddress();
                 IDManager.SetID(sentByIDRef, ob);
             }
             else if (item.Attributes.ToString() == "href")
             {
                 sentByIDRef = item.Attributes["href"].Name;
             }
             else
             {
                 sentBy = new MessageAddress(item);
             }
         }
     }
     
 
     XmlNodeList sendToNodeList = xmlNode.SelectNodes("sendTo");
     
     foreach (XmlNode item in sendToNodeList)
     {
         if (item.Attributes["href"] != null || item.Attributes["id"] == null) 
         {
             if (item.Attributes["id"] != null) 
             {
                 sendToIDRef = item.Attributes["id"].Name;
                 List<MessageAddress> ob = new List<MessageAddress>();
                 ob.Add(new MessageAddress(item));
                 IDManager.SetID(sendToIDRef, ob);
             }
             else if (item.Attributes.ToString() == "href")
             {
                 sendToIDRef = item.Attributes["href"].Name;
             }
             else
             {
             sendTo.Add(new MessageAddress(item));
             }
         }
     }
     
 
     XmlNodeList copyToNodeList = xmlNode.SelectNodes("copyTo");
     
     foreach (XmlNode item in copyToNodeList)
     {
         if (item.Attributes["href"] != null || item.Attributes["id"] == null) 
         {
             if (item.Attributes["id"] != null) 
             {
                 copyToIDRef = item.Attributes["id"].Name;
                 List<MessageAddress> ob = new List<MessageAddress>();
                 ob.Add(new MessageAddress(item));
                 IDManager.SetID(copyToIDRef, ob);
             }
             else if (item.Attributes.ToString() == "href")
             {
                 copyToIDRef = item.Attributes["href"].Name;
             }
             else
             {
             copyTo.Add(new MessageAddress(item));
             }
         }
     }
     
 
     XmlNodeList creationTimestampNodeList = xmlNode.SelectNodes("creationTimestamp");
     if (creationTimestampNodeList.Count > 1 )
     {
             throw new Exception();
     }
     
     foreach (XmlNode item in creationTimestampNodeList)
     {
         if (item.Attributes["href"] != null || item.Attributes["id"] == null) 
         {
             if (item.Attributes["id"] != null) 
             {
                 creationTimestampIDRef = item.Attributes["id"].Name;
                 XsdTypeDateTime ob = XsdTypeDateTime();
                 IDManager.SetID(creationTimestampIDRef, ob);
             }
             else if (item.Attributes.ToString() == "href")
             {
                 creationTimestampIDRef = item.Attributes["href"].Name;
             }
             else
             {
                 creationTimestamp = new XsdTypeDateTime(item);
             }
         }
     }
     
 
     XmlNodeList expiryTimestampNodeList = xmlNode.SelectNodes("expiryTimestamp");
     if (expiryTimestampNodeList.Count > 1 )
     {
             throw new Exception();
     }
     
     foreach (XmlNode item in expiryTimestampNodeList)
     {
         if (item.Attributes["href"] != null || item.Attributes["id"] == null) 
         {
             if (item.Attributes["id"] != null) 
             {
                 expiryTimestampIDRef = item.Attributes["id"].Name;
                 XsdTypeDateTime ob = XsdTypeDateTime();
                 IDManager.SetID(expiryTimestampIDRef, ob);
             }
             else if (item.Attributes.ToString() == "href")
             {
                 expiryTimestampIDRef = item.Attributes["href"].Name;
             }
             else
             {
                 expiryTimestamp = new XsdTypeDateTime(item);
             }
         }
     }
     
 
     XmlNodeList implementationSpecificationNodeList = xmlNode.SelectNodes("implementationSpecification");
     if (implementationSpecificationNodeList.Count > 1 )
     {
             throw new Exception();
     }
     
     foreach (XmlNode item in implementationSpecificationNodeList)
     {
         if (item.Attributes["href"] != null || item.Attributes["id"] == null) 
         {
             if (item.Attributes["id"] != null) 
             {
                 implementationSpecificationIDRef = item.Attributes["id"].Name;
                 ImplementationSpecification ob = ImplementationSpecification();
                 IDManager.SetID(implementationSpecificationIDRef, ob);
             }
             else if (item.Attributes.ToString() == "href")
             {
                 implementationSpecificationIDRef = item.Attributes["href"].Name;
             }
             else
             {
                 implementationSpecification = new ImplementationSpecification(item);
             }
         }
     }
     
 
     XmlNodeList partyMessageInformationNodeList = xmlNode.SelectNodes("partyMessageInformation");
     
     foreach (XmlNode item in partyMessageInformationNodeList)
     {
         if (item.Attributes["href"] != null || item.Attributes["id"] == null) 
         {
             if (item.Attributes["id"] != null) 
             {
                 partyMessageInformationIDRef = item.Attributes["id"].Name;
                 List<PartyMessageInformation> ob = new List<PartyMessageInformation>();
                 ob.Add(new PartyMessageInformation(item));
                 IDManager.SetID(partyMessageInformationIDRef, ob);
             }
             else if (item.Attributes.ToString() == "href")
             {
                 partyMessageInformationIDRef = item.Attributes["href"].Name;
             }
             else
             {
             partyMessageInformation.Add(new PartyMessageInformation(item));
             }
         }
     }
     
 
     XmlNodeList SignatureNodeList = xmlNode.SelectNodes("Signature");
     if (SignatureNodeList.Count > 1 )
     {
             throw new Exception();
     }
     
     foreach (XmlNode item in SignatureNodeList)
     {
         if (item.Attributes["href"] != null || item.Attributes["id"] == null) 
         {
             if (item.Attributes["id"] != null) 
             {
                 SignatureIDRef = item.Attributes["id"].Name;
                 SignatureType ob = SignatureType();
                 IDManager.SetID(SignatureIDRef, ob);
             }
             else if (item.Attributes.ToString() == "href")
             {
                 SignatureIDRef = item.Attributes["href"].Name;
             }
             else
             {
                 Signature = new SignatureType(item);
             }
         }
     }
     
 
 }
Ejemplo n.º 42
0
		/// <summary>
		/// Generate the signature base that is used to produce the signature
		/// </summary>
		/// <param name="url">The full URL that needs to be signed including its non OAuth URL parameters.</param>
		/// <param name="consumerKey">The consumer key.</param>
		/// <param name="token">The token, if available. If not available pass null or an empty string.</param>
		/// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string.</param>
		/// <param name="verifier">The callback verifier, if available. If not available pass null or an empty string.</param>
		/// <param name="httpMethod">The HTTP method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
		/// <param name="signatureType">The signature type. To use the default values use <see cref="SignatureType">SignatureType</see>.</param>
		/// <returns>The signature base.</returns>
		private string GenerateSignatureBase (Uri url, string consumerKey, string token, string tokenSecret, string verifier,
						      RequestMethod method, TimeSpan timeStamp, string nonce, SignatureType signatureType, string callbackUrl,
						      out string normalizedUrl,
			out List<IQueryParameter<string>> parameters)
		{
			log.LogDebug ("Generating signature base for OAuth request.");

			token = token ?? string.Empty;
			tokenSecret = tokenSecret ?? string.Empty;
			verifier = verifier ?? String.Empty;

			if (consumerKey == null) throw new ArgumentNullException ("consumerKey");

			log.LogDebug ("URL: {0}", url.Query);

			var signatureString = string.Empty;

			switch (signatureType) {
				case SignatureType.HMACSHA1:
					signatureString = "HMAC-SHA1";
					break;
				case SignatureType.RSASHA1:
					signatureString = "RSA-SHA1";
					break;
				case SignatureType.PLAINTEXT:
					signatureString = SignatureType.PLAINTEXT.ToString ();
					break;
			}

			parameters = GetQueryParameters (url.Query).Concat (new List<IQueryParameter<string>> {
				new QueryParameter<string> (OAuthVersionKey, OAuthVersion, s => string.IsNullOrEmpty (s)),
				new QueryParameter<string> (OAuthTimestampKey, ((long)timeStamp.TotalSeconds).ToString (), s => string.IsNullOrEmpty (s)),
				new QueryParameter<string> (OAuthSignatureMethodKey, signatureString, s => string.IsNullOrEmpty (s)),
				new QueryParameter<string> (OAuthNonceKey, nonce, s => string.IsNullOrEmpty (s)),
				new QueryParameter<string> (OAuthConsumerKeyKey, consumerKey, s => string.IsNullOrEmpty (s))
			}).ToList ();

			if (!string.IsNullOrEmpty (token)) parameters.Add (new QueryParameter<string> (OAuthTokenKey, token, s => string.IsNullOrEmpty (s)));
			if (!string.IsNullOrEmpty (verifier)) parameters.Add (new QueryParameter<string> (OAuthVerifierKey, verifier, s => string.IsNullOrEmpty (s)));
			if (!string.IsNullOrEmpty (callbackUrl)) parameters.Add (new QueryParameter<string> (OAuthCallbackKey, UrlEncode (callbackUrl), s => string.IsNullOrEmpty (s)));

			log.LogDebug ("Normalizing URL for signature.");

			normalizedUrl = string.Format ("{0}://{1}", url.Scheme, url.Host);
			if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443))) normalizedUrl += ":" + url.Port;
			normalizedUrl += url.AbsolutePath;

			log.LogDebug ("Generated normalized URL: {0}", normalizedUrl);
			log.LogDebug ("Normalizing request parameters.");

			parameters.Sort ();
			string normalizedRequestParameters = parameters.NormalizeRequestParameters ();

			log.LogDebug ("Normalized request parameters {0}.", normalizedRequestParameters);
			log.LogDebug ("Generating signature base from normalized URL and request parameters.");

			var signatureBase = new StringBuilder ();
			signatureBase.AppendFormat("{0}&", method.ToString ());
			signatureBase.AppendFormat("{0}&", UrlEncode (normalizedUrl));
			signatureBase.AppendFormat("{0}", UrlEncode (normalizedRequestParameters));

			log.LogDebug ("Signature base: {0}", signatureBase.ToString ());

			return signatureBase.ToString ();
		}
Ejemplo n.º 43
0
		/// <summary>
		/// Generates a signature using the specified signature type.
		/// </summary>
		/// <param name="url">The full URL that needs to be signed including its non-OAuth URL parameters.</param>
		/// <param name="consumerKey">The consumer key.</param>
		/// <param name="consumerSecret">The consumer seceret.</param>
		/// <param name="token">The token, if available. If not available pass null or an empty string.</param>
		/// <param name="tokenSecret">The token secret, if available. If not, pass null or an empty string.</param>
		/// <param name="verifier">The callback verifier, if available. If not, pass null or an empty string.</param>
		/// <param name="httpMethod">The HTTP method used. Must be a valid HTTP method verb (POST,GET,PUT, etc).</param>
		/// <param name="signatureType">The type of signature to use.</param>
		/// <returns>A Base64 string of the hash value.</returns>
		private string GenerateSignature (Uri url, string consumerKey, string consumerSecret, string token,
		                                  string tokenSecret, string verifier, RequestMethod method, TimeSpan timeStamp, string nonce, SignatureType signatureType,
		                                  string callbackUrl, out string normalizedUrl, out List<IQueryParameter<string>> parameters)
		{
			log.LogDebug ("Generating signature using signature type {0}", signatureType);

			normalizedUrl = null;
			parameters = null;

			switch (signatureType)
			{
				case SignatureType.PLAINTEXT:
					var signature = UrlEncode (string.Format ("{0}&{1}", consumerSecret, tokenSecret));
					log.LogDebug ("Plaintext encoding signature {0} of consumer secret and token secret.", signature);
					return signature;
				case SignatureType.HMACSHA1:
					string signatureBase = GenerateSignatureBase (url, consumerKey, token, tokenSecret, verifier, method,
					                                              timeStamp, nonce, SignatureType.HMACSHA1, callbackUrl,
					                                              out normalizedUrl, out parameters);

					var hmacsha1 = new HMACSHA1 ();
					hmacsha1.Key = Encoding.ASCII.GetBytes (string.Format ("{0}&{1}",
						UrlEncode (consumerSecret),
						string.IsNullOrEmpty (tokenSecret) ? "" : UrlEncode(tokenSecret)));

					var hashedSignature = GenerateSignatureUsingHash (signatureBase, hmacsha1);

					log.LogDebug ("HMAC-SHA1 encoded signature {0} of consumer secret and token secret.", hashedSignature);
					return hashedSignature;
				case SignatureType.RSASHA1:
					throw new NotImplementedException ();
				default:
					throw new ArgumentException ("Unknown signature type", "signatureType");
			}
		}
Ejemplo n.º 44
0
        /// <summary>
        /// Generates the authorization signatures for a B* REST API request
        /// </summary>
        /// <param name="request">The HTTP request object</param>
        /// <param name="signatureType">The type of signature to apply.</param>
        /// <param name="secret">The shared secret used to generate the signature</param>
        /// <returns></returns>
        public static string GenerateSignature(HttpRequestBase request, SignatureType signatureType, string secret)
        {
            if (signatureType == SignatureType.Unknown) throw new ArgumentException("Invalid signature type", "signatureType");
            if (signatureType == SignatureType.PlainText)
            {
                return secret;
            }
            var stringToSign = new StringBuilder();
            stringToSign.AppendLine(request.RequestType.ToUpperInvariant())
                .AppendLine(request.Headers["Content-Encoding"])
                .AppendLine(request.Headers["Content-Language"])
                .AppendLine(request.Headers["Content-Length"])
                .AppendLine(request.Headers["Content-MD5"])
                .AppendLine(request.Headers["Content-Type"])
                .AppendLine(request.Headers["Date"])
                .AppendLine(request.Headers["If-Modified-Since"])
                .AppendLine(request.Headers["If-Match"])
                .AppendLine(request.Headers["If-None-Match"])
                .AppendLine(request.Headers["If-Unmodified-Since"])
                .AppendLine(request.Headers["Range"])
                .Append(CanonicalizedResource(request.Url));
            var key = Convert.FromBase64String(secret);
            var hmac = new HMACSHA256(key);
            var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign.ToString())));
            return signature;

        }
 public string GetPatientSignature(string patientId, ConsentType consentType, SignatureType signatureType)
 {
     System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
     var conStr = config.AppSettings.Settings["DBConnection"].Value;
     using (var sqlConnection = new SqlConnection(conStr))
     {
         sqlConnection.Open();
         var cmdSignature = new SqlCommand(@"GetPatientSignature", sqlConnection) { CommandType = CommandType.StoredProcedure };
         cmdSignature.Parameters.Add("@patientID", SqlDbType.NVarChar).Value = patientId;
         cmdSignature.Parameters.Add("@signatureType", SqlDbType.VarChar).Value = signatureType.ToString();
         cmdSignature.Parameters.Add("@consentType", SqlDbType.VarChar).Value = consentType.ToString();
         using (var sqlDataAdapter = new SqlDataAdapter(cmdSignature))
         {
             var sig = new DataSet();
             sqlDataAdapter.Fill(sig);
             if (sig.Tables.Count > 0 && sig.Tables[0].Rows.Count > 0 && sig.Tables[0].Rows[0][0] != null)
                 return sig.Tables[0].Rows[0][0].ToString();
         }
     }
     return string.Empty;
 }