/// <summary> /// Validates server acceptance message /// </summary> /// <remark> /// Here the client verifies that the received message length is 80 /// bytes, then opens the encrypted box and verifies that the sent /// message is server's signature to the derived shared secrets. With /// this the handshake concludes. /// </remark> /// <exception cref="ArgumentException"> /// Thrown if the server's Accept <paramref name="msg"/> is not the /// correct size or the signature is not valid. /// </exception> /// <param name="msg"> /// The received message, encrypted server's signature. /// </param> public void VerifyAccept(byte[] msg) { if (msg.Length != 80) { throw new ArgumentException("Incorrect message size"); } var nonce = new byte[NONCE_SIZE]; nonce.Initialize(); // Concatenate the network key and derived secrets to obtain // the message key var key = CryptoHash.Sha256( Utils.Concat(_network_key, _shared_ab, _shared_aB, _shared_Ab) ); var opened_msg = SecretBox.Open(msg, nonce, key); // Compute the message that it is supposed to be signed with the // server's long term key var hashed = CryptoHash.Sha256(_shared_ab); var msg_to_verify = Utils.Concat( _network_key, detached_signature_A, _longterm_client_keypair.PublicKey, hashed ); if (!PublicKeyAuth.VerifyDetached(opened_msg, msg_to_verify, _longterm_server_pk)) { throw new ArgumentException("Invalid signature"); } }
/// <summary> /// Given the keys obtained during the handshake generates a pair of /// Boxer/Unboxer. /// </summary> /// <remarks> /// <para> /// TODO: Write about the process detailed in the spec /// </para> /// </remarks> /// <param name="derived_secret"> /// The secret derived from the client long term key and the server's /// ephemeral key (Ab). /// </param> /// <param name="foreing_pubkey"> /// The public key that identifies the other peer, that is, the server /// public key if this is called from the client and vice versa. /// </param> /// <param name="self_pubkey"> /// The public key that identifies the entity calling this. /// </param> /// <param name="network_key"> /// The key that identifies the network, in the case of scuttlebutt is /// the one posted in the scuttlebutt protocol /// <see href="https://ssbc.github.io/scuttlebutt-protocol-guide/"> /// guide /// </see>. /// </param> /// <param name="a"> /// The client's ephemeral public key used during the handshake. /// </param> /// <param name="b"> /// The server's ephemeral public key used during the handshake. /// </param> /// <returns> /// The Boxer/Unboxer pair that a client or server can use to /// communicate with the other. /// </returns> public static (Boxer, Unboxer) Build( byte[] derived_secret, byte[] foreing_pubkey, byte[] self_pubkey, byte[] network_key, byte[] a, byte[] b ) { var common = CryptoHash.Sha256(CryptoHash.Sha256(derived_secret)); var send_key = CryptoHash.Sha256(Utils.Concat(common, foreing_pubkey)); var recv_key = CryptoHash.Sha256(Utils.Concat(common, self_pubkey)); var send_nonce = new byte[24]; var recv_nonce = new byte[24]; var bhmac = SecretKeyAuth.Sign(b, network_key); var ahmac = SecretKeyAuth.Sign(a, network_key); Buffer.BlockCopy(send_nonce, 0, bhmac, 0, 24); Buffer.BlockCopy(recv_nonce, 0, ahmac, 0, 24); var boxer = new Boxer(send_key, send_nonce); var unboxer = new Unboxer(recv_key, recv_nonce); return(boxer, unboxer); }
/// <summary> /// Computes the message that accepts the handshake. /// </summary> /// <remark> /// Here the server computes a signature of the network key, the /// signature of the long term client's public key and a sha 256 of /// the shared ab secret. This is signed with the server's long term /// private key. /// /// This signature is encrypted using a sha 256 of the network key /// and all of the derived secrets. /// </remark> /// <returns> /// A byte array of length 80 consisting of the message. /// </returns> public byte[] Accept() { var detached_signature = PublicKeyAuth.SignDetached( Utils.Concat( _network_key, detached_signature_A, _longterm_client_pk, CryptoHash.Sha256(_shared_ab) ), _longterm_server_keypair.PrivateKey ); // A nonce consisting of 24 zeros var nonce = new byte[NONCE_SIZE]; nonce.Initialize(); var key = CryptoHash.Sha256( Utils.Concat(_network_key, _shared_ab, _shared_aB, _shared_Ab) ); var msg = SecretBox.Create(detached_signature, nonce, key); return(msg); }
public void Sha512Test() { var sha512 = CryptoHash.Sha512(System.Text.Encoding.UTF8.GetBytes(hashString)); string hex = BitConverter.ToString(sha512).Replace("-", string.Empty).ToLower(); Assert.AreEqual(sha512out, hex); }
protected override void OnModelCreating(ModelBuilder builder) { #if DEBUG // create super admin account var hasher = new CryptoHash(new CryptoRandom()); var(hash, salt) = hasher.Pbkdf2Hash("T0p$ecret"); builder.Entity <User>().HasData(new User { Id = 1000, FirstName = "Super", LastName = "Admin", Email = "*****@*****.**", Role = UserRole.Admin | UserRole.BankOfficer, PasswordSalt = salt.GetBase64String(), PasswordHash = hash.GetBase64String() }); // create currencies builder.Entity <Currency>().HasData(new Currency[] { new Currency { Id = 1000, Name = "VND" }, new Currency { Id = 1001, Name = "USD" }, new Currency { Id = 1002, Name = "EUR" } }); #endif }
/// <summary> /// Crafts the client Authenticate message /// </summary> /// <remark> /// Consists of a signature of the network identifier, the server's /// long term public key and a sha 256 of the derived secret ab, /// concatenated with the client's long term public key. All /// encrypted using the network identifier and the derived secrets /// ab and aB. /// /// This sets the object's <see cref="detached_signature_A"/> /// </remark> /// <returns> /// The client Authenticate message /// </returns> public byte[] Authenticate() { var hash_ab = CryptoHash.Sha256(this._shared_ab); // Concatenate the network identifier, the server's public key and // the hash of the derived secret. var to_sign = Utils.Concat( _network_key, _longterm_server_pk, hash_ab ); // Sign the first portion of the message and save it in the object // state for later use in the server accept verification. detached_signature_A = PublicKeyAuth.SignDetached( to_sign, _longterm_client_keypair.PrivateKey ); // Create the plaintext message var plaintext = Utils.Concat( detached_signature_A, _longterm_client_keypair.PublicKey ); // Create the key from the network key and the shared secrets var box_key = Utils.Concat( _network_key, _shared_ab, _shared_aB ); // A nonce consisting of 24 zeros var nonce = new byte[NONCE_SIZE]; nonce.Initialize(); var msg = SecretBox.Create(plaintext, nonce, CryptoHash.Sha256(box_key)); return(msg); }
/// <summary> /// Run the application. /// </summary> public override BoolMessageItem Execute() { // 1. Encrypt using default provider. ( Symmetric TripleDes ) string plainText = "www.knowledgedrink.com"; string encrypted = Crypto.Encrypt(plainText); string decrypted = Crypto.Decrypt(encrypted); Console.WriteLine("===================================================="); Console.WriteLine("CRYPTOGRAPHY "); Console.WriteLine("Encrypted : " + plainText + " to " + encrypted); Console.WriteLine("Decrypted : " + encrypted + " to " + decrypted); Console.WriteLine(Environment.NewLine); // 2. Use non-static encryption provider. ICrypto crypto = new CryptoHash("commonlib.net", new MD5CryptoServiceProvider()); string hashed = crypto.Encrypt("my baby - 2002 honda accord ex coupe"); Console.WriteLine(hashed); // 3. Change the crypto provider on the static helper. ICrypto crypto2 = new CryptoSym("new key", new TripleDESCryptoServiceProvider()); Crypto.Init(crypto2); string encryptedWithNewKey = Crypto.Encrypt("www.knowledgedrink.com"); Console.WriteLine(string.Format("Encrypted text : using old key - {0}, using new key - {1}", encrypted, encryptedWithNewKey)); return(BoolMessageItem.True); }
public void CanDecryptHash() { string encrypted = "44bf9ba3479261e365c6389bc03bf497"; ICrypto crypto = new CryptoHash("commonlib.net", new MD5CryptoServiceProvider()); bool ismatch = crypto.IsMatch(encrypted, "horizonguy"); Assert.AreEqual(ismatch, true); }
public void CanEncryptHash() { string plainText = "horizonguy"; ICrypto crypto = new CryptoHash("commonlib.net", new MD5CryptoServiceProvider()); string encrypted = crypto.Encrypt(plainText); Assert.AreNotEqual("horizonguy", encrypted); }
private byte[] GetVerifierHash() { var master = CryptWithPassword(_encryptedMasterKey); var verifier = CryptoHash.SHA256(master); Array.Clear(master, 0, master.Length); Array.Resize(ref verifier, 16); return(verifier); }
/// <summary> /// Checks for <paramref name="msg"/> length and validity, extracting /// the client's long term public key upon success. /// </summary> /// <param name="msg">Client authenticate message</param> /// <exception cref="ArgumentException"> /// Thrown if the client Auth <paramref name="msg"/> fails to pass the /// checks. /// </exception> public void AcceptAuth(byte[] msg) { if (msg.Length != 112) { throw new ArgumentException("Incorrect secretbox length"); } // A nonce consisting of 24 zeros var nonce = new byte[NONCE_SIZE]; nonce.Initialize(); // Calculate the decryption key from the dervided keys var key = CryptoHash.Sha256( Utils.Concat(_network_key, _shared_ab, _shared_aB) ); var opened_msg = SecretBox.Open(msg, nonce, key); if (opened_msg.Length != 96) { throw new ArgumentException("Invalid size of opened message"); } // Extract the signature of the long term client's public key // signed with the derived secret var detached_signature = new byte[SIG_SIZE]; Buffer.BlockCopy(opened_msg, 0, detached_signature, 0, SIG_SIZE); // Extract the long term client's public key var lt_cli_pk = new byte[PUB_KEY_SIZE]; Buffer.BlockCopy(opened_msg, SIG_SIZE, lt_cli_pk, 0, PUB_KEY_SIZE); var shared_hashed = CryptoHash.Sha256(_shared_ab); // Concat network_key, server longterm pk and sha256 hashed shared_ab secret var to_verify = Utils.Concat( _network_key, _longterm_server_keypair.PublicKey, shared_hashed ); if (!PublicKeyAuth.VerifyDetached(detached_signature, to_verify, lt_cli_pk)) { throw new ArgumentException("Signature does not match"); } detached_signature_A = detached_signature; _longterm_client_pk = lt_cli_pk; this.DeriveAb(); }
public string Login(string email, string password) { password = password.EnsureNotNullOrWhiteSpace(nameof(password)); var user = Get(email); var passwordHash = CryptoHash.Pbkdf2Hash(password, user.PasswordSalt.ParseBase64String()).GetBase64String(); if (passwordHash.IsOrdinalEqual(user.PasswordHash, true)) { return(JwtService.GenerateToken(user)); } else { throw new BusinessException("Email or password is not correct."); } }
public async Task ChangeCardPin(dynamic data) { try { string cardNum = data["card_num"]; string newPin = data["new_pin"]; var card = await _unitOfWork.Repository <Card>().GetAsync(c => c.Number == cardNum); card.PinHash = CryptoHash.ComputeHash(newPin, new MD5CryptoServiceProvider()); _unitOfWork.Repository <Card>().Update(card); await _unitOfWork.SaveChangesAsync(); } catch (InvalidOperationException) { throw new Exception("Incorrect card number or new pin "); } }
public (int userId, int?bankAccountId) Create(string email, string password, string role, string firstName, string lastName, string bankAccount, string bankAccountCurrency) { password.EnsureNotNullOrWhiteSpace(nameof(password)); email.EnsureNotNullOrWhiteSpace(nameof(email)); firstName.EnsureNotNullOrWhiteSpace(nameof(firstName)); lastName.EnsureNotNullOrWhiteSpace(nameof(lastName)); var createBankAccount = !string.IsNullOrWhiteSpace(bankAccount) && !string.IsNullOrWhiteSpace(bankAccountCurrency); if (UserRepository.ByEmail(email) != null) { throw new BusinessException("Email is taken."); } if (createBankAccount && BankAccountService.Exists(bankAccount)) { throw new BusinessException("Bank account name is taken."); } if (!Enum.TryParse(role, out UserRole userRole)) { userRole = UserRole.Customer; } var(hash, salt) = CryptoHash.Pbkdf2Hash(password); var entity = new User { Email = email, Role = userRole, FirstName = firstName, LastName = lastName, PasswordSalt = salt.GetBase64String(), PasswordHash = hash.GetBase64String() }; UserRepository.Create(entity); UnitOfWork.SaveChanges(); int?bankAccountId = !createBankAccount ? (int?)null : BankAccountService.Create(bankAccount, bankAccountCurrency, entity.Id); return(entity.Id, bankAccountId); }
public bool SearchPass(string Login, string password, bool flag) { CryptoHash cr = new CryptoHash(); password = cr.Crypto(Login, password); int result = 0; try { string command = ""; if (flag) { command = "Select COUNT(User_id) FROM Users Where Login = '******' and password = '******';"; } else { command = "Select COUNT(Worker_id) FROM Worker Where Login = '******' and password = '******';"; } MySqlCommand cmd2 = new MySqlCommand { Connection = conn, CommandText = string.Format(command) }; MySqlDataReader reader = cmd2.ExecuteReader(); while (reader.Read()) { result = reader.GetInt32(0); } reader.Close(); } catch (Exception) { } if (result == 1) { return(true); } else { return(false); } }
public Tuple <ulong, ulong?, string> logar(Login login) { username = username.ToUpperInvariant(); List <Usuario> listaUsuario = new List <Usuario>(1); try { using (Conexao.GetInstance) { Conexao.Abrir(); ICRUD <Usuario> ControllerUsuario = new CtrlUsuario(Conexao.GetInstance); listaUsuario = ControllerUsuario.Listar().ToList(); Conexao.Fechar(); } } catch (Exception ex) { return(new Tuple <ulong, ulong?, string>(0, 0, ex.ToString())); } foreach (Usuario usuario in listaUsuario) { string curStoredUsername = usuario.Login.ToUpperInvariant(); storedPassword = usuario.Senha; if (curStoredUsername == username) { //OBS: IdUsuario e IdAcesso deveriam ser do tipo 'ulong' e 'ulong?', não 'int' e 'int?'. id = (ulong)usuario.IdUsuario; idAcesso = (ulong)usuario.IdAcesso; validouSenha = CryptoHash.Verify(storedPassword, password); } else { CryptoHash.Verify(storedPassword, password); } } if (validouSenha) { return(new Tuple <ulong, ulong?, string>(id, idAcesso, username)); } return(new Tuple <ulong, ulong?, string>(0, 0, null)); }
public async Task <User> LoginToAtm(dynamic data) { try { string cardNum = data["number"]; string pin = data["pincode"]; var card = await _unitOfWork.Repository <Card>().GetAsync( c => c.Number == cardNum && c.PinHash == CryptoHash.ComputeHash(pin, new MD5CryptoServiceProvider())); var ac = await _unitOfWork.Repository <Account>().GetAsync( acc => acc.Id == card.AccountId); return(await _unitOfWork.Repository <User>().GetAsync( user => user.Passport == ac.OwnerPassport)); } catch (InvalidOperationException) { throw new Exception("Incorrect card number or pincode"); } }
private static byte[] SodiumHash(HashType hash, byte[] buffer) { switch (hash) { case HashType.Blake2B: return(Blake2B.ComputeHash(buffer)); case HashType.SipHash24: return(ShortHash.Hash(buffer, SipHash24Key)); case HashType.Sha256: return(CryptoHash.Sha256(buffer)); case HashType.Sha512: return(CryptoHash.Sha512(buffer)); case HashType.Md5: case HashType.Sha1: case HashType.Sha384: default: throw new NotSupportedException(); } }
/// <summary> /// Run the application. /// </summary> public override BoolMessageItem Execute() { //<doc:example> // 1. Encrypt using default provider. ( Symmetric TripleDes ) string plainText = "www.knowledgedrink.com"; string encrypted = Crypto.Encrypt(plainText); string decrypted = Crypto.Decrypt(encrypted); Console.WriteLine("===================================================="); Console.WriteLine("CRYPTOGRAPHY "); Console.WriteLine("Encrypted : " + plainText + " to " + encrypted); Console.WriteLine("Decrypted : " + encrypted + " to " + decrypted); Console.WriteLine(Environment.NewLine); // 2. Use non-static encryption provider. ICrypto crypto = new CryptoHash("commonlib.net", new MD5CryptoServiceProvider()); string hashed = crypto.Encrypt("my baby - 2002 honda accord ex coupe"); Console.WriteLine(hashed); // 3. Change the crypto provider on the static helper. ICrypto crypto2 = new CryptoSym("new key", new TripleDESCryptoServiceProvider()); Crypto.Init(crypto2); string encryptedWithNewKey = Crypto.Encrypt("www.knowledgedrink.com"); Console.WriteLine(string.Format("Encrypted text : using old key - {0}, using new key - {1}", encrypted, encryptedWithNewKey)); // 4. Generate the check value of a 3DES key by encrypting 16 hexadecimal zeroes. DESKey randomKey = new DESKey(DesKeyType.TripleLength); string keyCheckValue = ComLib.Cryptography.DES.TripleDES.Encrypt(randomKey, "0000000000000000"); Console.WriteLine(string.Format("3DES key: {0} with check value {1}", randomKey.ToString(), keyCheckValue)); //</doc:example> return(BoolMessageItem.True); }
public string adicionarUsuario(Registrar registrar) { email = email.ToLowerInvariant(); username = username.ToUpperInvariant(); Regex regex = new Regex("[^A-Z0-9_]"); Regex emailRegex = new Regex("[^a-z0-9_.@]"); string regexedUsername = regex.Replace(username, String.Empty); usuario.Login = regexedUsername; string regexedEmail = emailRegex.Replace(email, String.Empty); if (regexedEmail != email) { return("Email inválido. Tente novamente." + email + regexedEmail); } List <Usuario> listaUsuario = new List <Usuario>(1); try { using (Conexao.GetInstance) { Conexao.Abrir(); string curStoredUsername = usuario.Login.ToUpperInvariant(); string curStoredEmail = usuario.Email.ToLowerInvariant(); ICRUD <Usuario> ControllerUsuario = new CtrlUsuario(Conexao.GetInstance); listaUsuario = ControllerUsuario.Listar().ToList(); foreach (Usuario usuario in listaUsuario) { curStoredUsername = usuario.Login.ToUpperInvariant(); curStoredEmail = usuario.Email.ToLowerInvariant(); if (curStoredUsername == username || curStoredEmail == email) { //OBS: IdUsuario e IdAcesso deveriam ser do tipo 'ulong' e 'ulong?', não 'int' e 'int?'. return("Usuário ou email já registrados. Tente novamente."); } } CryptoHash cryptohash = new CryptoHash(password); string cryptoHashStr = cryptohash.GetCryptoHash(cryptohash); usuario.Senha = cryptoHashStr; ControllerUsuario.Criar(usuario); Conexao.Fechar(); if (regexedUsername != username) { return("Usuário " + usuario.Login + " continha caracteres não permitidos e foi modificado para " + regexedUsername + " e registrado com sucesso."); } else { return("Usuário " + usuario.Login + " registrado com sucesso"); } } } catch (Exception ex) { return(ex.Message); } }
public static string hash512(string message) { var hash = CryptoHash.Sha512(message); return(Encoding.UTF8.GetString(hash)); }
public static byte[] Sha256(this byte[] input) { return(CryptoHash.Sha256(input)); }
public void CryptoHashSHA512ArrayTest() { var actual = CryptoHash.SHA512(Encoding.ASCII.GetBytes("Adam Caudill")); CollectionAssert.AreEqual(Utilities.HexToBinary(SHA512_HASH), actual); }
static void Main(string[] args) { var str = CryptoSecureString.ToSecureString(new[] { 'h', 'i', 'r', 'o' }); char [] charArray = CryptoSecureString.CharacterData(str); string unsecure = CryptoSecureString.ConvertToUnsecureString(str); var rsaParameters = new CryptoRSAParameters(); rsaParameters.GenerateKeys(); Console.WriteLine($"Random {Convert.ToBase64String(CryptoRandom.Generate(32))}"); Console.WriteLine("-------------------------------------------"); var message = "Hiro universe"; var messageBytes = Encoding.UTF8.GetBytes(message); Console.WriteLine($"MD5 message: {message} hash: {Convert.ToBase64String(CryptoHash.Md5(messageBytes))}"); Console.WriteLine($"SHA1 message: {message} hash: {Convert.ToBase64String(CryptoHash.Sha1(messageBytes))}"); Console.WriteLine($"SHA256 message: {message} hash: {Convert.ToBase64String(CryptoHash.Sha256(messageBytes))}"); Console.WriteLine($"SHA512 message: {message} hash: {Convert.ToBase64String(CryptoHash.Sha512(messageBytes))}"); var key = CryptoRandom.Generate(32); Console.WriteLine($"HMAC MD5 message: {message} hash: {Convert.ToBase64String(CryptoHmac.Md5(messageBytes, key))}"); Console.WriteLine($"HMAC SHA1 message: {message} hash: {Convert.ToBase64String(CryptoHmac.Sha1(messageBytes, key))}"); Console.WriteLine($"HMAC SHA256 message: {message} hash: {Convert.ToBase64String(CryptoHmac.Sha256(messageBytes, key))}"); Console.WriteLine($"HMAC SHA512 message: {message} hash: {Convert.ToBase64String(CryptoHmac.Sha512(messageBytes, key))}"); Console.WriteLine("-------------------------------------------"); Console.WriteLine("Passsword hash with salt"); Console.WriteLine($"Password: {message}"); Console.WriteLine($"Password hashed: {Convert.ToBase64String(CryptoHash.Password(messageBytes))}"); Console.WriteLine("-------------------------------------------"); var salt = CryptoRandom.Generate(32); Console.WriteLine("Passsword hash with salt - Based Key Derivation Function - PBKDF2"); Console.WriteLine($"Password: {message}"); Console.WriteLine($"Password hashed 100 rounds: {Convert.ToBase64String(CryptoHash.Password(messageBytes, salt, 100))}"); Console.WriteLine($"Password hashed 1000 rounds: {Convert.ToBase64String(CryptoHash.Password(messageBytes, salt, 1000))}"); Console.WriteLine($"Password hashed 10000 rounds: {Convert.ToBase64String(CryptoHash.Password(messageBytes, salt, 10000))}"); Console.WriteLine("-------------------------------------------"); var desKey = CryptoRandom.Generate(8); var desIv = CryptoRandom.Generate(8); var desEncryptedMessage = CryptoDes.Encrypt(message, desKey, desIv); var desDecryptedMessage = CryptoDes.Decrypt(desEncryptedMessage, desKey, desIv); Console.WriteLine("DES Encryption"); Console.WriteLine($"Text: {message}"); Console.WriteLine($"Key: {Convert.ToBase64String(desKey)}"); Console.WriteLine($"IV: {Convert.ToBase64String(desIv)}"); Console.WriteLine($"Encrypted: {Convert.ToBase64String(desEncryptedMessage)}"); Console.WriteLine($"Decrypted: {desDecryptedMessage}"); Console.WriteLine("-------------------------------------------"); var tripleDesKey = CryptoRandom.Generate(16); var tripleDesIv = CryptoRandom.Generate(8); var tripleDesEncryptedMessage = CryptoTripleDes.Encrypt(message, tripleDesKey, tripleDesIv); var tripleDesDecryptedMessage = CryptoTripleDes.Decrypt(tripleDesEncryptedMessage, tripleDesKey, tripleDesIv); Console.WriteLine("Triple DES Encryption"); Console.WriteLine($"Text: {message}"); Console.WriteLine($"Key: {Convert.ToBase64String(tripleDesKey)}"); Console.WriteLine($"IV: {Convert.ToBase64String(tripleDesIv)}"); Console.WriteLine($"Encrypted: {Convert.ToBase64String(tripleDesEncryptedMessage)}"); Console.WriteLine($"Decrypted: {tripleDesDecryptedMessage}"); Console.WriteLine("-------------------------------------------"); var aesKey = CryptoRandom.Generate(32); var aesIv = CryptoRandom.Generate(16); var aesEncryptedMessage = CryptoAes.Encrypt(message, aesKey, aesIv); var aesDecryptedMessage = CryptoAes.Decrypt(aesEncryptedMessage, aesKey, aesIv); Console.WriteLine("AES Encryption"); Console.WriteLine($"Text: {message}"); Console.WriteLine($"Key: {Convert.ToBase64String(aesKey)}"); Console.WriteLine($"IV: {Convert.ToBase64String(aesIv)}"); Console.WriteLine($"Encrypted: {Convert.ToBase64String(aesEncryptedMessage)}"); Console.WriteLine($"Decrypted: {aesDecryptedMessage}"); Console.WriteLine("-------------------------------------------"); var rsaEncryptedMessage = CryptoRsa.Encrypt(messageBytes, rsaParameters.publicKey); var rsaDecryptedMessage = CryptoRsa.Decrypt(rsaEncryptedMessage, rsaParameters.privateKey); Console.WriteLine("RSA Encryption"); Console.WriteLine($"Text: {message}"); Console.WriteLine($"Encrypted: {Convert.ToBase64String(rsaEncryptedMessage)}"); Console.WriteLine($"Decrypted: {Encoding.Default.GetString(rsaDecryptedMessage)}"); Console.WriteLine("-------------------------------------------"); var hybridEncryptedPacket = CryptoHybrid.Encrypt(message, rsaParameters.publicKey); var hybridDecryptedMessage = CryptoHybrid.Decrypt(hybridEncryptedPacket, rsaParameters.privateKey); Console.WriteLine("Hybrid Encryption using AES and RSA"); Console.WriteLine($"Text: {message}"); Console.WriteLine($"Encrypted: {Convert.ToBase64String(hybridEncryptedPacket.EncryptedData)}"); Console.WriteLine($"Decrypted: {hybridDecryptedMessage}"); Console.WriteLine("-------------------------------------------"); var hashedMessage = CryptoHash.Sha256(messageBytes); var signature = CryptoDigitalSignature.Sign(hashedMessage, rsaParameters.privateKey); var verify = CryptoDigitalSignature.Verify(hashedMessage, signature, rsaParameters.publicKey); Console.WriteLine("Digital Signature"); Console.WriteLine($"Text: {message}"); Console.WriteLine($"Signature: {Convert.ToBase64String(signature)}"); Console.WriteLine("Is Verified: " + (verify ? "true" : "false")); Console.WriteLine("-------------------------------------------"); try { var hybridSignatureEncryptedPacket = CryptoHybridIntegrity.Encrypt(message, rsaParameters); var hybridSignatureDecryptedMessage = CryptoHybridIntegrity.Decrypt(hybridSignatureEncryptedPacket, rsaParameters); Console.WriteLine("Hybrid encryption with digital signature"); Console.WriteLine($"Text: {message}"); Console.WriteLine($"Signature: {Convert.ToBase64String(hybridSignatureEncryptedPacket.Signature)}"); Console.WriteLine($"Encrypted: {Convert.ToBase64String(hybridSignatureEncryptedPacket.EncryptedData)}"); Console.WriteLine($"Decrypted: {hybridSignatureDecryptedMessage}"); } catch (CryptographicException ex) { Console.WriteLine("Error : " + ex.Message); } }
public void CryptoHashSha256ArrayTest() { var actual = CryptoHash.Sha256(Encoding.UTF8.GetBytes("Adam Caudill")); CollectionAssert.AreEqual(Utilities.HexToBinary(SHA256_HASH), actual); }
public void CryptoHashSha256StringTest() { var actual = CryptoHash.Sha256("Adam Caudill"); CollectionAssert.AreEqual(Utilities.HexToBinary(SHA256_HASH), actual); }
public void Md5ShouldEncodeString() { var result = CryptoHash.Md5("test"); Assert.That(result, Is.Not.Null); }
private void Button1_Click(object sender, EventArgs e) { switch (UserType) { case 0: //////ADMIN { if (ConfirmedAdmin) { if (ConfirmedLogin) { if (ConfirmedPassword) { if (textBox1.Text != " " && textBox2.Text != " " && textBox4.Text != " " && dateTimePicker1.Text != " " && textBox7.Text != " " && textBox5.Text != " " && textBox3.Text != " " && textBox9.Text != " " && textBox9.Text != " " && textBox1.Text != "" && textBox2.Text != "" && textBox4.Text != "" && dateTimePicker1.Text != "" && textBox7.Text != "" && textBox5.Text != "" && textBox3.Text != "" && textBox9.Text != "" && textBox9.Text != "" ) { try { CryptoHash cr = new CryptoHash(); string pass = cr.Crypto(textBox3.Text, textBox6.Text); /////////////////////Password string sql = "insert into Users(User_id, User_name, User_surname," + " User_fname, Birthdate, Phone, Login, Password, Adress, Email) values (null, '" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox4.Text + "', '" + dateTimePicker1.Text + "', '" + textBox7.Text + "', '" + textBox3.Text + "', '" + pass + "', '" + textBox9.Text + "', '" + textBox10.Text + "')"; MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.ExecuteNonQuery(); MessageBox.Show("Реєстрація була успішною!"); conn.Close(); LogIn lg = new LogIn(); lg.Show(); this.Close(); } catch (Exception) { } } else { MessageBox.Show("Не всі поля заповнені! Будь-ласка, перевірте правильність завонення полів!"); } } else { MessageBox.Show("Помилка паролю!"); } } else { MessageBox.Show("Помилка логіну!"); } } else { MessageBox.Show("Адміністратор не підтвердив паролю!"); } break; } case 1: //////USER { if (ConfirmedLogin) { if (ConfirmedPassword) { if (ConfirmedEmail) { if (textBox1.Text != " " && textBox2.Text != " " && textBox4.Text != " " && dateTimePicker1.Text != " " && textBox7.Text != " " && textBox5.Text != " " && textBox3.Text != " " && textBox9.Text != " " && textBox9.Text != " " && textBox1.Text != "" && textBox2.Text != "" && textBox4.Text != "" && dateTimePicker1.Text != "" && textBox7.Text != "" && textBox5.Text != "" && textBox3.Text != "" && textBox9.Text != "" && textBox9.Text != "" ) { try { CryptoHash cr = new CryptoHash(); string pass = cr.Crypto(textBox3.Text, textBox6.Text); /////////////////////Password string sql = "insert into Users(User_id, User_name, User_surname," + " User_fname, Birthdate, Phone, Login, Password, Adress, Email) values (null, '" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox4.Text + "', '" + dateTimePicker1.Text + "', '" + textBox7.Text + "', '" + textBox3.Text + "', '" + pass + "', '" + textBox9.Text + "', '" + textBox10.Text + "')"; MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.ExecuteNonQuery(); MessageBox.Show("Реєстрація була успішною!"); conn.Close(); LogIn lg = new LogIn(); lg.Show(); this.Close(); } catch (Exception) { } } else { MessageBox.Show("Не всі поля заповнені! Будь-ласка, перевірте правильність заповнення полів!"); } } else { MessageBox.Show("Помилка E-mail адреси!"); } } else { MessageBox.Show("Помилка паролю!"); } } else { MessageBox.Show("Помилка логіну!"); } break; } case 2: //////WORKER { if (ConfirmedLogin) { if (ConfirmedPassword) { if (textBox1.Text != " " && textBox2.Text != " " && textBox4.Text != " " && dateTimePicker1.Text != " " && textBox7.Text != " " && textBox5.Text != " " && textBox3.Text != " " && textBox11.Text != " " && comboBox3.Text != " " && textBox1.Text != "" && textBox2.Text != "" && textBox4.Text != "" && dateTimePicker1.Text != "" && textBox7.Text != "" && textBox5.Text != "" && textBox3.Text != "" && textBox11.Text != "" && comboBox3.Text != "" ) { try { CryptoHash cr = new CryptoHash(); string pass = cr.Crypto(textBox3.Text, textBox6.Text); /////////////////////Password int index = Office_ids[comboBox3.SelectedIndex]; string sql = "insert into Worker(Worker_id, Worker_name, Worker_surname," + "Worker_fname, Birthdate, Phone, Login, Password, Worker_proffession, Office_id) values (null, '" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox4.Text + "', '" + dateTimePicker1.Text + "', '" + textBox7.Text + "', '" + textBox3.Text + "', '" + pass + "', '" + textBox11.Text + "', '" + index + "')"; MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.ExecuteNonQuery(); //INSERT INTO Orders VALUES (null, 1, 1, 5, 'AN55SLRT12FF', 2, 'TEST', '2017:01:01', 'NULL', 10, 0); MessageBox.Show("Реєстрація була успішною!"); int worker_id = 0; cmd = new MySqlCommand { Connection = conn, CommandText = string.Format("SELECT MAX(Worker_id) FROM Worker;") }; MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { worker_id = reader.GetInt32(0); } sql = "iINSERT INTO Orders(Order_id, User_id, Service_id, Worker_id, Serial_number" + "Status_id,Description,Order_Date, Complete_set, Appearance, Order_price) VALUES (null, 1, 1, " + worker_id + ", 'AN55SLRT12FF', 2, 'TEST', '2017:01:01', 'NULL', 10, 0);"; cmd = new MySqlCommand(sql, conn); cmd.ExecuteNonQuery(); reader.Close(); conn.Close(); LogIn lg = new LogIn(); lg.Show(); this.Close(); } catch (Exception) { } } else { MessageBox.Show("Не всі поля заповнені! Будь-ласка, перевірте правильність заповнення полів!"); } } else { MessageBox.Show("Помилка пароля!"); } } else { MessageBox.Show("Помилка логіну!"); } break; } default: { MessageBox.Show("Користувач не обраний!"); break; } } }