/// <summary> /// Hash Encrypt a string. /// </summary> /// <param name="input">The input string.</param> /// <param name="mode">The <see cref="HashAlgorithmType"/> enum.</param> /// <returns>The encrypted hash string.</returns> public static string Encrypt(string input, HashAlgorithmType mode) { ExceptionManager.ThrowArgumentNullExceptionIfNullOrEmpty(input); byte[] utf8Bytes = Encoding.UTF8.GetBytes(input); string result; switch (mode) { case HashAlgorithmType.MD5: result = CalculateHash(new MD5CryptoServiceProvider(), utf8Bytes); break; case HashAlgorithmType.SHA1: result = CalculateHash(new SHA1CryptoServiceProvider(), utf8Bytes); break; case HashAlgorithmType.SHA256: result = CalculateHash(new SHA256CryptoServiceProvider(), utf8Bytes); break; case HashAlgorithmType.SHA384: result = CalculateHash(new SHA384CryptoServiceProvider(), utf8Bytes); break; case HashAlgorithmType.SHA512: result = CalculateHash(new SHA512CryptoServiceProvider(), utf8Bytes); break; default: result = CalculateHash(new MD5CryptoServiceProvider(), utf8Bytes); break; } return result; }
/// <summary> /// Initializes a new instance of the HashAlgorithm class. /// </summary> /// <param name="serviceProvider">The name of the service provider which implements the hash algorithm</param> /// <param name="mechanism">The hash algorithm type</param> public HashAlgorithm(HashAlgorithmType hashAlgorithm, string serviceProvider = "") : base(new Session(serviceProvider, (MechanismType)hashAlgorithm), true) { m_mechanism = new Mechanism((MechanismType)hashAlgorithm); m_hashSize = -1; Initialize(); }
public CipherSuite Add( short code, string name, CipherAlgorithmType cipherType, HashAlgorithmType hashType, ExchangeAlgorithmType exchangeType, bool exportable, bool blockMode, byte keyMaterialSize, byte expandedKeyMaterialSize, short effectiveKeyBytes, byte ivSize, byte blockSize) { switch (this.protocol) { case SecurityProtocolType.Default: case SecurityProtocolType.Tls: return((CipherSuite)this.add(new TlsCipherSuite(code, name, cipherType, hashType, exchangeType, exportable, blockMode, keyMaterialSize, expandedKeyMaterialSize, effectiveKeyBytes, ivSize, blockSize))); case SecurityProtocolType.Ssl3: return((CipherSuite)this.add(new SslCipherSuite(code, name, cipherType, hashType, exchangeType, exportable, blockMode, keyMaterialSize, expandedKeyMaterialSize, effectiveKeyBytes, ivSize, blockSize))); default: throw new NotSupportedException("Unsupported security protocol type."); } }
/// <summary> /// Initializes a new instance of the <see cref="DigestAccessAuthenticationParameters"/> class. /// </summary> /// <param name="credentials">The credentials used in the computation of HA1-, HA2-, and response hash values.</param> /// <param name="httpMethod">The HTTP method to include in the HA2 computed value.</param> /// <param name="password">The password to include in the HA1 computed value.</param> /// <param name="algorithm">The algorithm to use when computing the HA1-, HA2-, and response hash values.</param> internal DigestAccessAuthenticationParameters(ImmutableDictionary <string, string> credentials, string httpMethod, string password, HashAlgorithmType algorithm) { Credentials = credentials; HttpMethod = httpMethod; Password = password; Algorithm = algorithm; }
public async void Query() { var privateKey = new PrivateKey(); var preEval = new BlockContent <NullAction> { Index = 1, Difficulty = 1, TotalDifficulty = 1, PublicKey = privateKey.PublicKey, PreviousHash = new BlockHash(TestUtils.GetRandomBytes(HashDigest <SHA256> .Size)), Timestamp = DateTimeOffset.UtcNow, }.Mine(HashAlgorithmType.Of <SHA256>()); var stateRootHash = new HashDigest <SHA256>(TestUtils.GetRandomBytes(HashDigest <SHA256> .Size)); var block = new Block <NullAction>( preEval, stateRootHash, preEval.MakeSignature(privateKey, stateRootHash) ); var query = @"{ index hash nonce difficulty totalDifficulty miner publicKey timestamp stateRootHash signature }"; ExecutionResult result = await ExecuteQueryAsync <BlockType <NullAction> >(query, source : block); Dictionary <string, object> resultData = (Dictionary <string, object>)result.Data; Assert.Null(result.Errors); Assert.Equal(block.Index, resultData["index"]); Assert.Equal( ByteUtil.Hex(block.Hash.ToByteArray()), resultData["hash"]); Assert.Equal(block.Difficulty, resultData["difficulty"]); Assert.Equal( block.TotalDifficulty, resultData["totalDifficulty"]); Assert.Equal( block.Miner.ToString(), resultData["miner"]); Assert.Equal( ByteUtil.Hex(block.Nonce.ToByteArray()), resultData["nonce"]); Assert.Equal( new DateTimeOffsetGraphType().Serialize(block.Timestamp), resultData["timestamp"]); Assert.Equal( ByteUtil.Hex(block.StateRootHash.ToByteArray()), resultData["stateRootHash"]); }
/// <summary> /// Initializes a new instance of the HashAlgorithm class. /// </summary> /// <param name="session">The Cryptoki session context the hash algorithm will execute in.</param> /// <param name="mechanism">The hash algorithm type</param> public HashAlgorithm(HashAlgorithmType hashAlgorithm, Session session) : base(session, false) { m_mechanism = new Mechanism((MechanismType)hashAlgorithm); m_hashSize = -1; Initialize(); }
public static IHashAlgorithm CreateAlgorithm(HashAlgorithmType type) { switch (type) { case HashAlgorithmType.Md5Sha1: return(new MD5SHA1()); case HashAlgorithmType.Md5: return(new MD5CryptoServiceProvider()); case HashAlgorithmType.Sha1: return(new SHA1CryptoServiceProvider()); case HashAlgorithmType.Sha224: return(new SHA224Managed()); case HashAlgorithmType.Sha256: return(new SHA256Managed()); case HashAlgorithmType.Sha384: return(new SHA384Managed()); case HashAlgorithmType.Sha512: return(new SHA512Managed()); default: throw new NotSupportedException(); } }
public static async Task <Result <EncryptedFileInfo> > EncryptFileAsync( string filePath, string publicKeyXmlFilePath, HashAlgorithmType hashAlgorithm = HashAlgorithmType.SHA2_256) { var folderPath = Path.GetDirectoryName(filePath); var encryptedFileName = $"{Path.GetFileName(filePath)}.encrypted"; var infoXmlFilePath = Path.Combine(folderPath, $"{encryptedFileName}.xml"); EncryptedFileInfo infoXml; try { var publicKeyXml = CryptoKeys.ReadXmlKeyFromFile(publicKeyXmlFilePath); infoXml = await Task.Factory.StartNew(() => Encrypt(filePath, publicKeyXml, hashAlgorithm)).ConfigureAwait(false); } catch (FileNotFoundException ex) { return(Result.Fail <EncryptedFileInfo>($"{ex.Message} {ex.GetType()}")); } var serializationResult = EncryptedFileInfo.SaveToFile(infoXml, infoXmlFilePath); return(serializationResult.Success ? Result.Ok(infoXml) : Result.Fail <EncryptedFileInfo>("Error occurred serializing encrypted file info to XML.")); }
public static string GetOID(HashAlgorithmType type) { switch (type) { case HashAlgorithmType.Md5Sha1: return(null); case HashAlgorithmType.Md5: return("1.2.840.113549.2.5"); case HashAlgorithmType.Sha1: return("1.3.14.3.2.26"); case HashAlgorithmType.Sha224: return("2.16.840.1.101.3.4.2.4"); case HashAlgorithmType.Sha256: return("2.16.840.1.101.3.4.2.1"); case HashAlgorithmType.Sha384: return("2.16.840.1.101.3.4.2.2"); case HashAlgorithmType.Sha512: return("2.16.840.1.101.3.4.2.3"); default: throw new NotSupportedException(); } }
public static int GetHashSize(HashAlgorithmType type) { switch (type) { case HashAlgorithmType.Md5Sha1: return(288); case HashAlgorithmType.Md5: return(128); case HashAlgorithmType.Sha1: return(160); case HashAlgorithmType.Sha224: return(224); case HashAlgorithmType.Sha256: return(256); case HashAlgorithmType.Sha384: return(384); case HashAlgorithmType.Sha512: return(512); default: throw new NotSupportedException(); } }
public async Task NodeStatus() { var cts = new CancellationTokenSource(); var apvPrivateKey = new PrivateKey(); var apv = AppProtocolVersion.Sign(apvPrivateKey, 0); var genesisBlock = BlockChain <EmptyAction> .MakeGenesisBlock( HashAlgorithmType.Of <SHA256>() ); // 에러로 인하여 NineChroniclesNodeService 를 사용할 수 없습니다. https://git.io/JfS0M // 따라서 LibplanetNodeService로 비슷한 환경을 맞춥니다. // 1. 노드를 생성합니다. var seedNode = CreateLibplanetNodeService <EmptyAction>(genesisBlock, apv, apvPrivateKey.PublicKey); await StartAsync(seedNode.Swarm, cts.Token); var service = CreateLibplanetNodeService <EmptyAction>(genesisBlock, apv, apvPrivateKey.PublicKey, peers: new [] { seedNode.Swarm.AsPeer }); // 2. NineChroniclesNodeService.ConfigureStandaloneContext(standaloneContext)를 호출합니다. // BlockChain 객체 공유 및 PreloadEnded, BootstrapEnded 이벤트 훅의 처리를 합니다. // BlockChain 객체 공유는 액션 타입이 달라 생략합니다. _ = service.BootstrapEnded.WaitAsync() .ContinueWith(task => StandaloneContextFx.BootstrapEnded = true); _ = service.PreloadEnded.WaitAsync() .ContinueWith(task => StandaloneContextFx.PreloadEnded = true); var bootstrapEndedTask = service.BootstrapEnded.WaitAsync(); var preloadEndedTask = service.PreloadEnded.WaitAsync(); async Task <Dictionary <string, bool> > QueryNodeStatus() { var result = await ExecuteQueryAsync("query { nodeStatus { bootstrapEnded preloadEnded } }"); var data = (Dictionary <string, object>)result.Data; var nodeStatusData = (Dictionary <string, object>)data["nodeStatus"]; return(nodeStatusData.ToDictionary(pair => pair.Key, pair => (bool)pair.Value)); } var nodeStatus = await QueryNodeStatus(); Assert.False(nodeStatus["bootstrapEnded"]); Assert.False(nodeStatus["preloadEnded"]); _ = service.StartAsync(cts.Token); await bootstrapEndedTask; await preloadEndedTask; // ContinueWith으로 넘긴 태스크가 실행되기를 기다립니다. await Task.Delay(1000); nodeStatus = await QueryNodeStatus(); Assert.True(nodeStatus["bootstrapEnded"]); Assert.True(nodeStatus["preloadEnded"]); await seedNode.StopAsync(cts.Token); }
public static string GetAlgorithmName(HashAlgorithmType type) { switch (type) { case HashAlgorithmType.Md5Sha1: return("MD5SHA1"); case HashAlgorithmType.Md5: return("MD5"); case HashAlgorithmType.Sha1: return("SHA1"); case HashAlgorithmType.Sha224: return("SHA224"); case HashAlgorithmType.Sha256: return("SHA256"); case HashAlgorithmType.Sha384: return("SHA384"); case HashAlgorithmType.Sha512: return("SHA512"); default: throw new NotSupportedException(); } }
private static HashAlgorithm InitialiseHasher(HashAlgorithmType hashAlgorithmType) { switch (hashAlgorithmType) { case HashAlgorithmType.Md5: return(MD5.Create()); case HashAlgorithmType.Sha1: return(new SHA1Managed()); case HashAlgorithmType.Sha256: return(new SHA256Managed()); case HashAlgorithmType.Sha384: return(new SHA384Managed()); case HashAlgorithmType.Sha512: return(new SHA512Managed()); case HashAlgorithmType.None: throw new ArgumentOutOfRangeException(nameof(hashAlgorithmType), hashAlgorithmType, "A hash algorithm was not provided"); default: throw new ArgumentOutOfRangeException(nameof(hashAlgorithmType), hashAlgorithmType, "A valid hash algorithm was not provided"); } }
public static void Copy(this IStore from, IStore to) { // TODO: take a IProgress<> so that a caller can be aware the progress of cloning. if (to.ListChainIds().Any()) { throw new ArgumentException("The destination store has to be empty.", nameof(to)); } foreach (Guid chainId in from.ListChainIds().ToArray()) { foreach (BlockHash blockHash in from.IterateIndexes(chainId)) { Block <NullAction> block = from.GetBlock <NullAction>( _ => HashAlgorithmType.Of <SHA256>(), // thunk getter; doesn't matter here blockHash ); to.PutBlock(block); to.AppendIndex(chainId, blockHash); } foreach (KeyValuePair <Address, long> kv in from.ListTxNonces(chainId)) { to.IncreaseTxNonce(chainId, kv.Key, kv.Value); } } if (from.GetCanonicalChainId() is Guid canonId) { to.SetCanonicalChainId(canonId); } }
public static HashAlgorithm Create(HashAlgorithmType type) { switch (type) { case HashAlgorithmType.MD5: return(new MD5CryptoServiceProvider()); case HashAlgorithmType.SHA1: return(new SHA1Managed()); case HashAlgorithmType.SHA256: return(new SHA256Managed()); case HashAlgorithmType.SHA384: return(new SHA384Managed()); case HashAlgorithmType.SHA512: return(new SHA512Managed()); case HashAlgorithmType.RIPEMD160: return(new RIPEMD160Managed()); default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } }
/// <summary> /// 计算字符串的哈希值 /// </summary> /// <param name="s"></param> /// <param name="hashAlgorithmType"></param> /// <param name="encoding">指定字符串的编码</param> /// <returns></returns> public static byte[] GetHash(string s, HashAlgorithmType hashAlgorithmType, Encoding encoding) { CheckUtil.ArgumentNotNullOrEmpty(s, "s"); byte[] data = encoding.GetBytes(s); return(GetHash(data, hashAlgorithmType)); }
private string GetHash(HashAlgorithmType hashAlgorithmType, string input) { // Convert the input string to a byte array and compute the hash. byte[] data = hashAlgorithmType == HashAlgorithmType.MD5 ? new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(input)) : hashAlgorithmType == HashAlgorithmType.SHA256 ? SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(input)) : null; // Create a new Stringbuilder to collect the bytes // and create a string. var sBuilder = new StringBuilder(); if (data != null) { // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } } // Return the hexadecimal string. return(sBuilder.ToString()); }
public void Constructor() { var genesisBlock = BlockChain <DummyAction> .MakeGenesisBlock(HashAlgorithmType.Of <SHA256>()); var service = new LibplanetNodeService <DummyAction>( new LibplanetNodeServiceProperties <DummyAction>() { AppProtocolVersion = new AppProtocolVersion(), GenesisBlock = genesisBlock, SwarmPrivateKey = new PrivateKey(), StoreStatesCacheSize = 2, StorePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()), Host = IPAddress.Loopback.ToString(), }, blockPolicy: new BlockPolicy <DummyAction>(), stagePolicy: new VolatileStagePolicy <DummyAction>(), renderers: null, minerLoopAction: (chain, swarm, pk, ct) => Task.CompletedTask, preloadProgress: null, exceptionHandlerAction: (code, msg) => throw new Exception($"{code}, {msg}"), preloadStatusHandlerAction: isPreloadStart => { } ); Assert.NotNull(service); }
/// <summary> /// 创建一个哈希算法提供者实例 /// </summary> /// <param name="hashAlgorithmType"></param> /// <returns></returns> public static HashAlgorithm CreateHashAlgorithmProvider(HashAlgorithmType hashAlgorithmType) { HashAlgorithm hashAlgorithm = null; switch (hashAlgorithmType) { case HashAlgorithmType.MD5: hashAlgorithm = new MD5CryptoServiceProvider(); break; case HashAlgorithmType.SHA1: hashAlgorithm = new SHA1Managed(); break; case HashAlgorithmType.SHA256: hashAlgorithm = new SHA256Managed(); break; case HashAlgorithmType.SHA384: hashAlgorithm = new SHA384Managed(); break; case HashAlgorithmType.SHA512: hashAlgorithm = new SHA512Managed(); break; default: hashAlgorithm = new MD5CryptoServiceProvider(); break; } return(hashAlgorithm); }
public void DeriveByteKeyHashGeneric(string expectedKey, HashAlgorithmType hashAlgorithmType, bool useFullyQualifiedTypeName, object[] inputs) { var bytes = CacheKeyFactory.DeriveByteKeyHash <CacheKeyFactoryTests>(hashAlgorithmType, useFullyQualifiedTypeName, inputs); var result = bytes == null ? null : Encoding.UTF8.GetString(bytes); result.Should().Be(expectedKey); }
private static int GetHashSize(HashAlgorithmType hash) { switch (hash) { case HashAlgorithmType.None: return(0); case HashAlgorithmType.Md5: return(128); case HashAlgorithmType.Sha1: return(160); case HashAlgorithmType.Sha256: return(256); case HashAlgorithmType.Sha384: return(384); case HashAlgorithmType.Sha512: return(512); default: throw new ArgumentOutOfRangeException(nameof(hash)); } }
public void DeriveByteKeyHash(string expectedKey, HashAlgorithmType hashAlgorithmType, object[] inputs) { var bytes = CacheKeyFactory.DeriveByteKeyHash(hashAlgorithmType, inputs); var result = bytes == null ? null : Encoding.UTF8.GetString(bytes); result.Should().Be(expectedKey); }
/// <summary> /// Hash加密构造函数 /// </summary> /// <param name="haType">Hash算法类别</param> public HashEncryption(HashAlgorithmType haType = HashAlgorithmType.MD5) { switch (haType) { case HashAlgorithmType.MD5: ha = new MD5CryptoServiceProvider(); break; case HashAlgorithmType.SHA1: ha = new SHA1CryptoServiceProvider(); break; case HashAlgorithmType.SHA256: ha = new SHA256CryptoServiceProvider(); break; case HashAlgorithmType.SHA384: ha = new SHA384CryptoServiceProvider(); break; case HashAlgorithmType.SHA512: ha = new SHA512CryptoServiceProvider(); break; } }
public void DigestMultipleTimes() { HashAlgorithmType sha256 = HashAlgorithmType.Of <SHA256>(); byte[] expected = { 0x78, 0x71, 0xe9, 0xcf, 0xd3, 0xf8, 0x22, 0x41, 0xd1, 0xd1, 0x70, 0x77, 0x27, 0x42, 0x12, 0xe5, 0xae, 0x20, 0xaa, 0xcd, 0x9c, 0xad, 0x04, 0xa4, 0x9d, 0x33, 0x69, 0x3b, 0xeb, 0xed, 0x0d, 0x8b, }; byte[] input = Encoding.ASCII.GetBytes("Hello, world! Foo. Bar"); byte[][] chunkedInput = { Encoding.ASCII.GetBytes("Hello, "), Encoding.ASCII.GetBytes("world! "), Encoding.ASCII.GetBytes("Foo. "), Encoding.ASCII.GetBytes("Bar"), }; byte[] digest; for (int i = 0; i < 20; i++) { for (int j = 0; j < 2; j++) { digest = sha256.Digest(input); AssertBytesEqual(expected, digest); } for (int j = 0; j < 2; j++) { digest = sha256.Digest(chunkedInput); AssertBytesEqual(expected, digest); } } }
/// <summary> /// Signs the bundle with certificate described by its thumprint. /// </summary> /// <param name="bundle"></param> /// <param name="certificateThumbprint">Certificate thumprint.</param> /// <param name="signedContentDescription">Description of the product.</param> /// <param name="timestampServerUrl">Timestamp server URL</param> /// <param name="hashAlgorithm">Hash algorithm</param> /// <returns>Same instance for chaining.</returns> public static Bundle SignWithCertificateThumprint(this Bundle bundle, string certificateThumbprint, string signedContentDescription, Uri timestampServerUrl, HashAlgorithmType hashAlgorithm = HashAlgorithmType.sha256) { if (bundle is null) throw new ArgumentNullException(nameof(bundle)); if (string.IsNullOrWhiteSpace(certificateThumbprint)) throw new ArgumentException("Invalid certificate thumbprint.", nameof(certificateThumbprint)); if (string.IsNullOrWhiteSpace(signedContentDescription)) throw new ArgumentException("Invalid signed content description.", nameof(signedContentDescription)); if (timestampServerUrl is null) throw new ArgumentNullException(nameof(timestampServerUrl)); // https://github.com/oleg-shilo/wixsharp/blob/master/Source/src/WixSharp.Samples/Wix%23%20Samples/Signing/setup.cs // https://github.com/oleg-shilo/wixsharp/issues/827 bundle.DigitalSignature = new DigitalSignatureBootstrapper() { // https://github.com/oleg-shilo/wixsharp/issues/827 // CertificateId = CertificateThumbprint, // CertificateStore = StoreType.sha1Hash, // HashAlgorithm = HashAlgorithmType.sha256, Description = signedContentDescription, TimeUrl = timestampServerUrl, OptionalArguments = $"/v /sha1 {certificateThumbprint} /fd {hashAlgorithm}" }; return bundle; }
public async Task CompleteWithBlockFetcherGivingWrongBlocks() { HashAlgorithmGetter hashAlgoGetter = _ => HashAlgorithmType.Of <SHA256>(); Block <DumbAction> genesis = MineGenesisBlock <DumbAction>( hashAlgoGetter, GenesisMiner), demand = MineNextBlock(genesis, hashAlgoGetter, GenesisMiner), wrong = MineNextBlock(genesis, hashAlgoGetter, GenesisMiner); _logger.Debug("Genesis: #{Index} {Hash}", genesis.Index, genesis.Hash); _logger.Debug("Demand: #{Index} {Hash}", demand.Index, demand.Hash); _logger.Debug("Wrong: #{Index} {Hash}", wrong.Index, wrong.Hash); var bc = new BlockCompletion <char, DumbAction>( ((IEquatable <BlockHash>)genesis.Hash).Equals, 5 ); bc.Demand(demand.Hash); long counter = 0; BlockCompletion <char, DumbAction> .BlockFetcher wrongBlockFetcher = (peer, blockHashes, token) => new AsyncEnumerable <Block <DumbAction> >(async yield => { // Provides a wrong block (i.e., not corresponding to the demand) at first call, // and then provide a proper block later calls. await yield.ReturnAsync(Interlocked.Read(ref counter) < 1 ? wrong : demand); Interlocked.Increment(ref counter); }); Tuple <Block <DumbAction>, char>[] result = await AsyncEnumerable.ToArrayAsync(bc.Complete(new[] { 'A' }, wrongBlockFetcher)); Assert.Equal(new[] { Tuple.Create(demand, 'A') }, result); }
public void DigestStream() { byte[][] inputs = { Encoding.ASCII.GetBytes("Hello, "), Encoding.ASCII.GetBytes("world! "), Encoding.ASCII.GetBytes("Foo. "), Encoding.ASCII.GetBytes("Bar"), }; byte[] expected = { 0xd9, 0xeb, 0x17, 0xa0, 0x2c, 0x6a, 0x25, 0xd3, 0xba, 0x42, 0xef, 0x18, 0xda, 0xa5, 0xf1, 0x6a, }; HashAlgorithmType md5 = HashAlgorithmType.Of <MD5>(); byte[] digest = md5.Digest(inputs); AssertBytesEqual(expected, digest); ImmutableArray <byte> immutableDigest = md5.Digest(inputs.Select(c => c.ToImmutableArray())); AssertBytesEqual(expected.ToImmutableArray(), immutableDigest); }
IHashAlgorithm GetAlgorithm(HashAlgorithmType type) { switch (type) { case HashAlgorithmType.Md5Sha1: return(hashes [0]); case HashAlgorithmType.Sha1: return(hashes [1]); case HashAlgorithmType.Sha224: return(hashes [2]); case HashAlgorithmType.Sha256: return(hashes [3]); case HashAlgorithmType.Sha384: return(hashes [4]); case HashAlgorithmType.Sha512: return(hashes [5]); default: throw new NotSupportedException(); } }
public static byte[] GetHashAsBytes(string message, string key, HashAlgorithmType hashAlgorithmType, Encoding encoding) { var messageBytes = encoding.GetBytes(message); var keyBytes = encoding.GetBytes(key); return(GetHashAsBytes(messageBytes, keyBytes, hashAlgorithmType)); }
public BlockType() { Field(x => x.Hash, type: typeof(NonNullGraphType <IdGraphType>)); Field(x => x.Index); Field(x => x.Difficulty); Field(x => x.TotalDifficulty); Field <NonNullGraphType <ByteStringType> >( "Nonce", resolve: ctx => ctx.Source.Nonce.ToByteArray() ); Field(x => x.Miner, type: typeof(NonNullGraphType <AddressType>)); Field(x => x.PublicKey, type: typeof(PublicKeyType)); Field <BlockType <T> >( "PreviousBlock", resolve: ctx => { if (!(ctx.Source.PreviousHash is BlockHash h)) { return(null); } // FIXME: (BlockChain<T>) casting does not work // REF COMMIT HASH: d50c90933c17a70381ad758719144e01bf9c21dc HashAlgorithmGetter hashAlgorithmGetter = _ => HashAlgorithmType.Of <SHA256>(); var store = (IStore)ctx.UserContext[nameof(IBlockChainContext <T> .Store)]; return(store.GetBlock <T>(hashAlgorithmGetter, h)); });
public bool IsHandling(HashAlgorithmType algorithmType) { var handled = algorithmType == HashAlgorithmType.Sha1; Console.WriteLine($"Handled: {handled} {algorithmType}"); return(handled); }
public void CancelMine() { using (CancellationTokenSource source = new CancellationTokenSource()) { HashAlgorithmType sha512 = HashAlgorithmType.Of <SHA512>(); Block1.Difficulty = long.MaxValue; Exception exception = null; Task task = Task.Run(() => { try { Block1.Mine(sha512, source.Token); } catch (OperationCanceledException ce) { exception = ce; } }); source.Cancel(); bool taskEnded = task.Wait(TimeSpan.FromSeconds(10)); Assert.True(taskEnded); Assert.NotNull(exception); Assert.IsAssignableFrom <OperationCanceledException>(exception); } }
public void ValidateWithMultipleAlgorithms() { using (var fx = new MemoryStoreFixture()) { IBlockPolicy <DumbAction> policy = new MultiAlgoPolicy <DumbAction>(); BlockChain <DumbAction> chain = TestUtils.MakeBlockChain( policy, fx.Store, fx.StateStore, new DumbAction[0] ); HashAlgorithmType invalidAlgo = HashAlgorithmType.Of <SHA1>(); Block <DumbAction> invalidBlock = TestUtils.MineNext( chain.Genesis, _ => invalidAlgo, miner: TestUtils.ChainPrivateKey.PublicKey, difficulty: policy.GetNextBlockDifficulty(chain) ).Evaluate(TestUtils.ChainPrivateKey, chain); Assert.Throws <InvalidBlockHashAlgorithmTypeException>( () => chain.Append(invalidBlock)); HashAlgorithmType validAlgo = HashAlgorithmType.Of <MD5>(); Block <DumbAction> validBlock = TestUtils.MineNext( chain.Genesis, _ => validAlgo, miner: TestUtils.ChainPrivateKey.PublicKey, difficulty: policy.GetNextBlockDifficulty(chain) ).Evaluate(TestUtils.ChainPrivateKey, chain); chain.Append(validBlock); } }
/// <summary> /// 计算文件流的哈希值并将其转换为使用Base64编码的字符串 /// </summary> /// <param name="fileStream"></param> /// <param name="hashAlgorithmType"></param> /// <returns></returns> public static string GetHash2Base64(FileStream fileStream, HashAlgorithmType hashAlgorithmType) { CheckUtil.ArgumentNotNull(fileStream, "fileStream"); byte[] bytes = GetHash(fileStream, hashAlgorithmType); string result = Convert.ToBase64String(bytes); return result; }
static byte[] CreateHash (HashAlgorithmType type, SecureBuffer data) { if (!HashAlgorithmProvider.IsAlgorithmSupported (type)) throw new TlsException (AlertDescription.IlegalParameter); using (var d = new DisposeContext ()) { var algorithm = d.Add (HashAlgorithmProvider.CreateAlgorithm (type)); algorithm.TransformBlock (data.Buffer, 0, data.Size); return algorithm.GetRunningHash (); } }
/// <summary> /// 计算字节数组的哈希值 /// </summary> /// <param name="data"></param> /// <param name="hashAlgorithmType"></param> /// <returns></returns> public static byte[] GetHash(byte[] data, HashAlgorithmType hashAlgorithmType) { CheckUtil.ArgumentNotNull(data, "data"); HashAlgorithm hashAlgorithm = CreateHashAlgorithmProvider(hashAlgorithmType); byte[] result = hashAlgorithm.ComputeHash(data); hashAlgorithm.Clear(); return result; }
/// <summary> /// Compute the Hash for a Stream /// </summary> /// <param name="stream">Stream to compute hash for</param> /// <param name="hashAlgorithm">Algorithm to use</param> /// <returns></returns> public static string ComputeHash(Stream stream, HashAlgorithmType hashAlgorithm = HashAlgorithmType.SHA1) { if (stream == null) throw new ArgumentNullException("stream"); byte[] bytes = new byte[stream.Length]; stream.Position = 0; stream.Read(bytes, 0, (int)stream.Length); return HashUtil.ComputeHash(bytes, hashAlgorithm); }
/// <summary> /// 计算文件流的哈希值 /// </summary> /// <param name="fileStream"></param> /// <param name="hashAlgorithmType"></param> /// <returns></returns> public static byte[] GetHash(FileStream fileStream, HashAlgorithmType hashAlgorithmType) { CheckUtil.ArgumentNotNull(fileStream, "fileStream"); HashAlgorithm hashAlgorithm = CreateHashAlgorithmProvider(hashAlgorithmType); byte[] result = hashAlgorithm.ComputeHash(fileStream); hashAlgorithm.Clear(); fileStream.Close(); return result; }
public TlsCipherSuite( short code, string name, CipherAlgorithmType cipherAlgorithmType, HashAlgorithmType hashAlgorithmType, ExchangeAlgorithmType exchangeAlgorithmType, bool exportable, bool blockMode, byte keyMaterialSize, byte expandedKeyMaterialSize, short effectiveKeyBytes, byte ivSize, byte blockSize) :base(code, name, cipherAlgorithmType, hashAlgorithmType, exchangeAlgorithmType, exportable, blockMode, keyMaterialSize, expandedKeyMaterialSize, effectiveKeyBytes, ivSize, blockSize) { }
internal static bool IsAlgorithmSupported (HashAlgorithmType algorithm) { switch (algorithm) { case HashAlgorithmType.Md5: case HashAlgorithmType.Sha1: case HashAlgorithmType.Sha256: case HashAlgorithmType.Sha384: case HashAlgorithmType.Sha512: return true; default: return false; } }
/// <summary> /// 计算文件流的哈希值并将其转换为字符串 /// </summary> /// <param name="fileStream"></param> /// <param name="hashAlgorithmType"></param> /// <returns></returns> public static string GetHash2String(FileStream fileStream, HashAlgorithmType hashAlgorithmType) { CheckUtil.ArgumentNotNull(fileStream, "fileStream"); string result = string.Empty; byte[] bytes = GetHash(fileStream, hashAlgorithmType); foreach (byte b in bytes) { result += Convert.ToString(b, 16).ToUpper(CultureInfo.InvariantCulture).PadLeft(2, '0'); } return result; }
public static string ComputeHash(string plainText, HashAlgorithmType hashAlgorithm, bool outputHexFormat) { HashAlgorithm algorithm; plainText = (SALTHash + plainText); byte[] bytes = Encoding.UTF8.GetBytes(plainText); switch (hashAlgorithm) { case HashAlgorithmType.SHA1: algorithm = new SHA1Managed(); break; case HashAlgorithmType.SHA256: algorithm = new SHA256Managed(); break; case HashAlgorithmType.SHA384: algorithm = new SHA384Managed(); break; case HashAlgorithmType.SHA512: algorithm = new SHA512Managed(); break; default: algorithm = new MD5CryptoServiceProvider(); break; } byte[] inArray = algorithm.ComputeHash(bytes); if (outputHexFormat) { var builder = new StringBuilder(); int num2 = (inArray.Length - 1); int i = 0; while ((i <= num2)) { if ((Conversion.Hex(inArray[i]).Length == 1)) { builder.Append(("0" + Conversion.Hex(inArray[i]))); } else { builder.Append(Conversion.Hex(inArray[i])); } if ((((i + 1)%2) == 0)) { builder.Append(" "); } i++; } return builder.ToString().Trim().Replace(" ", "-"); } return Convert.ToBase64String(inArray); }
public static int GetMacSize (HashAlgorithmType type) { switch (type) { case HashAlgorithmType.Md5: return 16; case HashAlgorithmType.Sha1: return 20; case HashAlgorithmType.Sha256: return 32; case HashAlgorithmType.Sha384: return 48; default: throw new NotSupportedException (); } }
internal Assembly(string name, HashAlgorithmType hashAlgId, ushort majVer, ushort minVer, ushort bldNo, ushort revNo, uint flags, byte[] pKey, string cult, PEFile pefile) : base(name) { this.hashAlgId = hashAlgId; this.majorVer = majVer; this.minorVer = minVer; this.buildNo = bldNo; this.revisionNo = revNo; this.flags = flags; this.publicKey = pKey; this.culture = cult; tabIx = MDTable.Assembly; }
public static string ComputeHashCode(this FileStream fileStream, HashAlgorithmType algorithmType = HashAlgorithmType.SHA1) { using (var algorithm = GetHashAlgorithm(algorithmType)) { var hash = algorithm.ComputeHash(fileStream); var sb = new StringBuilder(hash.Length * 2); foreach (var b in hash) { sb.AppendFormat("{0:X2}", b); } return sb.ToString(); } }
public static HMac Create (HashAlgorithmType type, SecureBuffer key) { switch (type) { case HashAlgorithmType.Md5: return new HMac (MD5.Create (), 64, key); case HashAlgorithmType.Sha1: return new HMac (SHA1.Create (), 64, key); case HashAlgorithmType.Sha256: return new HMac (SHA256.Create (), 64, key); case HashAlgorithmType.Sha384: return new HMac (SHA384.Create (), 128, key); default: throw new NotSupportedException (); } }
public static HashAlgorithm CreateHash (HashAlgorithmType type) { switch (type) { case HashAlgorithmType.Md5: return MD5.Create (); case HashAlgorithmType.Sha1: return SHA1.Create (); case HashAlgorithmType.Sha256: return SHA256.Create (); case HashAlgorithmType.Sha384: return SHA384.Create (); default: throw new NotSupportedException (); } }
public static bool IsAlgorithmSupported (HashAlgorithmType type) { switch (type) { case HashAlgorithmType.Md5Sha1: case HashAlgorithmType.Md5: case HashAlgorithmType.Sha1: case HashAlgorithmType.Sha224: case HashAlgorithmType.Sha256: case HashAlgorithmType.Sha384: case HashAlgorithmType.Sha512: return true; default: return false; } }
internal SecurityPackageContextConnectionInformation ( CipherAlgorithmType algorithmIdentifier, int cipherStrength, int exchangeStrength, HashAlgorithmType hash, int hashStrength, int keyExchangeAlgorithm, SecurityProtocol protocol) { AlgorithmIdentifier = algorithmIdentifier; CipherStrength = cipherStrength; ExchangeStrength = exchangeStrength; Hash = hash; HashStrength = hashStrength; KeyExchangeAlgorithm = keyExchangeAlgorithm; Protocol = protocol; }
private static string ConvertToHashAlgorithmName(HashAlgorithmType algorithmType) { switch (algorithmType) { case HashAlgorithmType.MD5: return HashAlgorithmNames.Md5; case HashAlgorithmType.SHA1: return HashAlgorithmNames.Sha1; case HashAlgorithmType.SHA256: return HashAlgorithmNames.Sha256; case HashAlgorithmType.SHA384: return HashAlgorithmNames.Sha384; case HashAlgorithmType.SHA512: return HashAlgorithmNames.Sha512; default: throw new NotSupportedException(); } }
IHashAlgorithm GetAlgorithm (HashAlgorithmType type) { switch (type) { case HashAlgorithmType.Md5Sha1: return hashes [0]; case HashAlgorithmType.Sha1: return hashes [1]; case HashAlgorithmType.Sha224: return hashes [2]; case HashAlgorithmType.Sha256: return hashes [3]; case HashAlgorithmType.Sha384: return hashes [4]; case HashAlgorithmType.Sha512: return hashes [5]; default: throw new NotSupportedException (); } }
public static IHashAlgorithm CreateAlgorithm (HashAlgorithmType type) { switch (type) { case HashAlgorithmType.Md5Sha1: return new MD5SHA1 (); case HashAlgorithmType.Md5: return new MD5CryptoServiceProvider (); case HashAlgorithmType.Sha1: return new SHA1CryptoServiceProvider (); case HashAlgorithmType.Sha224: return new SHA224Managed (); case HashAlgorithmType.Sha256: return new SHA256Managed (); case HashAlgorithmType.Sha384: return new SHA384Managed (); case HashAlgorithmType.Sha512: return new SHA512Managed (); default: throw new NotSupportedException (); } }
private static HashAlgorithm GetHashAlgorithm(HashAlgorithmType algorithmType) { switch (algorithmType) { case HashAlgorithmType.MD5: return HashAlgorithm.Create("MD5"); case HashAlgorithmType.SHA1: return HashAlgorithm.Create("SHA1"); case HashAlgorithmType.SHA256: return HashAlgorithm.Create("SHA-256"); case HashAlgorithmType.SHA384: return HashAlgorithm.Create("SHA-384"); case HashAlgorithmType.SHA512: return HashAlgorithm.Create("SHA-512"); } throw new ArgumentException(string.Format("Unknown hash algorithm type '{0}'.", algorithmType), "algorithmType"); }
/// <summary> /// Compute the Hash for a Byte Array /// </summary> /// <param name="stream">Byte Array to compute hash for</param> /// <param name="hashAlgorithm">Algorithm to use</param> /// <returns></returns> public static string ComputeHash(byte[] bytes, HashAlgorithmType hashAlgorithm = HashAlgorithmType.SHA1) { if (bytes == null) throw new ArgumentNullException("bytes"); // Initialize appropriate hashing algorithm class. HashAlgorithm hash; switch (hashAlgorithm) { case HashAlgorithmType.MD5: hash = new MD5CryptoServiceProvider(); break; case HashAlgorithmType.SHA1: hash = new SHA1Managed(); break; case HashAlgorithmType.SHA256: hash = new SHA256Managed(); break; case HashAlgorithmType.SHA384: hash = new SHA384Managed(); break; case HashAlgorithmType.SHA512: hash = new SHA512Managed(); break; default: throw new NotImplementedException("HashAlgorithm is not yet implemented."); } // Compute hash value of our plain text. byte[] hashBytes = hash.ComputeHash(bytes); // Convert result into a string. string hashValue = BitConverter.ToString(hashBytes).Replace("-", String.Empty); // Return the result. return hashValue; }
public SslCipherSuite( short code, string name, CipherAlgorithmType cipherAlgorithmType, HashAlgorithmType hashAlgorithmType, ExchangeAlgorithmType exchangeAlgorithmType, bool exportable, bool blockMode, byte keyMaterialSize, byte expandedKeyMaterialSize, short effectiveKeyBytes, byte ivSize, byte blockSize) : base(code, name, cipherAlgorithmType, hashAlgorithmType, exchangeAlgorithmType, exportable, blockMode, keyMaterialSize, expandedKeyMaterialSize, effectiveKeyBytes, ivSize, blockSize) { int padLength = (hashAlgorithmType == HashAlgorithmType.Md5) ? 48 : 40; // Fill pad arrays this.pad1 = new byte[padLength]; this.pad2 = new byte[padLength]; /* Pad the key for inner and outer digest */ for (int i = 0; i < padLength; ++i) { this.pad1[i] = 0x36; this.pad2[i] = 0x5C; } }
public CipherSuite Add( short code, string name, CipherAlgorithmType cipherType, HashAlgorithmType hashType, ExchangeAlgorithmType exchangeType, bool exportable, bool blockMode, byte keyMaterialSize, byte expandedKeyMaterialSize, short effectiveKeyBytes, byte ivSize, byte blockSize) { switch (this.protocol) { case SecurityProtocolType.Default: case SecurityProtocolType.Tls: return this.add( new TlsCipherSuite( code, name, cipherType, hashType, exchangeType, exportable, blockMode, keyMaterialSize, expandedKeyMaterialSize, effectiveKeyBytes, ivSize, blockSize)); case SecurityProtocolType.Ssl3: return this.add( new SslCipherSuite( code, name, cipherType, hashType, exchangeType, exportable, blockMode, keyMaterialSize, expandedKeyMaterialSize, effectiveKeyBytes, ivSize, blockSize)); case SecurityProtocolType.Ssl2: default: throw new NotSupportedException("Unsupported security protocol type."); } }
public static IJasilyHashAlgorithmProvider CreateHash(HashAlgorithmType algorithmType) => new UAPHashAlgorithmProvider( HashAlgorithmProvider.OpenAlgorithm( ConvertToHashAlgorithmName(algorithmType)));
public static IJasilyHashAlgorithmProvider CreateHash(HashAlgorithmType hashAlgorithm) { throw new NotSupportedException(); }
private void Initialize() { if (this.ptr == IntPtr.Zero || isInitialized) { return; } isInitialized = true; // marshal the structure raw = (SSL_CIPHER)Marshal.PtrToStructure(ptr, typeof(SSL_CIPHER)); // start picking the data out bool isExport = IsExport(raw.algo_strength); int privateKeyLength = ExportPrivateKeyLength(raw.algo_strength); int keyLength = ExportKeyLength(raw.algorithms, raw.algo_strength); // Get the SSL Protocol version if ((raw.algorithms & SSL_SSLV2) == SSL_SSLV2) { sslProtocol = SslProtocols.Ssl2; } else if ((raw.algorithms & SSL_SSLV3) == SSL_SSLV3) { sslProtocol = SslProtocols.Tls; // SSL3 & TLS are the same here... } // set the keyExchange strength keyExchangeStrength = privateKeyLength; // Get the Key Exchange cipher and strength switch (raw.algorithms & SSL_MKEY_MASK) { case SSL_kRSA: keyExchangeAlgorithm = ExchangeAlgorithmType.RsaKeyX; break; case SSL_kDHr: case SSL_kDHd: case SSL_kEDH: keyExchangeAlgorithm = ExchangeAlgorithmType.DiffieHellman; break; case SSL_kKRB5: /* VRS */ case SSL_KRB5: /* VRS */ keyExchangeAlgorithm = ExchangeAlgorithmType.Kerberos; break; case SSL_kFZA: keyExchangeAlgorithm = ExchangeAlgorithmType.Fortezza; break; case SSL_kECDH: case SSL_kECDHE: keyExchangeAlgorithm = ExchangeAlgorithmType.ECDiffieHellman; break; } // Get the authentication method switch (raw.algorithms & SSL_AUTH_MASK) { case SSL_aRSA: authMethod = AuthenticationMethod.Rsa; break; case SSL_aDSS: authMethod = AuthenticationMethod.Dss; break; case SSL_aDH: authMethod = AuthenticationMethod.DiffieHellman; break; case SSL_aKRB5: /* VRS */ case SSL_KRB5: /* VRS */ authMethod = AuthenticationMethod.Kerberos; break; case SSL_aFZA: case SSL_aNULL: authMethod = AuthenticationMethod.None; break; case SSL_aECDSA: authMethod = AuthenticationMethod.ECDsa; break; } // Get the symmetric encryption cipher info switch (raw.algorithms & SSL_ENC_MASK) { case SSL_DES: cipherAlgorithm = CipherAlgorithmType.Des; if (isExport && keyLength == 5) { cipherStrength = 40; } else { cipherStrength = 56; } break; case SSL_3DES: cipherAlgorithm = CipherAlgorithmType.TripleDes; cipherStrength = 168; break; case SSL_RC4: cipherAlgorithm = CipherAlgorithmType.Rc4; if (isExport) { if (keyLength == 5) { cipherStrength = 40; } else { cipherStrength = 56; } } else { if ((raw.algorithm2 & SSL2_CF_8_BYTE_ENC) == SSL2_CF_8_BYTE_ENC) { cipherStrength = 64; } else { cipherStrength = 128; } } break; case SSL_RC2: cipherAlgorithm = CipherAlgorithmType.Rc2; if (isExport) { if (keyLength == 5) { cipherStrength = 40; } else { cipherStrength = 56; } } else { cipherStrength = 128; } break; case SSL_IDEA: cipherAlgorithm = CipherAlgorithmType.Idea; cipherStrength = 128; break; case SSL_eFZA: cipherAlgorithm = CipherAlgorithmType.Fortezza; break; case SSL_eNULL: cipherAlgorithm = CipherAlgorithmType.None; break; case SSL_AES: switch (raw.strength_bits) { case 128: cipherAlgorithm = CipherAlgorithmType.Aes128; break; case 192: cipherAlgorithm = CipherAlgorithmType.Aes192; break; case 256: cipherAlgorithm = CipherAlgorithmType.Aes256; break; } break; case SSL_CAMELLIA: switch (raw.strength_bits) { case 128: cipherAlgorithm = CipherAlgorithmType.Camellia128; break; case 256: cipherAlgorithm = CipherAlgorithmType.Camellia256; break; } break; case SSL_SEED: cipherAlgorithm = CipherAlgorithmType.Seed; cipherStrength = 128; break; } // Get the MAC info switch (raw.algorithms & SSL_MAC_MASK) { case SSL_MD5: hashAlgorithm = HashAlgorithmType.Md5; break; case SSL_SHA1: hashAlgorithm = HashAlgorithmType.Sha1; break; default: hashAlgorithm = HashAlgorithmType.None; break; } }
/// <summary> /// 返回指定加密哈希算法的字符串的副本 /// </summary> /// <param name="s"></param> /// <param name="hashAlgorithm">哈希算法</param> /// <returns></returns> public static string ToHash(string s, HashAlgorithmType hashAlgorithm) { return HashCryto.GetHash2String(s, hashAlgorithm); }