예제 #1
0
 public DefaultHmac(ReadOnlySpan <byte> key, HashAlgorithmName name)
 {
     _hasher = IncrementalHash.CreateHMAC(name, key);
     Name    = name.ToString() switch
     {
         @"MD5" => @"HMAC-MD5",
         @"SHA1" => @"HMAC-SHA-1",
         @"SHA256" => @"HMAC-SHA-256",
         @"SHA384" => @"HMAC-SHA-384",
         @"SHA512" => @"HMAC-SHA-512",
         _ => name.ToString()
     };
 }
예제 #2
0
        /// <summary>
        /// Computes the hash of the string using the specified algorithm.
        /// </summary>
        /// <param name="value">The string which's hash to compute.</param>
        /// <param name="algorithm">The hash algorithm to use for computing the hash.</param>
        /// <returns>Returns the hash value as byte-array.</returns>
        public static byte[] ComputeHash(this string value, HashAlgorithmName algorithm)
        {
            using var implementation = HashAlgorithm.Create(algorithm.ToString());
            var bytes = Encoding.UTF8.GetBytes(value);

            return(implementation.ComputeHash(bytes));
        }
        public CertificateOutputViewModel(byte[] signature, byte[] data, byte[] key, HashAlgorithmName hash,
                                          SymmetricAlgorithmName sym, SymmetricAlgorithmKey symKey, AsymmetricAlgorithmName alg,
                                          AsymmetricAlgorithmKey algKey, string file)
        {
            this.Description = "Certificate";

            this.EnvelopeData     = Convert.ToBase64String(data);
            this.EnvelopeCryptKey = key.ConvertToHex();
            this.Signature        = signature.ConvertToHex();

            this.Methods = new List <string>()
            {
                hash.ToString(),
                    sym.ToString(),
                    alg.ToString()
            };
            this.Method     = string.Join("\n", Methods);
            this.KeyLengths = new List <string>()
            {
                "",
                ((int)symKey).ToString("X"), // hex
                ((int)algKey).ToString("X")  // hex
            };
            this.KeyLength = string.Join("\n", KeyLengths);
            this.FileName  = file;
        }
예제 #4
0
 public ScramShaMechanism(
     UsernamePasswordCredential credential,
     HashAlgorithmName hashAlgorithmName,
     IRandomStringGenerator randomStringGenerator,
     H h,
     Hi hi,
     Hmac hmac)
 {
     _credential = Ensure.IsNotNull(credential, nameof(credential));
     _h          = h;
     _hi         = hi;
     _hmac       = hmac;
     if (!hashAlgorithmName.ToString().StartsWith("SHA"))
     {
         throw new ArgumentException("Must specify a SHA algorithm.");
     }
     _name = $"SCRAM-SHA-{hashAlgorithmName.ToString().Substring(3)}";
     _randomStringGenerator = Ensure.IsNotNull(randomStringGenerator, nameof(randomStringGenerator));
 }
        public static string GetBankingSignature(this string dataToSign, string privateKey, HashAlgorithmName hashAlgorithmName)
        {
            var csp = new RSACryptoServiceProvider(2048);

            csp.FromXmlStringEx(privateKey);
            var inputBytes     = Encoding.UTF8.GetBytes(dataToSign);
            var signatureBytes = csp.SignData(inputBytes, hashAlgorithmName.ToString());

            return(Convert.ToBase64String(signatureBytes));
        }
예제 #6
0
 public SignatureOutputViewModel(byte[] signature, HashAlgorithmName hash, AsymmetricAlgorithmName alg,
                                 AsymmetricAlgorithmKey algKey, string file)
 {
     this.Description = "Signature";
     this.Signature   = signature.ConvertToHex();
     this.Methods     = new List <string>()
     {
         hash.ToString(),
             alg.ToString()
     };
     this.Method     = string.Join("\n", Methods);
     this.KeyLengths = new List <string>()
     {
         "0A",
         ((int)algKey).ToString("X")  // hex
     };
     this.KeyLength = string.Join("\n", KeyLengths);
     this.FileName  = file;
 }
        private static void X509Certificate2ToString(X509Certificate2 cert, StringBuilder certStringBuilder, HashAlgorithmName fingerprintAlgorithm, string indentation)
        {
            var certificateFingerprint = GetHashString(cert, fingerprintAlgorithm);

            certStringBuilder.AppendLine($"{indentation}{string.Format(CultureInfo.CurrentCulture, Strings.CertUtilityCertificateSubjectName, cert.Subject)}");
            certStringBuilder.AppendLine($"{indentation}{string.Format(CultureInfo.CurrentCulture, Strings.CertUtilityCertificateHashSha1, cert.Thumbprint)}");
            certStringBuilder.AppendLine($"{indentation}{string.Format(CultureInfo.CurrentCulture, Strings.CertUtilityCertificateHash, fingerprintAlgorithm.ToString(), certificateFingerprint)}");
            certStringBuilder.AppendLine($"{indentation}{string.Format(CultureInfo.CurrentCulture, Strings.CertUtilityCertificateIssuer, cert.IssuerName.Name)}");
            certStringBuilder.AppendLine($"{indentation}{string.Format(CultureInfo.CurrentCulture, Strings.CertUtilityCertificateValidity, cert.NotBefore, cert.NotAfter)}");
        }
        /// <summary>
        /// Converts a X509Certificate2 to a collection of log messages for various verbosity levels -
        /// Subject Name: CN=name
        /// SHA1 hash: hash
        /// Issued by: CN=issuer
        /// Valid from: issue date time to expiry date time in local time
        /// </summary>
        /// <param name="cert">X509Certificate2 to be converted to string.</param>
        /// <param name="fingerprintAlgorithm">Algorithm used to calculate certificate fingerprint</param>
        /// <returns>string representation of the X509Certificate2.</returns>
        internal static IReadOnlyList <SignatureLog> X509Certificate2ToLogMessages(X509Certificate2 cert, HashAlgorithmName fingerprintAlgorithm, string indentation = "  ")
        {
            var certificateFingerprint = GetHashString(cert, fingerprintAlgorithm);
            var issues = new List <SignatureLog>();

            issues.Add(SignatureLog.MinimalLog($"{indentation}{string.Format(CultureInfo.CurrentCulture, Strings.CertUtilityCertificateSubjectName, cert.Subject)}"));
            issues.Add(SignatureLog.InformationLog($"{indentation}{string.Format(CultureInfo.CurrentCulture, Strings.CertUtilityCertificateHashSha1, cert.Thumbprint)}"));
            issues.Add(SignatureLog.MinimalLog($"{indentation}{string.Format(CultureInfo.CurrentCulture, Strings.CertUtilityCertificateHash, fingerprintAlgorithm.ToString(), certificateFingerprint)}"));
            issues.Add(SignatureLog.InformationLog($"{indentation}{string.Format(CultureInfo.CurrentCulture, Strings.CertUtilityCertificateIssuer, cert.IssuerName.Name)}"));
            issues.Add(SignatureLog.MinimalLog($"{indentation}{string.Format(CultureInfo.CurrentCulture, Strings.CertUtilityCertificateValidity, cert.NotBefore, cert.NotAfter)}"));

            return(issues);
        }
예제 #9
0
 public static String SignHash(string data, HashAlgorithmName algorithmName, X509Certificate2 cert, OutputDataType datatype)
 {
     byte[] bData, bHash, bResult;
     HashAlgorithm ha = GetHashAlgorithm(algorithmName);
     bData = UnicodeEncoding.UTF8.GetBytes(data);
     bHash = ha.ComputeHash(bData);
     RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;
     bResult = rsa.SignHash(bHash, CryptoConfig.MapNameToOID(algorithmName.ToString()));
     return ToString(bResult, datatype);
 }
예제 #10
0
        /// <summary>
        /// Updates the certificate list of a trusted signer by adding the given certificate.
        /// If the signer does not exists it creates a new one.
        /// </summary>
        /// <remarks>This method defaults to adding a trusted author if the signer doesn't exist.</remarks>
        /// <param name="name">Name of the trusted author.</param>
        /// <param name="fingerprint">Fingerprint to be added to the certificate entry.</param>
        /// <param name="hashAlgorithm">Hash algorithm used to calculate <paramref name="fingerprint"/>.</param>
        /// <param name="allowUntrustedRoot">Specifies if allowUntrustedRoot should be set to true in the certificate entry.</param>
        public void AddOrUpdateTrustedSigner(string name, string fingerprint, HashAlgorithmName hashAlgorithm, bool allowUntrustedRoot)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(name));
            }

            if (string.IsNullOrEmpty(fingerprint))
            {
                throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(fingerprint));
            }

            if (!Enum.IsDefined(typeof(HashAlgorithmName), hashAlgorithm) || hashAlgorithm == HashAlgorithmName.Unknown)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.UnsupportedHashAlgorithm, hashAlgorithm.ToString()));
            }

            var certificateToAdd          = new CertificateItem(fingerprint, hashAlgorithm, allowUntrustedRoot);
            TrustedSignerItem signerToAdd = null;

            var signers = _trustedSignersProvider.GetTrustedSigners();

            foreach (var existingSigner in signers)
            {
                if (string.Equals(existingSigner.Name, name, StringComparison.Ordinal))
                {
                    signerToAdd = existingSigner;

                    break;
                }
            }

            string logMessage = null;

            if (signerToAdd == null)
            {
                signerToAdd = new AuthorItem(name, certificateToAdd);
                logMessage  = Strings.SuccessfullyAddedTrustedAuthor;
            }
            else
            {
                signerToAdd.Certificates.Add(certificateToAdd);
                logMessage = Strings.SuccessfullUpdatedTrustedSigner;
            }

            _trustedSignersProvider.AddOrUpdateTrustedSigner(signerToAdd);

            _logger.Log(LogLevel.Information, string.Format(CultureInfo.CurrentCulture, logMessage, name));
        }
        private PackageVerificationResult VerifyAllowList(ISignedPackageReader package, Signature signature, SignedPackageVerifierSettings settings)
        {
            var status = SignatureVerificationStatus.Trusted;
            var issues = new List <SignatureLog>();

            if (_allowList.Count() > 0 && !IsSignatureAllowed(signature))
            {
                status = SignatureVerificationStatus.Invalid;
                issues.Add(SignatureLog.Issue(fatal: true, code: NuGetLogCode.NU3003, message: string.Format(CultureInfo.CurrentCulture, Strings.Error_NoMatchingCertificate, _fingerprintAlgorithm.ToString())));
            }

            return(new SignedPackageVerificationResult(status, signature, issues));
        }