public byte[] New() { return(_system.ComputeHash(_bytes)); }
public void TestSerializeAndDeserializeConsensusContext() { var consensusContext = new ConsensusContext(null, null); consensusContext.PrevHash = UInt256.Parse("0xaa8e1b1c619467a6500cbca4425f76512d1bd0ba2e0aee7e5fd15169325db52e"); consensusContext.BlockIndex = 1; consensusContext.ViewNumber = 2; consensusContext.Validators = new ECPoint[7] { ECPoint.Parse("02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70", Krona.Cryptography.ECC.ECCurve.Secp256r1), ECPoint.Parse("024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d", Krona.Cryptography.ECC.ECCurve.Secp256r1), ECPoint.Parse("02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e", Krona.Cryptography.ECC.ECCurve.Secp256r1), ECPoint.Parse("02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554", Krona.Cryptography.ECC.ECCurve.Secp256r1), ECPoint.Parse("02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093", Krona.Cryptography.ECC.ECCurve.Secp256r1), ECPoint.Parse("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c", Krona.Cryptography.ECC.ECCurve.Secp256r1), ECPoint.Parse("03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a", Krona.Cryptography.ECC.ECCurve.Secp256r1) }; consensusContext.MyIndex = -1; consensusContext.PrimaryIndex = 6; consensusContext.Timestamp = 4244941711; consensusContext.Nonce = UInt64.MaxValue; consensusContext.NextConsensus = UInt160.Parse("5555AAAA5555AAAA5555AAAA5555AAAA5555AAAA"); var testTx1 = TestUtils.CreateRandomHashInvocationMockTransaction().Object; var testTx2 = TestUtils.CreateRandomHashInvocationMockTransaction().Object; int txCountToInlcude = 256; consensusContext.TransactionHashes = new UInt256[txCountToInlcude]; Transaction[] txs = new Transaction[txCountToInlcude]; txs[0] = TestUtils.CreateRandomMockBlockReward().Object; consensusContext.TransactionHashes[0] = txs[0].Hash; for (int i = 1; i < txCountToInlcude; i++) { txs[i] = TestUtils.CreateRandomHashInvocationMockTransaction().Object; consensusContext.TransactionHashes[i] = txs[i].Hash; } // consensusContext.TransactionHashes = new UInt256[2] {testTx1.Hash, testTx2.Hash}; consensusContext.Transactions = txs.ToDictionary(p => p.Hash); consensusContext.PreparationPayloads = new ConsensusPayload[consensusContext.Validators.Length]; var prepareRequestMessage = new PrepareRequest { Nonce = consensusContext.Nonce, NextConsensus = consensusContext.NextConsensus, TransactionHashes = consensusContext.TransactionHashes, BlockReward = (BlockReward)consensusContext.Transactions[consensusContext.TransactionHashes[0]], Timestamp = 23, StateRootSignature = new byte[64] }; consensusContext.PreparationPayloads[6] = MakeSignedPayload(consensusContext, prepareRequestMessage, 6, new[] { (byte)'3', (byte)'!' }); consensusContext.PreparationPayloads[0] = MakeSignedPayload(consensusContext, new PrepareResponse { PreparationHash = consensusContext.PreparationPayloads[6].Hash, StateRootSignature = new byte[64] }, 0, new[] { (byte)'t', (byte)'e' }); consensusContext.PreparationPayloads[1] = MakeSignedPayload(consensusContext, new PrepareResponse { PreparationHash = consensusContext.PreparationPayloads[6].Hash, StateRootSignature = new byte[64] }, 1, new[] { (byte)'s', (byte)'t' }); consensusContext.PreparationPayloads[2] = null; consensusContext.PreparationPayloads[3] = MakeSignedPayload(consensusContext, new PrepareResponse { PreparationHash = consensusContext.PreparationPayloads[6].Hash, StateRootSignature = new byte[64] }, 3, new[] { (byte)'1', (byte)'2' }); consensusContext.PreparationPayloads[4] = null; consensusContext.PreparationPayloads[5] = null; consensusContext.CommitPayloads = new ConsensusPayload[consensusContext.Validators.Length]; using (SHA256 sha256 = SHA256.Create()) { consensusContext.CommitPayloads[3] = MakeSignedPayload(consensusContext, new Commit { Signature = sha256.ComputeHash(testTx1.Hash.ToArray()) }, 3, new[] { (byte)'3', (byte)'4' }); consensusContext.CommitPayloads[6] = MakeSignedPayload(consensusContext, new Commit { Signature = sha256.ComputeHash(testTx2.Hash.ToArray()) }, 3, new[] { (byte)'6', (byte)'7' }); } consensusContext.Timestamp = TimeProvider.Current.UtcNow.ToTimestamp(); consensusContext.ChangeViewPayloads = new ConsensusPayload[consensusContext.Validators.Length]; consensusContext.ChangeViewPayloads[0] = MakeSignedPayload(consensusContext, new ChangeView { ViewNumber = 1, Timestamp = 6 }, 0, new[] { (byte)'A' }); consensusContext.ChangeViewPayloads[1] = MakeSignedPayload(consensusContext, new ChangeView { ViewNumber = 1, Timestamp = 5 }, 1, new[] { (byte)'B' }); consensusContext.ChangeViewPayloads[2] = null; consensusContext.ChangeViewPayloads[3] = MakeSignedPayload(consensusContext, new ChangeView { ViewNumber = 1, Timestamp = uint.MaxValue }, 3, new[] { (byte)'C' }); consensusContext.ChangeViewPayloads[4] = null; consensusContext.ChangeViewPayloads[5] = null; consensusContext.ChangeViewPayloads[6] = MakeSignedPayload(consensusContext, new ChangeView { ViewNumber = 1, Timestamp = 1 }, 6, new[] { (byte)'D' }); consensusContext.LastChangeViewPayloads = new ConsensusPayload[consensusContext.Validators.Length]; var copiedContext = TestUtils.CopyMsgBySerialization(consensusContext, new ConsensusContext(null, null)); copiedContext.PrevHash.Should().Be(consensusContext.PrevHash); copiedContext.BlockIndex.Should().Be(consensusContext.BlockIndex); copiedContext.ViewNumber.Should().Be(consensusContext.ViewNumber); copiedContext.Validators.ShouldAllBeEquivalentTo(consensusContext.Validators); copiedContext.MyIndex.Should().Be(consensusContext.MyIndex); copiedContext.PrimaryIndex.Should().Be(consensusContext.PrimaryIndex); copiedContext.Timestamp.Should().Be(consensusContext.Timestamp); copiedContext.Nonce.Should().Be(consensusContext.Nonce); copiedContext.NextConsensus.Should().Be(consensusContext.NextConsensus); copiedContext.TransactionHashes.ShouldAllBeEquivalentTo(consensusContext.TransactionHashes); copiedContext.Transactions.ShouldAllBeEquivalentTo(consensusContext.Transactions); copiedContext.Transactions.Values.ShouldAllBeEquivalentTo(consensusContext.Transactions.Values); copiedContext.PreparationPayloads.ShouldAllBeEquivalentTo(consensusContext.PreparationPayloads); copiedContext.CommitPayloads.ShouldAllBeEquivalentTo(consensusContext.CommitPayloads); copiedContext.ChangeViewPayloads.ShouldAllBeEquivalentTo(consensusContext.ChangeViewPayloads); }
public List <User> LoginUser(User user) { List <User> listUser = new List <User>(); ExceptionHandling e = new ExceptionHandling(); // Create StringBuilded (Mutable char string) to append bytes of hashed password to // (Did not use String because they are not mutable) // Create empty salt string to store salt from User table for matched username StringBuilder hashed = new StringBuilder(); string salt = ""; string dbConnection = System.Configuration.ConfigurationManager.ConnectionStrings["dbConnection"].ConnectionString; try { // Get users Salt by entered Username using (SqlConnection conn = new SqlConnection(dbConnection)) { using (SqlCommand command = new SqlCommand("SP_SELECT_USERS_SALT", conn)) { command.CommandType = System.Data.CommandType.StoredProcedure; command.CommandTimeout = 30; conn.Open(); command.Parameters.AddWithValue("@parmUserName", SqlDbType.VarChar).Value = user.UserName; using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { User u = new User(); u.Salt = reader["Salt"].ToString(); salt = u.Salt; } } } conn.Close(); } // Once salt is recieved add it to User Password and hash it string saltAndPassword = user.UserPassword + salt; // Take salted password then Hash with SHA256 using (SHA256 sha256Hash = SHA256.Create()) { // ComputeHash - returns byte array byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(saltAndPassword)); // Convert byte array to a string for (int i = 0; i < bytes.Length; i++) { hashed.Append(bytes[i].ToString("x2"));// x2 is a string formatter. Prints two hexadecimal digits } hashed.ToString(); } using (SqlConnection conn = new SqlConnection(dbConnection)) { using (SqlCommand command = new SqlCommand("SP_SELECT_USER", conn)) { command.CommandType = System.Data.CommandType.StoredProcedure; command.CommandTimeout = 30; conn.Open(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { User u = new User(); u.UserID = (int)reader["UserID"]; u.FirstName = reader["FirstName"].ToString(); u.LastName = reader["LastName"].ToString(); u.UserName = reader["UserName"].ToString(); u.UserPassword = reader["UserPassword"].ToString(); u.Salt = reader["Salt"].ToString(); u.Email = reader["Email"].ToString(); u.RoleIDFK = (int)reader["RoleIDFK"]; if (reader["SavedDirtbikeIDFK"] != DBNull.Value) { u.SavedDirtbikeIDFK = (int)reader["SavedDirtbikeIDFK"]; } else { } listUser.Add(u); } } } conn.Close(); } } catch (Exception ex) { e.WriteLogger(ex); e.InsertLoggerToDB(ex); } // Find match of user input from list return(listUser.Where(singleuser => singleuser.UserName == user.UserName && singleuser.UserPassword == hashed.ToString()).ToList()); }
public static byte[] ComputeDoubleHash(this SHA256 sha256, byte[] buffer) { return(sha256.ComputeHash(sha256.ComputeHash(buffer))); }
private int[] EntropyHexToWordValues(String entropyHex) { // Convert entropy length from nibbles to bits int entropyLength = entropyHex.Length * 4; // Entropy length in bytes int entropyLengthBytes = entropyLength / 8; // BIP-0039 says entropy must be divisible by 32 bits (8 nibbles) if (entropyLength % 32 > 0) { throw new ArgumentException("Length of hexadecimal representation of mnemonic must be a multiple of 32 bits.", entropyHex); } // The number of checksum bits needed (makes length divisible by 11) int checksumLength = entropyLength / 32; // A byte array to store the entropy byte[] entropyBytes = new byte[entropyLengthBytes]; // Convert each 2-nibble byte from hex string to bytes for (int currentByte = 0; currentByte < entropyLengthBytes; currentByte++) { entropyBytes[currentByte] = Convert.ToByte(entropyHex.Substring(currentByte * 2, 2), 16); } // Create a SHA256 instance SHA256 sha256 = SHA256.Create(); // Calculate and store the checksum hash bytes byte[] checksumBytes = sha256.ComputeHash(entropyBytes); // An integer array to store the 11-bit BIP-39 word values int[] wordlistValues = new int[(entropyLength + checksumLength) / 11]; // Track where we are in the entropy byte array int currentEntropyByte = 0; // Track where we are in the current entropy byte int currentEntropyBit = 0; // Track where we are in the checksum byte array int currentChecksumByte = 0; // Track where we are in the current checksum byte int currentChecksumBit = 0; // Populate the BIP-39 word value array for (int currentWord = 0; currentWord < wordlistValues.Length; currentWord++) { // Clear the value of the new word wordlistValues[currentWord] = 0; // Fill the bits of the word for (int i = 0; i < 11; i++) { // Check if this bit can come from the entropy bytes if ((currentWord * 11 + i) < entropyLength) { // If the current bit should be a 1, make it a 1 if ((entropyBytes[currentEntropyByte] & (1 << (7 - currentEntropyBit))) != 0) { wordlistValues[currentWord] |= 1 << (10 - i); } // Move to next bit in the current byte currentEntropyBit++; // Move to next byte if there are no bits left in the current byte if (currentEntropyBit % 8 == 0) { currentEntropyByte++; currentEntropyBit = 0; } } else { // If the current bit should be a 1, make it a 1 if ((checksumBytes[currentChecksumByte] & (1 << (7 - currentChecksumBit))) != 0) { wordlistValues[currentWord] |= 1 << (10 - i); } // Move to next bit in the current byte currentChecksumBit++; // Move to next byte if there are no bits left in the current byte if (currentChecksumBit % 8 == 0) { currentChecksumByte++; currentChecksumBit = 0; } } } } Array.Clear(entropyBytes, 0, entropyBytes.Length); Array.Clear(checksumBytes, 0, checksumBytes.Length); return(wordlistValues); }
/// <summary> /// Hash email address using SHA-256 hashing algorithm. /// </summary> /// <param name="digest">Provides the algorithm for SHA-256.</param> /// <param name="email">The email address to hash.</param> /// <returns>Hash email address using SHA-256 hashing algorithm.</returns> private static string ToSha256String(SHA256 digest, string email) { byte[] digestBytes = digest.ComputeHash(Encoding.UTF8.GetBytes(email)); // Convert the byte array into an unhyphenated hexadecimal string. return(BitConverter.ToString(digestBytes).Replace("-", string.Empty)); }
/// <summary> /// Compute sha256 checksum. /// </summary> /// <param name="body">Bytes body</param> /// <returns>Bytes of sha256 checksum</returns> private byte[] ComputeSha256(byte[] body) { SHA256 sha256 = System.Security.Cryptography.SHA256.Create(); return(sha256.ComputeHash(body)); }
public void CalculateX(string accountName, string password, bool calcB) { I = sha256.ComputeHash(Encoding.UTF8.GetBytes(accountName)); var p = sha256.ComputeHash(Encoding.UTF8.GetBytes(I.ToHexString() + ":" + password.ToUpper())); var x = sha256.ComputeHash(S.Combine(p)).MakeBigInteger(); CalculateV(x, calcB); }
/// <summary> /// Send (resend) the ClientKeyExchange flight /// </summary> /// <param name="isRetransmit"> /// True if this is a retransmit of the flight. Otherwise, /// false /// </param> private void SendClientKeyExchangeFlight(bool isRetransmit) { // Describe our flight Handshake keyExchangeHandshake = new Handshake(); keyExchangeHandshake.MessageType = HandshakeType.ClientKeyExchange; keyExchangeHandshake.Length = (ushort)this.nextEpoch.Handshake.CalculateClientMessageSize(); keyExchangeHandshake.MessageSequence = 5; keyExchangeHandshake.FragmentOffset = 0; keyExchangeHandshake.FragmentLength = keyExchangeHandshake.Length; Record keyExchangeRecord = new Record(); keyExchangeRecord.ContentType = ContentType.Handshake; keyExchangeRecord.Epoch = this.epoch; keyExchangeRecord.SequenceNumber = this.currentEpoch.NextOutgoingSequence; keyExchangeRecord.Length = (ushort)this.currentEpoch.RecordProtection.GetEncryptedSize(Handshake.Size + (int)keyExchangeHandshake.Length); ++this.currentEpoch.NextOutgoingSequence; Record changeCipherSpecRecord = new Record(); changeCipherSpecRecord.ContentType = ContentType.ChangeCipherSpec; changeCipherSpecRecord.Epoch = this.epoch; changeCipherSpecRecord.SequenceNumber = this.currentEpoch.NextOutgoingSequence; changeCipherSpecRecord.Length = (ushort)this.currentEpoch.RecordProtection.GetEncryptedSize(ChangeCipherSpec.Size); ++this.currentEpoch.NextOutgoingSequence; Handshake finishedHandshake = new Handshake(); finishedHandshake.MessageType = HandshakeType.Finished; finishedHandshake.Length = Finished.Size; finishedHandshake.MessageSequence = 6; finishedHandshake.FragmentOffset = 0; finishedHandshake.FragmentLength = finishedHandshake.Length; Record finishedRecord = new Record(); finishedRecord.ContentType = ContentType.Handshake; finishedRecord.Epoch = this.nextEpoch.Epoch; finishedRecord.SequenceNumber = this.nextEpoch.NextOutgoingSequence; finishedRecord.Length = (ushort)this.nextEpoch.RecordProtection.GetEncryptedSize(Handshake.Size + (int)finishedHandshake.Length); ++this.nextEpoch.NextOutgoingSequence; // Encode flight to wire format int packetLength = 0 + Record.Size + keyExchangeRecord.Length + Record.Size + changeCipherSpecRecord.Length + Record.Size + finishedRecord.Length; ; ByteSpan packet = new byte[packetLength]; ByteSpan writer = packet; keyExchangeRecord.Encode(writer); writer = writer.Slice(Record.Size); keyExchangeHandshake.Encode(writer); writer = writer.Slice(Handshake.Size); this.nextEpoch.Handshake.EncodeClientKeyExchangeMessage(writer); ByteSpan startOfChangeCipherSpecRecord = packet.Slice(Record.Size + keyExchangeRecord.Length); writer = startOfChangeCipherSpecRecord; changeCipherSpecRecord.Encode(writer); writer = writer.Slice(Record.Size); ChangeCipherSpec.Encode(writer); writer = writer.Slice(ChangeCipherSpec.Size); ByteSpan startOfFinishedRecord = startOfChangeCipherSpecRecord.Slice(Record.Size + changeCipherSpecRecord.Length); writer = startOfFinishedRecord; finishedRecord.Encode(writer); writer = writer.Slice(Record.Size); finishedHandshake.Encode(writer); writer = writer.Slice(Handshake.Size); // Interject here to writer our client key exchange // message into the verification stream if (!isRetransmit) { this.nextEpoch.VerificationStream.Write( packet.GetUnderlyingArray() , Record.Size , Handshake.Size + (int)keyExchangeHandshake.Length ); } // Calculate the hash of the verification stream ByteSpan handshakeHash; using (SHA256 sha256 = SHA256.Create()) { this.nextEpoch.VerificationStream.Position = 0; handshakeHash = sha256.ComputeHash(this.nextEpoch.VerificationStream); } // Expand our master secret into Finished digests for the client and server PrfSha256.ExpandSecret( this.nextEpoch.ServerVerification , this.nextEpoch.MasterSecret , PrfLabel.SERVER_FINISHED , handshakeHash ); PrfSha256.ExpandSecret( writer.Slice(0, Finished.Size) , this.nextEpoch.MasterSecret , PrfLabel.CLIENT_FINISHED , handshakeHash ); writer = writer.Slice(Finished.Size); // Protect the ClientKeyExchange record this.currentEpoch.RecordProtection.EncryptClientPlaintext( packet.Slice(Record.Size, keyExchangeRecord.Length) , packet.Slice(Record.Size, Handshake.Size + (int)keyExchangeHandshake.Length) , ref keyExchangeRecord ); // Protect the ChangeCipherSpec record this.currentEpoch.RecordProtection.EncryptClientPlaintext( startOfChangeCipherSpecRecord.Slice(Record.Size, changeCipherSpecRecord.Length) , startOfChangeCipherSpecRecord.Slice(Record.Size, ChangeCipherSpec.Size) , ref changeCipherSpecRecord ); // Protect the Finished record this.nextEpoch.RecordProtection.EncryptClientPlaintext( startOfFinishedRecord.Slice(Record.Size, finishedRecord.Length) , startOfFinishedRecord.Slice(Record.Size, Handshake.Size + (int)finishedHandshake.Length) , ref finishedRecord ); this.nextEpoch.State = HandshakeState.ExpectingChangeCipherSpec; this.nextEpoch.NextPacketResendTime = DateTime.UtcNow + this.handshakeResendTimeout; base.WriteBytesToConnection(packet.GetUnderlyingArray(), packet.Length); }
/// <summary> /// Validate Id token obetained for OpenId flow /// </summary> /// <param name="id_token"></param> /// <returns></returns> private System.Threading.Tasks.Task <bool> isIdTokenValid(string id_token) { output("Making IsIdToken Valid Call."); string idToken = id_token; if (keys != null) { //Get mod and exponent value foreach (var key in keys) { if (key.N != null) { //Mod mod = key.N; } if (key.N != null) { //Exponent expo = key.E; } } //IdentityToken if (idToken != null) { //Split the identityToken to get Header and Payload string[] splitValues = idToken.Split('.'); if (splitValues[0] != null) { //Decode header var headerJson = Encoding.UTF8.GetString(Base64Url.Decode(splitValues[0].ToString())); //Deserilaize headerData IdTokenHeader headerData = JsonConvert.DeserializeObject <IdTokenHeader>(headerJson); //Verify if the key id of the key used to sign the payload is not null if (headerData.Kid == null) { return(System.Threading.Tasks.Task.FromResult(false)); } //Verify if the hashing alg used to sign the payload is not null if (headerData.Alg == null) { return(System.Threading.Tasks.Task.FromResult(false)); } } if (splitValues[1] != null) { //Decode payload var payloadJson = Encoding.UTF8.GetString(Base64Url.Decode(splitValues[1].ToString())); IdTokenJWTClaimTypes payloadData = JsonConvert.DeserializeObject <IdTokenJWTClaimTypes>(payloadJson); //Verify Aud matches ClientId if (payloadData.Aud != null) { if (payloadData.Aud[0].ToString() != clientID) { return(System.Threading.Tasks.Task.FromResult(false)); } } else { return(System.Threading.Tasks.Task.FromResult(false)); } //Verify Authtime matches the time the ID token was authorized. if (payloadData.Auth_time == null) { return(System.Threading.Tasks.Task.FromResult(false)); } //Verify exp matches the time the ID token expires, represented in Unix time (integer seconds). if (payloadData.Exp != null) { long expiration = Convert.ToInt64(payloadData.Exp); long currentEpochTime = EpochTimeExtensions.ToEpochTime(DateTime.UtcNow); //Verify the ID expiration time with what expiry time you have calculated and saved in your application //If they are equal then it means IdToken has expired if ((expiration - currentEpochTime) <= 0) { return(System.Threading.Tasks.Task.FromResult(false)); } } //Verify Iat matches the time the ID token was issued, represented in Unix time (integer seconds). if (payloadData.Iat == null) { return(System.Threading.Tasks.Task.FromResult(false)); } //verify Iss matches the issuer identifier for the issuer of the response. if (payloadData.Iss != null) { if (payloadData.Iss.ToString() != issuerUrl) { return(System.Threading.Tasks.Task.FromResult(false)); } } else { return(System.Threading.Tasks.Task.FromResult(false)); } //Verify sub. Sub is an identifier for the user, unique among all Intuit accounts and never reused. //An Intuit account can have multiple emails at different points in time, but the sub value is never changed. //Use sub within your application as the unique-identifier key for the user. if (payloadData.Sub == null) { return(System.Threading.Tasks.Task.FromResult(false)); } } //Use external lib to decode mod and expo value and generte hashes RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); //Read values of n and e from discovery document. rsa.ImportParameters( new RSAParameters() { //Read values from discovery document Modulus = Base64Url.Decode(mod), Exponent = Base64Url.Decode(expo) }); //Verify Siganture hash matches the signed concatenation of the encoded header and the encoded payload with the specified algorithm SHA256 sha256 = SHA256.Create(); byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(splitValues[0] + '.' + splitValues[1])); RSAPKCS1SignatureDeformatter rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa); rsaDeformatter.SetHashAlgorithm("SHA256"); if (rsaDeformatter.VerifySignature(hash, Base64Url.Decode(splitValues[2]))) { //identityToken is valid return(System.Threading.Tasks.Task.FromResult(true)); } else { //identityToken is not valid return(System.Threading.Tasks.Task.FromResult(false)); } } else { //identityToken is not valid return(System.Threading.Tasks.Task.FromResult(false)); } } else { //Missing mod and expo values return(System.Threading.Tasks.Task.FromResult(false)); } }
public string DoSHA256(string input) => ByteUtils.ByteToHexBitFiddle(sha256.ComputeHash(Encoding.UTF8.GetBytes(input)));
public void TestSrpProtocol() { // Choose hash algorithm, g, N, username, password, salt SHA256 sha256 = SHA256.Create(); BigInteger g = AuthenticationHelper.g; BigInteger N = AuthenticationHelper.N; string password = "******"; string saltString = "fef2871d83ce2120f9c47a46db303d37"; //Does not have to always be this string BigInteger salt = BigIntegerExtensions.FromUnsignedLittleEndianHex(saltString); // Compute x = H(s,p) byte[] passBytes = Encoding.UTF8.GetBytes(password); byte[] userIdHash = sha256.ComputeHash(passBytes); byte[] saltBytes = salt.ToByteArray(); byte[] xBytes = new byte[saltBytes.Length + userIdHash.Length]; Buffer.BlockCopy(saltBytes, 0, xBytes, 0, saltBytes.Length); Buffer.BlockCopy(userIdHash, 0, xBytes, saltBytes.Length, userIdHash.Length); byte[] xDigest = sha256.ComputeHash(xBytes); BigInteger x = BigIntegerExtensions.FromUnsignedBigEndian(xDigest); // Compute v = g^x BigInteger v = BigInteger.ModPow(g, x, N); // Generate random a, b, A BigInteger a, b, A; do { a = AuthenticationHelper.CreateBigIntegerRandom(); b = AuthenticationHelper.CreateBigIntegerRandom(); A = BigInteger.ModPow(g, a, N); } while ((A.TrueMod(N)).Equals(BigInteger.Zero)); // Calculate k = H(N, g) byte[] nBytes = N.ToByteArray(); byte[] gBytes = g.ToByteArray(); byte[] content = new byte[nBytes.Length + gBytes.Length]; Buffer.BlockCopy(nBytes, 0, content, 0, nBytes.Length); Buffer.BlockCopy(gBytes, 0, content, nBytes.Length, gBytes.Length); byte[] digest = sha256.ComputeHash(content); BigInteger k = BigIntegerExtensions.FromUnsignedBigEndian(digest); //Calculate B = kv + g^b BigInteger B = k * v + (BigInteger.ModPow(g, b, N)); // Calculate u = H(A,B) byte[] ABytes = A.ToByteArray(); byte[] BBytes = B.ToByteArray(); byte[] ABcat = new byte[ABytes.Length + BBytes.Length]; Buffer.BlockCopy(ABytes, 0, ABcat, 0, ABytes.Length); Buffer.BlockCopy(BBytes, 0, ABcat, ABytes.Length, BBytes.Length); byte[] ABdigest = sha256.ComputeHash(ABcat); BigInteger u = BigIntegerExtensions.FromUnsignedBigEndian(ABdigest); // Calculate user side userS = (B - kg^x) ^ (a + ux) BigInteger userS = BigInteger.ModPow((B - k * BigInteger.ModPow(g, x, N)), a + u * x, N); // Calculate user side userK = H(userS) byte[] userSBytes = userS.ToByteArray(); byte[] userSDigest = sha256.ComputeHash(userSBytes); BigInteger userK = BigIntegerExtensions.FromUnsignedBigEndian(userSDigest); // Calculate host side hostS = (Av^u) ^ b BigInteger hostS = BigInteger.ModPow((A * BigInteger.ModPow(v, u, N)), b, N); // Calculate host side hostK = H(hostS) byte[] hostSBytes = hostS.ToByteArray(); byte[] hostSDigest = sha256.ComputeHash(hostSBytes); BigInteger hostK = BigIntegerExtensions.FromUnsignedBigEndian(hostSDigest); Assert.Equal(hostS, userS); Assert.Equal(hostK, userK); }
private void ExecuteOp(OpCode opcode, ExecutionContext context) { lastOpcode = opcode; if (opcode > OpCode.PUSH16 && opcode != OpCode.RET && context.PushOnly) { State |= VMState.FAULT; return; } if (opcode >= OpCode.PUSHBYTES1 && opcode <= OpCode.PUSHBYTES75) { EvaluationStack.Push(context.OpReader.ReadBytes((byte)opcode)); } else { switch (opcode) { // Push value case OpCode.PUSH0: EvaluationStack.Push(new byte[0]); break; case OpCode.PUSHDATA1: EvaluationStack.Push(context.OpReader.ReadBytes(context.OpReader.ReadByte())); break; case OpCode.PUSHDATA2: EvaluationStack.Push(context.OpReader.ReadBytes(context.OpReader.ReadUInt16())); break; case OpCode.PUSHDATA4: EvaluationStack.Push(context.OpReader.ReadBytes(context.OpReader.ReadInt32())); break; case OpCode.PUSHM1: case OpCode.PUSH1: case OpCode.PUSH2: case OpCode.PUSH3: case OpCode.PUSH4: case OpCode.PUSH5: case OpCode.PUSH6: case OpCode.PUSH7: case OpCode.PUSH8: case OpCode.PUSH9: case OpCode.PUSH10: case OpCode.PUSH11: case OpCode.PUSH12: case OpCode.PUSH13: case OpCode.PUSH14: case OpCode.PUSH15: case OpCode.PUSH16: EvaluationStack.Push((int)opcode - (int)OpCode.PUSH1 + 1); break; // Control case OpCode.NOP: break; case OpCode.JMP: case OpCode.JMPIF: case OpCode.JMPIFNOT: { int offset = context.OpReader.ReadInt16(); offset = context.InstructionPointer + offset - 3; if (offset < 0 || offset > context.Script.Length) { State |= VMState.FAULT; return; } bool fValue = true; if (opcode > OpCode.JMP) { fValue = EvaluationStack.Pop().GetBoolean(); if (opcode == OpCode.JMPIFNOT) { fValue = !fValue; } } if (fValue) { context.InstructionPointer = offset; } } break; case OpCode.CALL: InvocationStack.Push(context.Clone()); context.InstructionPointer += 2; ExecuteOp(OpCode.JMP, CurrentContext); break; case OpCode.RET: InvocationStack.Pop().Dispose(); if (InvocationStack.Count == 0) { State |= VMState.HALT; } break; case OpCode.APPCALL: case OpCode.TAILCALL: { if (table == null) { State |= VMState.FAULT; return; } byte[] script_hash = context.OpReader.ReadBytes(20); Console.WriteLine($"ExecuteOp: script_hash {script_hash.ToHexString()}"); if (script_hash.All(p => p == 0)) { script_hash = EvaluationStack.Pop().GetByteArray(); } Console.WriteLine($"ExecuteOp: script_hash {script_hash.ToHexString()}"); byte[] script = table.GetScript(script_hash); if (script == null) { State |= VMState.FAULT; return; } if (opcode == OpCode.TAILCALL) { InvocationStack.Pop().Dispose(); } LoadScript(script); } break; case OpCode.SYSCALL: lastSysCall = Encoding.ASCII.GetString(context.OpReader.ReadVarBytes(252)); if (!service.Invoke(lastSysCall, this)) { State |= VMState.FAULT; } break; // Stack ops case OpCode.DUPFROMALTSTACK: EvaluationStack.Push(AltStack.Peek()); break; case OpCode.TOALTSTACK: AltStack.Push(EvaluationStack.Pop()); break; case OpCode.FROMALTSTACK: EvaluationStack.Push(AltStack.Pop()); break; case OpCode.XDROP: { int n = (int)EvaluationStack.Pop().GetBigInteger(); if (n < 0) { State |= VMState.FAULT; return; } EvaluationStack.Remove(n); } break; case OpCode.XSWAP: { int n = (int)EvaluationStack.Pop().GetBigInteger(); if (n < 0) { State |= VMState.FAULT; return; } if (n == 0) { break; } StackItem xn = EvaluationStack.Peek(n); EvaluationStack.Set(n, EvaluationStack.Peek()); EvaluationStack.Set(0, xn); } break; case OpCode.XTUCK: { int n = (int)EvaluationStack.Pop().GetBigInteger(); if (n <= 0) { State |= VMState.FAULT; return; } EvaluationStack.Insert(n, EvaluationStack.Peek()); } break; case OpCode.DEPTH: EvaluationStack.Push(EvaluationStack.Count); break; case OpCode.DROP: EvaluationStack.Pop(); break; case OpCode.DUP: EvaluationStack.Push(EvaluationStack.Peek()); break; case OpCode.NIP: { StackItem x2 = EvaluationStack.Pop(); EvaluationStack.Pop(); EvaluationStack.Push(x2); } break; case OpCode.OVER: { StackItem x2 = EvaluationStack.Pop(); StackItem x1 = EvaluationStack.Peek(); EvaluationStack.Push(x2); EvaluationStack.Push(x1); } break; case OpCode.PICK: { int n = (int)EvaluationStack.Pop().GetBigInteger(); if (n < 0) { State |= VMState.FAULT; return; } EvaluationStack.Push(EvaluationStack.Peek(n)); } break; case OpCode.ROLL: { int n = (int)EvaluationStack.Pop().GetBigInteger(); if (n < 0) { State |= VMState.FAULT; return; } if (n == 0) { break; } EvaluationStack.Push(EvaluationStack.Remove(n)); } break; case OpCode.ROT: { StackItem x3 = EvaluationStack.Pop(); StackItem x2 = EvaluationStack.Pop(); StackItem x1 = EvaluationStack.Pop(); EvaluationStack.Push(x2); EvaluationStack.Push(x3); EvaluationStack.Push(x1); } break; case OpCode.SWAP: { StackItem x2 = EvaluationStack.Pop(); StackItem x1 = EvaluationStack.Pop(); EvaluationStack.Push(x2); EvaluationStack.Push(x1); } break; case OpCode.TUCK: { StackItem x2 = EvaluationStack.Pop(); StackItem x1 = EvaluationStack.Pop(); EvaluationStack.Push(x2); EvaluationStack.Push(x1); EvaluationStack.Push(x2); } break; case OpCode.CAT: { byte[] x2 = EvaluationStack.Pop().GetByteArray(); byte[] x1 = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(x1.Concat(x2).ToArray()); } break; case OpCode.SUBSTR: { int count = (int)EvaluationStack.Pop().GetBigInteger(); if (count < 0) { State |= VMState.FAULT; return; } int index = (int)EvaluationStack.Pop().GetBigInteger(); if (index < 0) { State |= VMState.FAULT; return; } byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(x.Skip(index).Take(count).ToArray()); } break; case OpCode.LEFT: { int count = (int)EvaluationStack.Pop().GetBigInteger(); if (count < 0) { State |= VMState.FAULT; return; } byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(x.Take(count).ToArray()); } break; case OpCode.RIGHT: { int count = (int)EvaluationStack.Pop().GetBigInteger(); if (count < 0) { State |= VMState.FAULT; return; } byte[] x = EvaluationStack.Pop().GetByteArray(); if (x.Length < count) { State |= VMState.FAULT; return; } EvaluationStack.Push(x.Skip(x.Length - count).ToArray()); } break; case OpCode.SIZE: { byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(x.Length); } break; // Bitwise logic case OpCode.INVERT: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(~x); } break; case OpCode.AND: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 & x2); } break; case OpCode.OR: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 | x2); } break; case OpCode.XOR: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 ^ x2); } break; case OpCode.EQUAL: { StackItem x2 = EvaluationStack.Pop(); StackItem x1 = EvaluationStack.Pop(); EvaluationStack.Push(x1.Equals(x2)); } break; // Numeric case OpCode.INC: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x + 1); } break; case OpCode.DEC: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x - 1); } break; case OpCode.SIGN: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x.Sign); } break; case OpCode.NEGATE: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(-x); } break; case OpCode.ABS: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(BigInteger.Abs(x)); } break; case OpCode.NOT: { bool x = EvaluationStack.Pop().GetBoolean(); EvaluationStack.Push(!x); } break; case OpCode.NZ: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x != BigInteger.Zero); } break; case OpCode.ADD: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 + x2); } break; case OpCode.SUB: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 - x2); } break; case OpCode.MUL: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 * x2); } break; case OpCode.DIV: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 / x2); } break; case OpCode.MOD: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 % x2); } break; case OpCode.SHL: { int n = (int)EvaluationStack.Pop().GetBigInteger(); BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x << n); } break; case OpCode.SHR: { int n = (int)EvaluationStack.Pop().GetBigInteger(); BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x >> n); } break; case OpCode.BOOLAND: { bool x2 = EvaluationStack.Pop().GetBoolean(); bool x1 = EvaluationStack.Pop().GetBoolean(); EvaluationStack.Push(x1 && x2); } break; case OpCode.BOOLOR: { bool x2 = EvaluationStack.Pop().GetBoolean(); bool x1 = EvaluationStack.Pop().GetBoolean(); EvaluationStack.Push(x1 || x2); } break; case OpCode.NUMEQUAL: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 == x2); } break; case OpCode.NUMNOTEQUAL: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 != x2); } break; case OpCode.LT: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 < x2); } break; case OpCode.GT: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 > x2); } break; case OpCode.LTE: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 <= x2); } break; case OpCode.GTE: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 >= x2); } break; case OpCode.MIN: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(BigInteger.Min(x1, x2)); } break; case OpCode.MAX: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(BigInteger.Max(x1, x2)); } break; case OpCode.WITHIN: { BigInteger b = EvaluationStack.Pop().GetBigInteger(); BigInteger a = EvaluationStack.Pop().GetBigInteger(); BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(a <= x && x < b); } break; // Crypto case OpCode.SHA1: using (SHA1 sha = SHA1.Create()) { byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(sha.ComputeHash(x)); } break; case OpCode.SHA256: using (SHA256 sha = SHA256.Create()) { byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(sha.ComputeHash(x)); } break; case OpCode.HASH160: { byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(CryptoUtils.Hash160(x)); } break; case OpCode.HASH256: { byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(CryptoUtils.Hash256(x)); } break; case OpCode.CHECKSIG: { byte[] pubkey = EvaluationStack.Pop().GetByteArray(); byte[] signature = EvaluationStack.Pop().GetByteArray(); try { EvaluationStack.Push(CryptoUtils.VerifySignature(ScriptContainer.GetMessage(), signature, pubkey)); } catch (ArgumentException) { EvaluationStack.Push(false); } } break; case OpCode.CHECKMULTISIG: { int n; byte[][] pubkeys; StackItem item = EvaluationStack.Pop(); if (item is VMArray array1) { pubkeys = array1.Select(p => p.GetByteArray()).ToArray(); n = pubkeys.Length; if (n == 0) { State |= VMState.FAULT; return; } } else { n = (int)item.GetBigInteger(); if (n < 1 || n > EvaluationStack.Count) { State |= VMState.FAULT; return; } pubkeys = new byte[n][]; for (int i = 0; i < n; i++) { pubkeys[i] = EvaluationStack.Pop().GetByteArray(); } } int m; byte[][] signatures; item = EvaluationStack.Pop(); if (item is VMArray array2) { signatures = array2.Select(p => p.GetByteArray()).ToArray(); m = signatures.Length; if (m == 0 || m > n) { State |= VMState.FAULT; return; } } else { m = (int)item.GetBigInteger(); if (m < 1 || m > n || m > EvaluationStack.Count) { State |= VMState.FAULT; return; } signatures = new byte[m][]; for (int i = 0; i < m; i++) { signatures[i] = EvaluationStack.Pop().GetByteArray(); } } byte[] message = ScriptContainer.GetMessage(); bool fSuccess = true; try { for (int i = 0, j = 0; fSuccess && i < m && j < n;) { if (CryptoUtils.VerifySignature(message, signatures[i], pubkeys[j])) { i++; } j++; if (m - i > n - j) { fSuccess = false; } } } catch (ArgumentException) { fSuccess = false; } EvaluationStack.Push(fSuccess); } break; // Array case OpCode.ARRAYSIZE: { StackItem item = EvaluationStack.Pop(); if (item is ICollection collection) { EvaluationStack.Push(collection.Count); } else { EvaluationStack.Push(item.GetByteArray().Length); } } break; case OpCode.PACK: { int size = (int)EvaluationStack.Pop().GetBigInteger(); if (size < 0 || size > EvaluationStack.Count) { State |= VMState.FAULT; return; } List <StackItem> items = new List <StackItem>(size); for (int i = 0; i < size; i++) { items.Add(EvaluationStack.Pop()); } EvaluationStack.Push(items); } break; case OpCode.UNPACK: { StackItem item = EvaluationStack.Pop(); if (item is VMArray array) { for (int i = array.Count - 1; i >= 0; i--) { EvaluationStack.Push(array[i]); } EvaluationStack.Push(array.Count); } else { State |= VMState.FAULT; return; } } break; case OpCode.PICKITEM: { StackItem key = EvaluationStack.Pop(); if (key is ICollection) { State |= VMState.FAULT; return; } switch (EvaluationStack.Pop()) { case VMArray array: int index = (int)key.GetBigInteger(); if (index < 0 || index >= array.Count) { State |= VMState.FAULT; return; } EvaluationStack.Push(array[index]); break; case Map map: if (map.TryGetValue(key, out StackItem value)) { EvaluationStack.Push(value); } else { State |= VMState.FAULT; return; } break; default: State |= VMState.FAULT; return; } } break; case OpCode.SETITEM: { StackItem value = EvaluationStack.Pop(); if (value is Struct s) { value = s.Clone(); } StackItem key = EvaluationStack.Pop(); if (key is ICollection) { State |= VMState.FAULT; return; } switch (EvaluationStack.Pop()) { case VMArray array: int index = (int)key.GetBigInteger(); if (index < 0 || index >= array.Count) { State |= VMState.FAULT; return; } array[index] = value; break; case Map map: map[key] = value; break; default: State |= VMState.FAULT; return; } } break; case OpCode.NEWARRAY: { int count = (int)EvaluationStack.Pop().GetBigInteger(); List <StackItem> items = new List <StackItem>(count); for (var i = 0; i < count; i++) { items.Add(false); } EvaluationStack.Push(new Types.Array(items)); } break; case OpCode.NEWSTRUCT: { int count = (int)EvaluationStack.Pop().GetBigInteger(); List <StackItem> items = new List <StackItem>(count); for (var i = 0; i < count; i++) { items.Add(false); } EvaluationStack.Push(new VM.Types.Struct(items)); } break; case OpCode.NEWMAP: EvaluationStack.Push(new Map()); break; case OpCode.APPEND: { StackItem newItem = EvaluationStack.Pop(); if (newItem is Types.Struct s) { newItem = s.Clone(); } StackItem arrItem = EvaluationStack.Pop(); if (arrItem is VMArray array) { array.Add(newItem); } else { State |= VMState.FAULT; return; } } break; case OpCode.REVERSE: { StackItem arrItem = EvaluationStack.Pop(); if (arrItem is VMArray array) { array.Reverse(); } else { State |= VMState.FAULT; return; } } break; case OpCode.REMOVE: { StackItem key = EvaluationStack.Pop(); if (key is ICollection) { State |= VMState.FAULT; return; } switch (EvaluationStack.Pop()) { case VMArray array: int index = (int)key.GetBigInteger(); if (index < 0 || index >= array.Count) { State |= VMState.FAULT; return; } array.RemoveAt(index); break; case Map map: map.Remove(key); break; default: State |= VMState.FAULT; return; } } break; case OpCode.HASKEY: { StackItem key = EvaluationStack.Pop(); if (key is ICollection) { State |= VMState.FAULT; return; } switch (EvaluationStack.Pop()) { case VMArray array: int index = (int)key.GetBigInteger(); if (index < 0) { State |= VMState.FAULT; return; } EvaluationStack.Push(index < array.Count); break; case Map map: EvaluationStack.Push(map.ContainsKey(key)); break; default: State |= VMState.FAULT; return; } } break; case OpCode.KEYS: switch (EvaluationStack.Pop()) { case Map map: EvaluationStack.Push(new VMArray(map.Keys)); break; default: State |= VMState.FAULT; return; } break; case OpCode.VALUES: { ICollection <StackItem> values; switch (EvaluationStack.Pop()) { case VMArray array: values = array; break; case Map map: values = map.Values; break; default: State |= VMState.FAULT; return; } List <StackItem> newArray = new List <StackItem>(values.Count); foreach (StackItem item in values) { if (item is Struct s) { newArray.Add(s.Clone()); } else { newArray.Add(item); } } EvaluationStack.Push(new VMArray(newArray)); } break; // Exceptions case OpCode.THROW: State |= VMState.FAULT; return; case OpCode.THROWIFNOT: if (!EvaluationStack.Pop().GetBoolean()) { State |= VMState.FAULT; return; } break; default: State |= VMState.FAULT; return; } } if (!State.HasFlag(VMState.FAULT) && InvocationStack.Count > 0) { if (CurrentContext.BreakPoints.Contains((uint)CurrentContext.InstructionPointer)) { State |= VMState.BREAK; } } }
/// <summary> /// Performs an installation /// </summary> public virtual bool Install(AppletPackage package, bool isUpgrade = false) { this.m_tracer.TraceWarning("Installing {0}", package.Meta); // TODO: Verify package hash / signature if (!this.VerifyPackage(package)) { throw new SecurityException("Applet failed validation"); } else if (!this.m_appletCollection.VerifyDependencies(package.Meta)) { throw new InvalidOperationException($"Applet {package.Meta} depends on : [{String.Join(", ", package.Meta.Dependencies.Select(o => o.ToString()))}] which are missing or incompatible"); } var appletSection = ApplicationContext.Current.Configuration.GetSection <AppletConfigurationSection>(); String appletPath = Path.Combine(appletSection.AppletDirectory, package.Meta.Id); try { // Desearialize an prep for install this.m_tracer.TraceInfo("Installing applet {0} (IsUpgrade={1})", package.Meta, isUpgrade); ApplicationContext.Current.SetProgress(package.Meta.GetName("en"), 0.0f); // TODO: Verify the package // Copy if (!Directory.Exists(appletSection.AppletDirectory)) { Directory.CreateDirectory(appletSection.AppletDirectory); } if (File.Exists(appletPath)) { if (!isUpgrade) { throw new InvalidOperationException(Strings.err_duplicate_package_name); } // Unload the loaded applet version var existingApplet = this.m_appletCollection.FirstOrDefault(o => o.Info.Id == package.Meta.Id); if (existingApplet != null) { this.UnInstallInternal(existingApplet); } } var mfst = package.Unpack(); // Migrate data. if (mfst.DataSetup != null) { foreach (var itm in mfst.DataSetup.Action) { Type idpType = typeof(IDataPersistenceService <>); idpType = idpType.MakeGenericType(new Type[] { itm.Element.GetType() }); var svc = ApplicationContext.Current.GetService(idpType); idpType.GetMethod(itm.ActionName).Invoke(svc, new object[] { itm.Element }); } } // Now export all the binary files out var assetDirectory = Path.Combine(appletSection.AppletDirectory, "assets", mfst.Info.Id); if (!Directory.Exists(assetDirectory)) { Directory.CreateDirectory(assetDirectory); } else { Directory.Delete(assetDirectory, true); } for (int i = 0; i < mfst.Assets.Count; i++) { var itm = mfst.Assets[i]; var itmPath = Path.Combine(assetDirectory, itm.Name); ApplicationContext.Current.SetProgress($"Installing {package.Meta.GetName("en")}", 0.1f + (float)(0.8 * (float)i / mfst.Assets.Count)); // Get dir name and create if (!Directory.Exists(Path.GetDirectoryName(itmPath))) { Directory.CreateDirectory(Path.GetDirectoryName(itmPath)); } // Extract content if (itm.Content is byte[]) { File.WriteAllBytes(itmPath, itm.Content as byte[]); itm.Content = null; } else if (itm.Content is String) { File.WriteAllText(itmPath, itm.Content as String); itm.Content = null; } } // Serialize the data to disk using (FileStream fs = File.Create(appletPath)) mfst.Save(fs); // For now sign with SHA256 SHA256 sha = SHA256.Create(); package.Meta.Hash = sha.ComputeHash(File.ReadAllBytes(appletPath)); // HACK: Re-re-remove appletSection.Applets.RemoveAll(o => o.Id == package.Meta.Id); appletSection.Applets.Add(package.Meta.AsReference()); ApplicationContext.Current.SetProgress(package.Meta.GetName("en"), 0.98f); ApplicationContext.Current.SaveConfiguration(); this.LoadApplet(mfst); } catch (Exception e) { this.m_tracer.TraceError("Error installing applet {0} : {1}", package.Meta.ToString(), e); // Remove if (File.Exists(appletPath)) { File.Delete(appletPath); } throw; } return(true); }
public byte[] calculateHashForBlock() { SHA256 mySHA256 = SHA256Managed.Create(); return(mySHA256.ComputeHash(Encoding.ASCII.GetBytes(this.index + this.previousHash.ToString() + this.timestamp + this.data + this.value))); }
public static string Hash(this string content) => _hash.ComputeHash(content.ToBytesUtf8()).ToBase64String();
private byte[] GetSha256Sum(String _file) { FileStream fs = File.OpenRead(_file); return(Sha256.ComputeHash(fs)); }
private string SHA256(string filePath) { using SHA256 SHA256 = SHA256.Create(); using FileStream fileStream = File.OpenRead(filePath); return(Convert.ToBase64String(SHA256.ComputeHash(fileStream))); }
public long ParseNro(out NroInfo Res, ServiceCtx Context, ulong NroAddress, ulong NroSize, ulong BssAddress, ulong BssSize) { Res = null; if (NroInfos.Count >= MaxNro) { return(MakeError(ErrorModule.Loader, LoaderErr.MaxNro)); } else if (NroSize == 0 || NroAddress + NroSize <= NroAddress || (NroSize & 0xFFF) != 0) { return(MakeError(ErrorModule.Loader, LoaderErr.BadSize)); } else if (BssSize != 0 && BssAddress + BssSize <= BssAddress) { return(MakeError(ErrorModule.Loader, LoaderErr.BadSize)); } else if ((NroAddress & 0xFFF) != 0) { return(MakeError(ErrorModule.Loader, LoaderErr.UnalignedAddress)); } uint Magic = Context.Memory.ReadUInt32((long)NroAddress + 0x10); uint NroFileSize = Context.Memory.ReadUInt32((long)NroAddress + 0x18); if (Magic != NroMagic || NroSize != NroFileSize) { return(MakeError(ErrorModule.Loader, LoaderErr.InvalidNro)); } byte[] NroData = Context.Memory.ReadBytes((long)NroAddress, (long)NroSize); byte[] NroHash = null; MemoryStream Stream = new MemoryStream(NroData); using (SHA256 Hasher = SHA256.Create()) { NroHash = Hasher.ComputeHash(Stream); } if (!IsNroHashPresent(NroHash)) { return(MakeError(ErrorModule.Loader, LoaderErr.NroHashNotPresent)); } if (IsNroLoaded(NroHash)) { return(MakeError(ErrorModule.Loader, LoaderErr.NroAlreadyLoaded)); } Stream.Position = 0; NxRelocatableObject Executable = new NxRelocatableObject(Stream, NroAddress, BssAddress); // check if everything is page align. if ((Executable.Text.Length & 0xFFF) != 0 || (Executable.RO.Length & 0xFFF) != 0 || (Executable.Data.Length & 0xFFF) != 0 || (Executable.BssSize & 0xFFF) != 0) { return(MakeError(ErrorModule.Loader, LoaderErr.InvalidNro)); } // check if everything is contiguous. if (Executable.ROOffset != Executable.TextOffset + Executable.Text.Length || Executable.DataOffset != Executable.ROOffset + Executable.RO.Length || NroFileSize != Executable.DataOffset + Executable.Data.Length) { return(MakeError(ErrorModule.Loader, LoaderErr.InvalidNro)); } // finally check the bss size match. if ((ulong)Executable.BssSize != BssSize) { return(MakeError(ErrorModule.Loader, LoaderErr.InvalidNro)); } int TotalSize = Executable.Text.Length + Executable.RO.Length + Executable.Data.Length + Executable.BssSize; Res = new NroInfo( Executable, NroHash, NroAddress, NroSize, BssAddress, BssSize, (ulong)TotalSize); return(0); }
private byte[] SeedWordsToEntropyBytes(string[] seedWords) { // An int array to store the seed word values int[] wordlistValues = new int[seedWords.Length]; // Convert the seed words to integers for (int currentWord = 0; currentWord < wordlistValues.Length; currentWord++) { wordlistValues[currentWord] = BIP_0039_Dictionaries.en_US.IntFromWord(seedWords[currentWord]); } // Each seed word represents 11 bits int seedLength = wordlistValues.Length * 11; // There is a checksum bit for every 32 bits of entropy - 11 * 32 = 352 int checksumLength = (seedLength / 352 * 32) + (seedLength % 32); // Calculate and validate the entropy length (in bits) int entropyLength = seedLength - checksumLength; if (entropyLength % 32 != 0) { throw new ArgumentException("Entropy from seed must be a multiple of 32 bits."); } // Entropy length in bytes int entropyLengthBytes = entropyLength / 8; // An int array to store the entropy int[] entropyByteInts = new int[entropyLengthBytes]; // An int array to store the checksum int[] seedChecksumByteInts = new int[checksumLength / 8 + 1]; // Track where we are in the entropy byte array int currentEntropyByte = 0; // Track where we are in the current entropy byte int currentEntropyBit = 0; // Track where we are in the checksum byte array int currentChecksumByte = 0; // Track where we are in the current checksum byte int currentChecksumBit = 0; // Extract the bits from the BIP-39 word value array for (int currentWord = 0; currentWord < wordlistValues.Length; currentWord++) { // Get the bits from the word for (int i = 0; i < 11; i++) { // Check if this bit belongs to entropy bytes if ((currentWord * 11 + i) < entropyLength) { // If the current bit should be a 1, make it a 1 if ((wordlistValues[currentWord] & (1 << (10 - i))) != 0) { entropyByteInts[currentEntropyByte] |= 1 << (7 - currentEntropyBit); } // Move to next bit in the current byte currentEntropyBit++; // Move to next byte if there are no bits left in the current byte if (currentEntropyBit % 8 == 0) { currentEntropyByte++; currentEntropyBit = 0; } } else { // If the current bit should be a 1, make it a 1 if ((wordlistValues[currentWord] & (1 << (10 - i))) != 0) { seedChecksumByteInts[currentChecksumByte] |= 1 << (7 - currentChecksumBit); } // Move to next bit in the current byte currentChecksumBit++; // Move to next byte if there are no bits left in the current byte if (currentChecksumBit % 8 == 0) { currentChecksumByte++; currentChecksumBit = 0; } } } } // Convert the entropy int array to a byte array byte[] entropyBytes = new byte[entropyLengthBytes]; for (int i = 0; i < entropyByteInts.Length; i++) { entropyBytes[i] = (byte)entropyByteInts[i]; } Array.Clear(entropyByteInts, 0, entropyByteInts.Length); // Convert the checksum int array to a byte array byte[] seedChecksumBytes = new byte[checksumLength / 8 + 1]; for (int i = 0; i < seedChecksumByteInts.Length; i++) { seedChecksumBytes[i] = (byte)seedChecksumByteInts[i]; } Array.Clear(seedChecksumByteInts, 0, seedChecksumByteInts.Length); // Create a SHA256 instance SHA256 sha256 = SHA256.Create(); // Calculate and store the checksum hash bytes byte[] checksumBytes = sha256.ComputeHash(entropyBytes); // Bit shift the last relevant byte in the hashsum for the final 1-8 checksum bits byte checksumBits = (byte)(checksumBytes[checksumLength / 8] << (7 - (checksumLength % 8))); // Verify the checksum bytes (if applicable) for (int i = 0; i < checksumLength / 8; i++) { if (seedChecksumBytes[i] != checksumBytes[i]) { Console.WriteLine("Checksum doesn't match."); } } // Verify the final 1-8 checksum bits if (checksumBits != seedChecksumBytes[^ 1]) { Console.WriteLine("Checksum doesn't match."); } return(entropyBytes); }
internal static string Hash(FileStream stream) { var hash = sha256.ComputeHash(stream); return(BitConverter.ToString(hash).Replace("-", string.Empty).ToLowerInvariant()); }
/// <summary> /// Copies AIV sets to aivDir (aiv subdirectory of SHC installation) /// </summary> /// <param name="aivDir"></param> internal bool CopyAIVs(DirectoryInfo destinationDir, bool overwrite, bool graphical) { Assembly asm = Assembly.GetExecutingAssembly(); List <string> resourceFiles = Directory.GetFiles(Path.Combine("resources", "aiv", resFolder)).Where(x => x.EndsWith(".aiv")).Select(x => Path.GetFileName(ReplaceFirst(x, resFolder + Path.PathSeparator, ""))).ToList(); // If same AIV exist in both check if contents identical bool isIdentical = true; if (destinationDir.GetFiles().ToList().Select(x => x.Name).Where(x => x.EndsWith(".aiv")).SequenceEqual(resourceFiles, StringComparer.CurrentCultureIgnoreCase)) { foreach (string aivFile in resourceFiles) { using (SHA256 SHA256Instance = SHA256.Create()) { using (Stream dstStream = new FileInfo(Path.Combine(destinationDir.FullName, aivFile)).OpenRead()) { using (Stream srcStream = new FileInfo(Path.Combine("resources", "aiv", resFolder, aivFile)).OpenRead()) { if (!Convert.ToBase64String(SHA256Instance.ComputeHash(srcStream)) .Equals(Convert.ToBase64String(SHA256Instance.ComputeHash(dstStream)))) { isIdentical = false; break; } } } } } } else { isIdentical = false; } if (isIdentical) { return(true); } // If overwrite, delete aiv contents of aiv directory and write new AIV files if (overwrite) { foreach (FileInfo file in destinationDir.GetFiles()) { file.Delete(); } foreach (string aivFile in resourceFiles) { using (Stream dstStream = new FileInfo(Path.Combine(destinationDir.FullName, aivFile)).OpenWrite()) { using (Stream srcStream = new FileInfo(Path.Combine("resources", "aiv", resFolder, aivFile)).OpenRead()) { srcStream.CopyTo(dstStream); } } } return(true); } /** * This logic runs when the contents of the backup and destination aiv folders are different. * If an existing subfolder named 'original' does not exist in the destination aiv folder * - Create folder 'original' * - Copy all files from destination aiv folder to 'original' folder * - Copy new aiv files to destination aiv folder */ DirectoryInfo backupDir = new DirectoryInfo(Path.Combine(destinationDir.FullName, "original")); if (!Directory.Exists(Path.Combine(destinationDir.FullName, "original")) || backupDir.GetFiles().Length == 0) { if (Directory.EnumerateFiles(destinationDir.FullName, "*", SearchOption.TopDirectoryOnly).Select(x => x.EndsWith(".aiv")).ToList().Count > 0) { backupDir.Create(); } foreach (string aivFile in destinationDir.GetFiles().ToList().Select(x => x.Name)) { using (Stream dstStream = new FileInfo(Path.Combine(backupDir.FullName, aivFile)).OpenWrite()) { using (Stream srcStream = new FileInfo(Path.Combine(destinationDir.FullName, aivFile)).OpenRead()) { srcStream.CopyTo(dstStream); } File.Delete(Path.Combine(destinationDir.FullName, aivFile)); } } } else { // Determine if the aiv files in destination folder are identical to backup folder bool backupIdentical = true; foreach (string aivFile in destinationDir.GetFiles().ToList().Where(x => x.Name.EndsWith(".aiv")).Select(x => x.Name)) { using (SHA256 SHA256Instance = SHA256.Create()) { try { using (Stream dstStream = new FileInfo(Path.Combine(backupDir.FullName, aivFile)).OpenRead()) { using (Stream srcStream = new FileInfo(Path.Combine(destinationDir.FullName, aivFile)).OpenRead()) { if (!Convert.ToBase64String(SHA256Instance.ComputeHash(srcStream)) .Equals(Convert.ToBase64String(SHA256Instance.ComputeHash(dstStream)))) { backupIdentical = false; break; } } } } catch (IOException) { backupIdentical = false; } } } // If backup contains all aiv files from destination folder then delete aiv from destination folder if (backupIdentical) { foreach (FileInfo file in destinationDir.GetFiles()) { if (file.Extension.Equals(".aiv")) { file.Delete(); } } } /** * This logic runs when the contents of the backup and destination aiv folders are different. */ if (!backupIdentical && graphical) // Clear backup folder of aiv files { MessageBoxResult result = System.Windows.MessageBox.Show(Localization.Get("aiv_prompt"), "", MessageBoxButton.YesNoCancel); if (result == MessageBoxResult.No) { foreach (FileInfo file in destinationDir.GetFiles()) { file.Delete(); } } else if (result == MessageBoxResult.Yes) // Clear destination aiv folder of aiv files. { using (var dialog = new FolderBrowserDialog()) { dialog.Description = Localization.Get("backup_aiv_select"); dialog.RootFolder = Environment.SpecialFolder.Desktop; DialogResult folderResult = DialogResult.Cancel; var thread = new Thread(obj => { folderResult = dialog.ShowDialog(); }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); if (folderResult == DialogResult.OK && !string.IsNullOrWhiteSpace(dialog.SelectedPath)) { DirectoryInfo savePath = new DirectoryInfo(dialog.SelectedPath); string[] files = Directory.GetFiles(dialog.SelectedPath); foreach (FileInfo file in destinationDir.GetFiles()) { file.MoveTo(Path.Combine(savePath.FullName, Path.GetFileName(file.Name))); } } else { throw new Exception(); } } } else { throw new Exception(); } } else if (!backupIdentical) { string input = ""; while (!input.ToLower().Equals("delete") && (input.IndexOfAny(Path.GetInvalidPathChars()) != -1 || (input.Equals("") || Directory.Exists(Path.Combine(destinationDir.FullName, input))))) { Console.WriteLine(Localization.Get("aiv_cli_prompt")); input = Console.ReadLine().Replace("\n", ""); } ; if (input.ToLower().Equals("delete")) { foreach (string file in Directory.EnumerateFiles(destinationDir.FullName, "*", SearchOption.TopDirectoryOnly)) { File.Delete(file); } } else { DirectoryInfo extraBackupDir = Directory.CreateDirectory(Path.Combine(destinationDir.FullName, input)); foreach (string file in Directory.EnumerateFiles(backupDir.FullName, "*", SearchOption.TopDirectoryOnly)) { File.Move(file, Path.Combine(extraBackupDir.FullName, Path.GetFileName(file))); } } foreach (string file in Directory.EnumerateFiles(destinationDir.FullName, "*", SearchOption.TopDirectoryOnly)) { File.Move(file, Path.Combine(backupDir.FullName, Path.GetFileName(file))); } } } foreach (string aivFile in resourceFiles) { using (Stream dstStream = new FileInfo(Path.Combine(destinationDir.FullName, aivFile)).OpenWrite()) { using (Stream srcStream = new FileInfo(Path.Combine("resources", "aiv", resFolder, aivFile)).OpenRead()) { srcStream.CopyTo(dstStream); } } } return(true); }
private string EncodeNumber(SHA256 sha256, string numberToEncode) { return(string.Join("", sha256 .ComputeHash(Encoding.UTF8.GetBytes(numberToEncode)) .Select(item => item.ToString("x2")))); }
public byte[] Sha256() => sha256.ComputeHash(data);
public void UploadMatchBatch(AccumulatedFrame round, bool final = false) { if (!SparkSettings.instance.uploadToIgniteDB) { Console.WriteLine("Won't upload right now."); } BatchOutputFormat data = new BatchOutputFormat { final = final, match_data = round.ToDict() }; round.players.Values.ToList().ForEach(e => { if (e.Name != "anonymous") { data.match_players.Add(e.ToDict()); } }); round.events.ForEach(e => { if (!e.inDB) { data.events.Add(e.ToDict()); } e.inDB = true; }); round.goals.ForEach(e => { if (!e.inDB) { data.goals.Add(e.ToDict()); } e.inDB = true; }); round.throws.ForEach(e => { if (!e.inDB) { data.throws.Add(e.ToDict()); } e.inDB = true; }); string dataString = JsonConvert.SerializeObject(data); string hash; using (SHA256 sha = SHA256.Create()) { byte[] rawHash = sha.ComputeHash(Encoding.ASCII.GetBytes(dataString + round.frame.client_name)); // Convert the byte array to hexadecimal string StringBuilder sb = new StringBuilder(); foreach (byte b in rawHash) { sb.Append(b.ToString("X2")); } hash = sb.ToString().ToLower(); } if (SparkSettings.instance.uploadToIgniteDB || DiscordOAuth.AccessCode.series_name.Contains("vrml")) { _ = DoUploadMatchBatchIgniteDB(dataString, hash, round.frame.client_name); } // upload tablet stats as well if (round.frame?.private_match == false) { Program.AutoUploadTabletStats(); } }
static byte[] HashSHA256(string plainText) { SHA256 sha = SHA256.Create(); return(sha.ComputeHash(Encoding.UTF8.GetBytes(plainText))); }
public async Task <IActionResult> LoginAsync([FromBody] LoginModel loginModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } using (SHA256 sha256Hash = SHA256.Create()) { // ComputeHash - returns byte array byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(loginModel.Password)); // Convert byte array to a string StringBuilder builder = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { builder.Append(bytes[i].ToString("x2")); } loginModel.Password = builder.ToString(); } Person personFound = _context.Person.FirstOrDefault(person => person.Email == loginModel.Email && person.Password == loginModel.Password); if (personFound == null) { return(Unauthorized()); } var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, personFound.Email), new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64), new Claim("idUser", personFound.PersonId.ToString()) }; claims.Add(new Claim("role", personFound.Role)); claims.Add(new Claim("name", personFound.Name)); claims.Add(new Claim("firstName", personFound.Name)); JwtSecurityToken token = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: _jwtOptions.SigningCredentials ); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(token); var reponse = new Token() { Access_Token = encodedJwt, Expires_In = (int)_jwtOptions.ValidFor.TotalSeconds // TODO : Aller remettre 5 minutes dans le ValidFor des jwtOptions }; return(Ok(reponse)); }
private static byte[] HashIteration(byte[] bytes) { return(_generator.ComputeHash(bytes)); }
public async Task <IActionResult> OnPostAsync(int id) { var cardToUpdate = await _context.CreditCards.FindAsync(id); if (cardToUpdate == null) { return(NotFound()); } var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound()); } var Userid = _signInManager.Context.User.Claims.FirstOrDefault().Value; cardToUpdate.OwnerId = Userid; cardToUpdate.Owner = user; DateTime checkdate = DateTime.Now; if (Input.CardNumber.ToString().Length != 16) { ViewData["Err"] = "Card Number is not valid"; } else if (Input.Month == 0 || Input.Month > 12 || Input.Month < 0) { ViewData["Err"] = "Expiry Month is not valid"; } else if (Input.Year.ToString().Length != 4) { ViewData["Err"] = "Expiry Year is not valid"; } else if ((Input.Month < checkdate.Month && Input.Year == checkdate.Year) || (Input.Year < checkdate.Year)) { ViewData["Err"] = "Card has expired. Please enter a valid card."; } else { if (cardToUpdate.Month != Input.Month) { cardToUpdate.Month = Input.Month; } if (cardToUpdate.Year != Input.Year) { cardToUpdate.Year = Input.Year; } string hashCardNumber = Input.CardNumber.ToString(); using (SHA256 sha256Hash = SHA256.Create()) { // ComputeHash - returns byte array byte[] hashValue = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(hashCardNumber)); StringBuilder result = new StringBuilder(); for (int i = 0; i < hashValue.Length; i++) { //result.Append(hashValue[i].ToString()); result.Insert(i, hashValue[i].ToString("x2")); } hashedCreditCard = result.ToString(); } //hashedCreditCard += Input.CardNumber.ToString().Substring(12, 4); if (cardToUpdate.CardNumber != Int64.Parse(Input.CardNumber.ToString().Substring(12, 4))) { cardToUpdate.CardNumber = Int64.Parse(Input.CardNumber.ToString().Substring(12, 4)); } if (cardToUpdate.HashedCardNumber != hashedCreditCard) { cardToUpdate.HashedCardNumber = hashedCreditCard; } //CreditCardVM.CardNumber = Int64.Parse(Input.CardNumber.ToString().Substring(12, 4)); //CreditCardVM.HashedCardNumber = hashedCreditCard; var entry = _context.CreditCards.Update(cardToUpdate); entry.CurrentValues.SetValues(cardToUpdate); await _context.SaveChangesAsync(); return(RedirectToPage("./CreditCardIndex")); } return(Page()); }
/** * Signs a message.<br/> * This is a "one stop" method and does not require <code>initSign</code> to be called. Only the message supplied via * the parameter <code>m</code> is signed, regardless of prior calls to {@link #update(byte[])}. * @param m the message to sign * @param kp a key pair (the public key is needed to ensure there are no signing failures) * @return a signature * @throws NtruException if the JRE doesn't implement the specified hash algorithm */ public byte[] sign(byte[] m, SignatureKeyPair kp) { try { // EESS directly passes the message into the MRGM (message representative // generation method). Since that is inefficient for long messages, we work // with the hash of the message. hashAlg = new SHA256(); byte[] msgHash = hashAlg.ComputeHash(m); return signHash(msgHash, kp); } catch (Exception e) { throw new NtruException(e.Message); } }
private T callRemoteApi <T, U>(U request, HotelApiPaths.HotelApiPathsBase path, List <Tuple <string, string> > param) { try { T response = default(T); using (var client = new HttpClient()) { if (request == null && (path.GetType() != typeof(HotelApiPaths.STATUS) && path.GetType() != typeof(HotelApiPaths.BOOKING_CANCEL) && path.GetType() != typeof(HotelApiPaths.BOOKING_DETAIL) && path.GetType() != typeof(HotelApiPaths.BOOKING_LIST))) { throw new Exception("Object request can't be null"); } client.BaseAddress = new Uri(path.getUrl(this.basePath, this.version)); client.DefaultRequestHeaders.Clear(); client.Timeout = new TimeSpan(0, 0, REST_TEMPLATE_READ_TIME_OUT); client.DefaultRequestHeaders.Add("Api-Key", this.apiKey); client.DefaultRequestHeaders.Add("Accept-Encoding", "Gzip"); client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json"); client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json"); long ts = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds / 1000; SHA256 hashstring = SHA256Managed.Create(); byte[] hash = hashstring.ComputeHash(Encoding.UTF8.GetBytes(this.apiKey + this.sharedSecret + ts)); string signature = BitConverter.ToString(hash).Replace("-", ""); client.DefaultRequestHeaders.Add("X-Signature", signature.ToString()); // GET Method if (path.getHttpMethod() == HttpMethod.Get) { string Uri = path.getEndPoint(); if (param != null) { Uri = path.getEndPoint(param); } HttpResponseMessage resp = client.GetAsync(Uri).Result; response = resp.Content.ReadAsAsync <T>().Result; return(response); } // DELETE Method if (path.getHttpMethod() == HttpMethod.Delete) { string Uri = path.getEndPoint(); if (param != null) { Uri = path.getEndPoint(param); } HttpResponseMessage resp = client.DeleteAsync(Uri).Result; response = resp.Content.ReadAsAsync <T>().Result; return(response); } StringContent contentToSend = null; if (request != null) { string objectSerialized = JsonConvert.SerializeObject(request, Formatting.Indented, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore }); contentToSend = new StringContent(objectSerialized, Encoding.UTF8, "application/json"); } if (path.getHttpMethod() == HttpMethod.Post) { HttpResponseMessage resp = null; if (param == null) { resp = client.PostAsync(path.getEndPoint(), contentToSend).Result; } else { resp = client.PostAsync(path.getEndPoint(param), contentToSend).Result; } response = resp.Content.ReadAsAsync <T>().Result; } } return(response); } catch (HotelSDKException e) { throw e; } }