private static void RSA_Test() { //RSAEncryption GenPrivateKeyc = new RSAEncryption(4096, true); //GenPrivateKeyc.GeneratePrivateKey(); //string PrivateKey = GenPrivateKeyc.PrivateKey; int BitSize = 4096; string PreGenPrivateKey = @"<RSAKeyValue> <Modulus>1ClYJTeXDkbppKjvJqC3xf+E4P4eVa4lwvFmdGTsqDdJoT+RMvLg/WkrWsCEASmxaj3ohlg1kBhSv2ZXuZlH90Roba5EWOxD1EQUDjk0e711ga0YVwZF5UUo9yx+Lo1QR3ErmeNMOkJDa0IZVnmuILgdaTFBdBm2ZYdJVnpeB+BIycNT0vAoqtwdDZXySjAzfl6nL6WsNw/XqJMIDuFcIt8hv6vghFtpiQXeWEsuZq3DQPlCu0oJDYuoAaRU5KxOIakbTzpTS11eBx+w1PDgd+VCAEVbx71sqjSFsAOEvmm4A0lRBRnQuJOdoGLNFoSePDGP9J88KfIfosMtAqFDUX2/8EsAc6B3QnpQ0un5vC2Au0xUDY0fwsKtN9yvFQPw10eRXEV+Smz4pBH+4gOEKi0RxNt3chKa0qqGG9I/CqL1/PPEtvN31Bjxc4H2vAyW3XMRNs7o9pktimaRNpwZ6sbBDi2eNY6Ty5ff7jHv0uy9DRQsreTewhXvZK6M8OcBUxLp1tkzi9zTBKTPTMXAuUF1oWDJktWDBuGnxbZcTfTvJ0X3zS8/mXdsUHsgV5vcGeT+2hZLQnskrwlbxt4QjEHSl0hgWM9i5Yhd+ltlg/9URvZdnkh5pKoShJR4OWNSBsI3kwRzwPHAKag8J4TSFIgZXCkSvtTlsM6v44f8pNU=</Modulus> <Exponent>AQAB</Exponent> <P>3cBHXk4SpnPWskCpGfJbW5u5XO3q1srmsW9XCDwo4HWezMaIjznjcwd46W50nUAkfS6zt91Ez7xPzWg0+kTrLwJEnAwLb5rYk7aGk29G8Vz0DW6rBnzT8hIxgdAnRUk/Htxkee1k8aHdL5kDUkfBDX1sRxi20A8bNHG039oq0joxkQKO8nrctIxHLiTtPXUH1R3AZ4+35keONp4iRBvKudPl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nHPn5MILmAcE2vYhv9bRgwUF8LRT4GkP9IW2g48WabzLhIdSu/azjT2GBnkMwz5FcwPYiFvQc3fquqVWhn9PqGN5tHq6LhE=</D> </RSAKeyValue>"; RSAEncryption A_Rsa = new RSAEncryption(BitSize, "", PreGenPrivateKey, true); //When generating, only the modulus and Exponent should be made public, nothing else string PublicKeyFromA = A_Rsa.GeneratePublicKey(); string TestData = "Helllo, This is A, let's hope this message arrived well"; byte[] EncryptedData = A_Rsa.Encrypt(ASCIIEncoding.ASCII.GetBytes(TestData), 0, TestData.Length); byte[] SignedData = A_Rsa.SignData(ASCIIEncoding.ASCII.GetBytes(TestData)); RSAEncryption B_Rsa = new RSAEncryption(BitSize, A_Rsa.PublicParameters.Value.Modulus, A_Rsa.PublicParameters.Value.Exponent, true); byte[] DecryptedData = B_Rsa.Decrypt(EncryptedData, 0, EncryptedData.Length); }
/* * Default role is user * 1 - admin * 2 - doctor * 3 - patient */ public void Add(string login, string password, int roleId = 3) { DataConnection.DefaultSettings = new MySettings(_test); using var db = new DbDoctor(); db.Users .Value(user => user.Login, login) .Value(user => user.Password, RSAEncryption.Encrypt(password)) .Value(user => user.RoleId, roleId) .Insert(); }
public void ExecuteEncrypt() { if (string.IsNullOrEmpty(publicKeyText.text)) { return; } string planeText = textInput.text; string encrypted = RSAEncryption.Encrypt(planeText, publicAndPrivateKeyValuePair.Key); resultText.text = encrypted; }
public void LoginExecuteChanged() { if (string.IsNullOrEmpty(UserName)) { MessageBox.Show("用户名不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (string.IsNullOrEmpty(Password)) { MessageBox.Show("用户名不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (!string.IsNullOrEmpty(UserNameTemp)) { if (UserNameTemp != UserName || Passwordtemp != Password) { MessageBox.Show("用户名或密码不正确!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } _scoketManager = ScoketManager.GetInstance(); string socketUrl = ConfigurationManager.AppSettings["QuotesAddress"]; if (!_scoketManager.StartQuotesSocket(socketUrl)) { MessageBox.Show("行情服务器无法连接,请检查服务器,重新登录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (IsSave) { IniHelper.ProfileWriteValue("User", "Username", UserName, IniHelper.configpath); string pasword = RSAEncryption.Encrypt(Password); IniHelper.ProfileWriteValue("User", "Password", pasword, IniHelper.configpath); } else { IniHelper.ProfileWriteValue("User", "Username", "", IniHelper.configpath); IniHelper.ProfileWriteValue("User", "Password", "", IniHelper.configpath); } KeyCodeValue.AddKeys(); //MainWindow main = new MainWindow(); //ContractVariety.main = main; //main.Show(); this.Close(); }
protected void Page_Load(object sender, EventArgs e) { Random rRandom; rRandom = new Random(); // populate the variables m_szFirstVariable = PopulateVariable(FirstVariableLabel, ModifiedFirstVariable, rRandom); m_szSecondVariable = PopulateVariable(SecondVariableLabel, ModifiedSecondVariable, rRandom); m_szThirdVariable = PopulateVariable(ThirdVariableLabel, ModifiedThirdVariable, rRandom); m_szForthVariable = PopulateVariable(ForthVariableLabel, ModifiedForthVariable, rRandom); m_szFifthVariable = PopulateVariable(FifthVariableLabel, ModifiedFifthVariable, rRandom); m_szSixthVariable = PopulateVariable(SixthVariableLabel, ModifiedSixthVariable, rRandom); m_szSeventhVariable = PopulateVariable(SeventhVariableLabel, ModifiedSeventhVariable, rRandom); m_szEighthVariable = PopulateVariable(EighthVariableLabel, ModifiedEighthVariable, rRandom); //-----------------------------------------------------------------------------------------------------------+ //Prep code was used to create the public and the private keys | //var rsa = new RSAEncryption(); | //rsa.AssignNewKey(Server.MapPath("~/Keys/publickey.xml"), Server.MapPath("~/Keys/privatekey.xml")); | //-----------------------------------------------------------------------------------------------------------+ // Step 1 -Create 32 byte session key var sessionKey = KeyGenerator.GenerateKey(); // Step 2 -Create 16 byte Initialisation Vector var iv = KeyGenerator.GenerateKey(16); // Step 3 -Encrypt the data using the session key and the IV. var data = Utils.BuildString(m_szFirstVariable, m_szSecondVariable, m_szThirdVariable, m_szForthVariable, m_szFifthVariable, m_szSixthVariable, m_szSeventhVariable, m_szEighthVariable); AESEncryption aes = new AESEncryption(); var encryptedData = aes.Enrypt(Encoding.UTF8.GetBytes(data), sessionKey, iv); // Step 4 -Hash the encrypted data using the session key byte[] hashedData = HashGenerator.ComputeHmacSha256(encryptedData, sessionKey); // Step 5 -Encrypt the session Key using the receiver's public key(created and stored safely before, in real life scenario will two different servers). RSAEncryption rsa = new RSAEncryption(); var encryptedSessionKey = rsa.Encrypt(Server.MapPath("~/Keys/publickey.xml"), sessionKey); // Step 6 -Setting the values that will be stored in the hidden values. hdEncryptedSessionKey.Value = Convert.ToBase64String(encryptedSessionKey); hdEncryptedData.Value = Convert.ToBase64String(encryptedData); hdIv.Value = Convert.ToBase64String(iv); // IV Doesn't need to be encrypted. hdHashedData.Value = Convert.ToBase64String(hashedData); }
public IActionResult Register(SignInUser signInUser) { if (ModelState.IsValid) { try { RSAEncryption encryption = new RSAEncryption(); signInUser.Pwd = System.Text.Encoding.UTF8.GetString(encryption.Encrypt(signInUser.Pwd)); authRepository.Register(signInUser); return(RedirectToAction("Login")); } catch (Exception) { return(View("Error")); } } return(View(signInUser)); }
public void Update(int id, string?password = null, int?roleId = null) { DataConnection.DefaultSettings = new MySettings(_test); using var db = new DbDoctor(); var user = Get(id); if (password != null) { user.Password = RSAEncryption.Encrypt(password); } if (roleId != null) { user.RoleId = (int)roleId; } db.Update(user); }
/// <summary> /// Encrypt: Asymmetrical encryption of a string using public RSA key /// </summary> /// <param name="data"></param> /// <returns></returns> public static string Encrypt(string data) { try { if (EncryptionEnabled) { if (string.IsNullOrEmpty(_public)) { return("You need to set the public key in the configuration for encryption to work correctly. [Missing AppSetting.RSA_PUBLIC_KEY]"); } return(RSAEncryption.Encrypt(data, _public)); } return(data); } catch (Exception exception) { // ExceptionHelper.Capture(exception); return("Encryption failed. " + exception.Message); } }
/// <summary> /// NewKey method implementation /// </summary> public override string NewKey(string upn) { if (string.IsNullOrEmpty(upn)) { return(null); } string lupn = upn.ToLower(); byte[] crypted = null; using (var prov = new RSAEncryption(_xorsecret, _certificatethumbprint)) { crypted = prov.Encrypt(lupn); if (crypted == null) { return(null); } } string outkey = AddStorageInfos(crypted); return(KeysStorage.NewUserKey(lupn, outkey)); }
/// <summary> /// NewKey method implementation /// </summary> public override string NewKey(string upn) { if (string.IsNullOrEmpty(upn)) { return(null); } string lupn = upn.ToLower(); byte[] crypted = null; using (var prov = new RSAEncryption(_xorsecret)) { prov.Certificate = KeysStorage.CreateCertificate(lupn, _validity, true); crypted = prov.Encrypt(lupn); if (crypted == null) { return(null); } string outkey = AddStorageInfos(crypted); return(KeysStorage.NewUserKey(lupn, outkey, prov.Certificate)); } }
/// <summary> /// 向文件中写入数据流 /// </summary> private void WriteFileStream() { try { string saveStr = string.Empty; foreach (var da in UserInfoData) { saveStr += da + ";"; } saveStr = RSAEncryption.Encrypt(saveStr.TrimEnd(';')); using (FileStream fs = new FileStream(FilePath, FileMode.Create, FileAccess.Write)) { byte[] bytes = new byte[saveStr.ToArray().Length]; bytes = Encoding.UTF8.GetBytes(saveStr); fs.Write(bytes, 0, bytes.Length); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
static string EncryptString(string laneCode, string cardNumber, DateTime expiryDate) { if (string.IsNullOrWhiteSpace(cardNumber)) { return(null); } const int dwKeySize = 1024; string keyXML = LookupManager.LaneEncryptionKeys(laneCode); if (string.IsNullOrEmpty(keyXML)) { throw new Exception("No RSA XML public key defined: 'PublicRSAKey' in LaneConfiguration is null or empty"); } RSAEncryption Encryptor = new RSAEncryption(dwKeySize, keyXML); //expiryDate = (DateTime)expiryDate; var inputString = cardNumber + "," + expiryDate.Year + "/" + expiryDate.Month; return(Encryptor.Encrypt(inputString)); }
public override bool onHandshake() { DiffieHellman diffieHellman = new DiffieHellman(256); //send RSA public key RSAEncryption RSA = KeyHandler.GetPrivateKey(); base.SendMessage(new MsgRsaPublicKey(RSA.Parameters)); //Calculate and apply the public key as key //If the key is spoofed the next packet that's being send could fail if public key is generated wrong :) byte[] SecretHash = SHS_KeyExchange.CalculateSecretHash(RSA.Parameters.Modulus, RSA.Parameters.Exponent); Client.Connection.protection.ApplyPrivateKey(SecretHash);//apply our secret hash based on the public key //generate a big random key byte[] encryptionKey = new byte[65535]; new Random(DateTime.Now.Millisecond).NextBytes(encryptionKey); //encrypt the key with RSA byte[] cryptedKey = RSA.Encrypt(encryptionKey, 0, encryptionKey.Length); diffieHellman = KeyHandler.GetDiffieHellman(); byte[] diffieStr = diffieHellman.GetDiffie(); long index = Client.PrivateKeyOffset % 65535; if (index <= 4) { index = 10; } byte[] diffieLen = BitConverter.GetBytes(diffieStr.Length); //create a backup of encrypted RSA data //byte[] RsaBackup = new byte[diffieLen.Length + diffieStr.Length]; //Array.Copy(cryptedKey, index - 4, RsaBackup, 0, RsaBackup.Length); //Rsa Backup Data Array.Copy(diffieLen, 0, cryptedKey, index - 4, diffieLen.Length); //write Diffie-Hellman key length Array.Copy(diffieStr, 0, cryptedKey, index, diffieStr.Length); //copy the diffie-hellman key in between random data //maybe not secure adding this at the end of the encrypted data but whatever for now //Array.Resize(ref cryptedKey, cryptedKey.Length + RsaBackup.Length); //Array.Copy(RsaBackup, 0, cryptedKey, cryptedKey.Length - RsaBackup.Length, RsaBackup.Length); uint KeyHash = BitConverter.ToUInt32(new CRC32().ComputeHash(cryptedKey), 0); CertInfo certificate = new CertInfo(serverProperties.ServerCertificate); certificate.FingerPrintMd5 = BitConverter.ToString(MD5.Create().ComputeHash(serverProperties.ServerCertificate.PrivateKey)).Replace("-", ""); certificate.FingerPrintSha1 = BitConverter.ToString(SHA1.Create().ComputeHash(serverProperties.ServerCertificate.PrivateKey)).Replace("-", ""); certificate.KeyAlgorithm = "RSA with " + Connection.RSA_KEY_SIZE + "bit"; certificate.Compression = ""; //serverProperties.Compression.ToString(); certificate.Cipher = ""; // serverProperties.Encryption.ToString(); certificate.HandshakeMethod = "RSA" + Connection.RSA_KEY_SIZE + "-DiffieHellman-AES256"; if (!serverProperties.ServerCertificate.ShowProtectionMethods) { certificate.Cipher = ""; certificate.Compression = ""; certificate.HandshakeMethod = ""; certificate.KeyAlgorithm = ""; } Client.Certificate = certificate; //Convert bytes to UINT uint[] TempKey = new uint[SecretHash.Length]; for (int i = 0; i < TempKey.Length; i++) { TempKey[i] = SecretHash[i]; } //Encrypt the diffie-hellman key with our SecretHash which is generated by our Public RSA UnsafeXor XorEncryption = new UnsafeXor(TempKey, true); XorEncryption.Encrypt(ref cryptedKey, 0, cryptedKey.Length); //send encryption info + diffie-hellman base.SendMessage(new MsgServerEncryption(serverProperties.AllowUdp, certificate, cryptedKey, KeyHash)); //apply the Encrypted Key, Yes the Encrypted Key, if spoofed the key should change at the client side ;) Client.Connection.protection.ApplyPrivateKey(cryptedKey); if (!base.ReceiveMessage((IMessage message) => { MsgDiffiehellman diffie = message as MsgDiffiehellman; if (diffie != null) { try { diffieHellman.HandleResponse(new PayloadReader(diffie.DiffieHellman)); Client.Connection.protection.ApplyPrivateKey(diffieHellman.Key); //apply diffie-hellman key return(true); } catch { return(false); } } return(false); }).Wait <bool>(false, 30000)) { Client.Disconnect(DisconnectReason.TimeOut); Client.onException(new Exception("Handshake went wrong, SHS_KeyExchange"), ErrorType.Core); return(false); } return(true); }
/// <summary> /// 字符串 RSA 加密 /// </summary> /// <param name="text">需要加密的文本</param> /// <param name="publicKey">公钥</param> /// <returns></returns> public static string ToRSAEncrpyt(this string text, string publicKey) { return(RSAEncryption.Encrypt(text, publicKey)); }
static string _EncryptConfig(string start, string key) { return(start + EncryptSplit + RSAEncryption.Encrypt(EncryptKey, key)); }
public void EncryptedPAN(ref ITollTransaction transaction) { RSAEncryption Encryptor = new RSAEncryption(1024, Settings.EncryptionKey); transaction.PaymentDetail = Encryptor.Encrypt(transaction.PaymentDetail); }
public AuthenticateResult Authenticate(LoginModel logonModel) { if (logonModel != null) { User user = null; if (!string.IsNullOrEmpty(logonModel.Token)) { string tokenText = RSAEncryption.Decrypt(logonModel.Token); ApiToken token; if (ApiToken.TryParse(tokenText, out token)) { if (token.AuthenticationTime > DateTime.Today.AddDays(-10)) { user = _userRepository.GetUser(token.UserId); } } } else { user = _userRepository.GetUser(logonModel.Username); if (user != null) { if (user.Password != logonModel.Password) { return(new AuthenticateResult(false, null) { Message = "invalid password" }); } } } if (user != null) { ApiToken token = new ApiToken() { UserId = user.Id, UserName = user.Username, Timezone = user.Timezone, Language = user.Language, //Roles = SerializeRoles(user.StaffAtBusinesses), AuthenticationTime = DateTime.Now }; string encryptedToken = RSAEncryption.Encrypt(token.ToString()); user.Password = null; // clear password AuthenticateResult result = new AuthenticateResult(true, encryptedToken) { User = new UserDTO(user) }; return(result); } } return(new AuthenticateResult(false, null) { Message = "invalid login" }); }
public static string GetSrc(ServiceUser user) { return(RSAEncryption.Encrypt(Base64Encryption.Decrypt(PublicKey), user.ToJson())); }