internal void OnDeserialized(StreamingContext context) { if (tsid != null && tsid.IsOk) { SessionId = tsid.SessionId; } else { // decrypt session if (MasterKey == null) { return; } var str = String.Format(@"{{""val"":""{0}""}}", privk); var helper = JsonConvert.DeserializeObject <PrivateKeyHelper>(str, new PrivateKeyConverter(MasterKey.Value)); PrivateKey = helper.val; if (PrivateKey == null) { return; } var sid = csid.ModPow(PrivateKey.D, PrivateKey.N); // val, exp, mod //var sid = BigInteger.ModPow(csid, PrivateKey.D, PrivateKey.N); var reversedBytes = sid.GetBytes(); var shift = reversedBytes[reversedBytes.Length - 1] == 0 ? 1 : 0; SessionId = Transport.Encode(reversedBytes // .Reverse() // .Skip(shift) .Take(43) .ToArray()); } }
private void Load() { if (_loaded) { return; } _loaded = true; using (XmlReader reader = XmlReader.Create(_stream, new XmlReaderSettings() { CloseInput = false })) { reader.MoveToContent(); reader.ReadStartElement("keyset"); reader.ReadToFollowing("client"); _client = new RSAKey(reader); reader.ReadToFollowing("server"); _server = new RSAKey(reader); reader.ReadEndElement(); } }
public void Encrypt(string inputPath, string outputPath, IKey key, Action <double> ProgressChanged = null) { if (key is RSAKey == false) { throw new ArgumentException("Key is not RSAKey"); } RSAKey rsaKey = key as RSAKey; using FileStream instream = File.OpenRead(inputPath); using FileStream outstream = File.Open(outputPath, FileMode.Create); long fileSize = instream.Length; byte[] inputChunk = new byte[rsaKey.MaxOpenTextSize]; byte[] outputChunk = new byte[rsaKey.MaxCipherTextSize]; while (instream.Read(inputChunk, 0, rsaKey.MaxOpenTextSize) != 0) { outputChunk = Encrypt(inputChunk, rsaKey); outstream.Write(outputChunk, 0, outputChunk.Length); int percent = (int)((instream.Position * 100f) / fileSize); ProgressChanged?.Invoke(percent); } instream.Close(); outstream.Close(); }
public void GenerateKeys() { random = new Random((int)DateTime.Now.Ticks % Int32.MaxValue); simpleList = GenerateSimpleNumbersList(1000); Int64 P = GenerateRandomNumberInt16(); Int64 Q = P; while (P == Q) { Q = GenerateRandomNumberInt16(); } Int64 N = P * Q; Int64 M = (P - 1) * (Q - 1); Int64 E = 0; do { E = GenerateRandomNumberInt32(); } while (EuclidsAlgorithm(E, M) != 1); Int64 D = ExtendedEuclid(E, M); RSAKey publicKey = new RSAKey(); publicKey.data = E; publicKey.N = N; RSAKey privateKey = new RSAKey(); privateKey.data = D; privateKey.N = N; KeyFileWriter.WriteKey(publicKey, PUBLIC_KEY_FILE_NAME); KeyFileWriter.WriteKey(privateKey, PRIVATE_KEY_FILE_NAME); }
public static void WriteKey(RSAKey key, string fileName) { using (StreamWriter streamWriter = new StreamWriter(fileName)) { streamWriter.Write("{0} {1}", key.data, key.N); } }
private void CreateNewKey() { RsaKey = new RSAKey(); if (!RsaKey.ReadConfig("config.rsa")) { RsaKey = RSAKeyGenerator.GenerateKeyPair(1024); } ReadKeysFromFile(); }
// GET: /<controller>/ public IActionResult Index() { RSAKey rsaKey = RSAHelper.CreateRsaKey(); ViewData["publicKey"] = rsaKey.PublicKey; HttpContext.Session.SetString("privateKey", rsaKey.PrivateKey); return(View()); }
public void SendUpdateUserRSAKey(string loginName, RSAKey key) { if (string.IsNullOrEmpty(loginName) || key == null) { return; } _mq.BasicPublish( routingKey: MqKeyword.UpdateUserRSAKeyRoutingKey, basicProperties: CreateBasicProperties(loginName), body: UserMqBodyUtil.GetUpdateUserRSAKeyMqSendBody(key)); }
private void button3_Click(object sender, EventArgs e) { RSAKey key = rsa.Key; listBox1.Items.Add("RSA n: " + key.n); listBox1.Items.Add("RSA e: " + key.e); listBox1.Items.Add("RSA d: " + key.d); listBox1.Items.Add("ECB Key: " + ecbKey); listBox1.Items.Add("Public ECB Key: " + publicDes); listBox1.Items.Add("Certificate: " + certificate); }
/// <summary> /// Writes a copy of this key into the local Csp store with the given options /// </summary> public void WriteToStore(string name, CspProviderFlags flags) { CspParameters cp = new CspParameters(); cp.KeyContainerName = name; cp.Flags = flags; RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cp); csp.ImportCspBlob(RSAKey.ExportCspBlob(IsPrivateKey)); csp.PersistKeyInCsp = true; csp.Clear(); }
public void SendUpdateUserRSAKey(string loginName, RSAKey key) { if (string.IsNullOrEmpty(loginName) || key == null) { return; } _serverConnection.MqChannel.BasicPublish( exchange: MqKeyword.NTMinerExchange, routingKey: MqKeyword.UpdateUserRSAKeyRoutingKey, basicProperties: CreateBasicProperties(loginName), body: UserMqBodyUtil.GetUpdateUserRSAKeyMqSendBody(key)); }
public void Run(ModuleInfo info, CancellationToken token = default(CancellationToken)) { BigInteger publicK = BigInteger.Parse(info.Parent.ReadString()); BigInteger shared = BigInteger.Parse(info.Parent.ReadString()); string text = info.Parent.ReadString(); RSAKey publicKey = new RSAKey(publicK, shared); var result = RSAProvider.Encrypt2(text, publicKey); var trueResult = result.Aggregate((x, y) => x + "." + y); info.Parent.WriteData(trueResult.ToString()); }
/// <summary> /// 获取秘钥 /// </summary> /// <param name="path"></param> /// <returns></returns> public static RSAKey GetRSAKey(string path) { RSAKey key = new RSAKey(); if (File.Exists(Path.Combine(path, publicKeyFileName))) { key.PublicKey = Convert.ToBase64String(File.ReadAllBytes(Path.Combine(path, publicKeyFileName))); } if (File.Exists(Path.Combine(path, privateKeyFileName))) { key.PrivateKey = Convert.ToBase64String(File.ReadAllBytes(Path.Combine(path, privateKeyFileName))); } return(key); }
//*********************************************************** //METODOS que se repiten //*********************************************************** //Generación de Llaves RSA Maestro/Esclavo public void generarLlavesRSA() { var llaves = new RSAKey(); var Items = llaves.get(); ClavePublica = Items.ExportParameters(false); ClavePrivada = Items.ExportParameters(true); ClavePublicaString = Items.ToXmlString(false); valorClavePublica.Text = ClavePublicaString; valorClavePrivada.Text = Items.ToXmlString(true); valorClavePublicaEsclavo.Text = ClavePublicaString; valorClavePrivadaEsclavo.Text = Items.ToXmlString(true); }
private byte[] ProcessRSA(byte[] inputBlock, RSAKey rsaKey) { List <byte> result = new List <byte>(inputBlock.Length); int readSize = 0; int writeSize = 0; if (rsaKey.IsPrivate) { readSize = rsaKey.MaxCipherTextSize; writeSize = rsaKey.MaxOpenTextSize; } else { readSize = rsaKey.MaxOpenTextSize; writeSize = rsaKey.MaxCipherTextSize; } try { for (int currentByte = 0; currentByte < inputBlock.Length; currentByte += readSize) { int byteCopyCount = Math.Min(readSize, inputBlock.Length - currentByte); byte[] currentBlock = new byte[byteCopyCount + 1]; // Добавлен 0х00 чтобы число было положительным Buffer.BlockCopy(inputBlock, currentByte, currentBlock, 0, byteCopyCount); BigInteger openInt = new BigInteger(currentBlock); BigInteger cipherInt = BigInteger.ModPow(openInt, rsaKey.Exponent, rsaKey.Modulus); byte[] cipherBlock = cipherInt.ToByteArray(false); byte[] packedBlock = new byte[writeSize]; Buffer.BlockCopy(cipherBlock, 0, packedBlock, 0, cipherBlock.Length); result.AddRange(packedBlock); } } catch (Exception ex) { throw new Exception("Ошибка! Проверьте входные параметры.", ex); } return(result.ToArray()); }
/// <summary> /// RSA生成公钥和私钥.net /// </summary> /// <returns></returns> public static RSAKey RSAGenerateKeysDotNet() { try { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); RSAKey key = new RSAKey(); key.PublicKey = rsa.ToXmlString(false); key.PrivateKey = rsa.ToXmlString(true); return(key); } catch (Exception) { return(null); } }
/// <summary> Create RSAPrivateKey with the provided key </summary> public RSAPrivateKey(RSAParameters keyInfo) : this(new RSACryptoServiceProvider()) { Check.NotNull(keyInfo); Check.NotNull(keyInfo.D); Check.NotNull(keyInfo.DP); Check.NotNull(keyInfo.DQ); Check.NotNull(keyInfo.Exponent); Check.NotNull(keyInfo.InverseQ); Check.NotNull(keyInfo.Modulus); Check.NotNull(keyInfo.P); Check.NotNull(keyInfo.Q); RSAKey.ImportParameters(keyInfo); }
public RSAKey GenerateKeys() { var keys = new RSAKey(); var rsa = RSA.Create(); //匯出公鑰 var pubKey = rsa.ExportRSAPublicKey(); //匯出私鑰 var priKey = rsa.ExportRSAPrivateKey(); keys.publicKey = Convert.ToBase64String(pubKey); keys.privateKey = Convert.ToBase64String(priKey); return(keys); }
public async void SetSecuritySettings(SecuritySettingsInfo securitySettings) #endif { SecuritySettings = null; if (securitySettings.SecurityMode == SecurityMode.None) { securitySettings.Data = null; #if (NET40 || NET35) SecuritySettingsInfo result = ConnectorExtensions.SendData <SecuritySettingsInfo>(this, new Shared.Models.MethodCallInfo() { Guid = Guid.NewGuid().ToString(), ServiceName = "/SetSettings", Data = JsonConvert.SerializeObject(securitySettings) }); #else SecuritySettingsInfo result = await ConnectorExtensions.SendData <SecuritySettingsInfo>(this, new Shared.Models.MethodCallInfo() { Guid = Guid.NewGuid().ToString(), ServiceName = "/SetSettings", Data = JsonConvert.SerializeObject(securitySettings) }); #endif } else if (securitySettings.SecurityMode == SecurityMode.RSA_AESSecurity) { #if (!PORTABLE) RSAKey keys = RSASecurity.GenerateRandomKey(); securitySettings.Data = new RSAAESEncryptionData() { RSAEncryptionKey = keys.PublicKey }; #if (NET40 || NET35) SecuritySettingsInfo result = ConnectorExtensions.SendData <SecuritySettingsInfo>(this, new Shared.Models.MethodCallInfo() { Guid = Guid.NewGuid().ToString(), ServiceName = "/SetSettings", Data = JsonConvert.SerializeObject(securitySettings) }); #else SecuritySettingsInfo result = await ConnectorExtensions.SendData <SecuritySettingsInfo>(this, new Shared.Models.MethodCallInfo() { Guid = Guid.NewGuid().ToString(), ServiceName = "/SetSettings", Data = JsonConvert.SerializeObject(securitySettings) }); #endif SecuritySettings = new SecuritySettingsInfo() { Data = new RSAAESEncryptionData() { Key = RSASecurity.Decrypt(result.Data.Key, RSASecurity.StringToKey(keys.PrivateKey)), IV = RSASecurity.Decrypt(result.Data.IV, RSASecurity.StringToKey(keys.PrivateKey)) }, SecurityMode = securitySettings.SecurityMode }; #endif } }
/// <summary> /// RSA生成公钥和私钥Java /// </summary> /// <returns></returns> public static RSAKey RSAGenerateKeysJava() { try { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); string publicKey = RSAPublicKeyDotNet2Java(rsa.ToXmlString(false)); string privateKey = RSAPrivateKeyDotNet2Java(rsa.ToXmlString(true)); RSAKey key = new RSAKey(); key.PublicKey = publicKey; key.PrivateKey = privateKey; return(key); } catch (Exception) { return(null); } }
public MainPage() { this.InitializeComponent(); object Ip = Settings.GetIp(), Username = Settings.GetUsername(); if (Ip != null) { ServerName_TB.Text = Ip.ToString(); } if (Username != null) { UserName_TB.Text = Username.ToString(); } _RSAKey = Encryption.RSA.GenerateKeys(); }
public override void Generate() { // IA Key var rsa = new RSACryptoServiceProvider(LengthIAKeyBits).ExportParameters(true); IAKey = new RSAKey(rsa); // FA Key var aes = new AesCryptoServiceProvider(); aes.KeySize = LengthFAKeyBits; aes.GenerateKey(); FAKey = new byte[aes.Key.Length]; aes.Key.CopyTo(FAKey, 0); // Update the Hash UpdateHash(); }
private void button2_Click(object sender, EventArgs e) { if (!connected) { Package pck = new Package(); pck.SetHeader("Command", "Connect"); pck.SetHeader("Username", textBox2.Text); Package response = SendCommand(pck); RSA certRSA = new RSA(certificateKey); string[] respCertf = certRSA.decrypt(response.GetHeader("Certificate")).Split(';'); publicKey = new RSAKey(BigInteger.Parse(respCertf[2]), BigInteger.Parse(respCertf[3])); // Send once more for des key pck = new Package(); pck.SetHeader("Command", "DES"); RSA rsaPub = new RSA(publicKey); pck.SetHeader("DES Key", rsaPub.encrypt(ecbKey)); response = SendCommand(pck); this.publicDes = response.GetHeader("DES Key"); this.publicDes = rsa.decrypt(this.publicDes); connected = true; button2.Text = "Disconnect"; textBox3.Enabled = false; listBox1.Enabled = true; textBox1.Enabled = true; textBox2.Enabled = false; button1.Enabled = true; } else { Package pck = new Package(); pck.SetHeader("Command", "Disconnect"); SendCommand(pck); connected = false; button2.Text = "Connect to server..."; textBox3.Enabled = true; listBox1.Enabled = false; textBox1.Enabled = false; textBox2.Enabled = true; button1.Enabled = false; } }
public static void HelloConnectMessageTreatment(Message message, byte[] packetDatas, AccountUC account) { account.SetStatus(Status.None); if (!account.IsMITM) { HelloConnectMessage helloConnectMessage = (HelloConnectMessage)message; using (BigEndianReader reader = new BigEndianReader(packetDatas)) { helloConnectMessage.Deserialize(reader); } sbyte[] credentials = RSAKey.Encrypt(helloConnectMessage.key, account.AccountName, account.AccountPassword, helloConnectMessage.salt); IdentificationMessage msg = new IdentificationMessage(GameConstants.AutoConnect, GameConstants.UseCertificate, GameConstants.UseLoginToken, new Common.Protocol.Types.VersionExtended(GameConstants.Major, GameConstants.Minor, GameConstants.Release, GameConstants.Revision, GameConstants.Patch, GameConstants.BuildType, GameConstants.Install, GameConstants.Technology), GameConstants.Lang, credentials, GameConstants.ServerID, GameConstants.SessionOptionalSalt, new System.Collections.Generic.List <short>()); account.SocketManager.Send(msg); } account.Log(new ConnectionTextInformation("Identification en cours."), 0); }
static void Main(string[] args) { string content = "Mr@1234_$%!"; RSAKey rsaKey = RsaHelper.CreateRsaKey(); WriteLine($"PrivateKey:{rsaKey.PrivateKey}"); WriteLine(); WriteLine($"PublicKey;{rsaKey.PublicKey}"); WriteLine(); WriteLine($"{content} 加密后:"); string e = RsaHelper.RSAEncrypt(content, rsaKey.PublicKey); WriteLine(e); WriteLine($"解密后:{RsaHelper.RSADecrypt(e, rsaKey.PrivateKey)}"); ReadKey(); }
public static RSAKey ReadKey(string fileName) { RSAKey key = new RSAKey(); FileStream fileStream = new FileStream(fileName, FileMode.Open); string fileContents; using (StreamReader reader = new StreamReader(fileStream)) { fileContents = reader.ReadToEnd(); } fileStream.Close(); Int64[] dataArray = fileContents.Split().Select(x => Int64.Parse(x)).ToArray(); if (dataArray.Length != 2) { throw new Exception("Error reading key from file!"); } key.data = dataArray[0]; key.N = dataArray[1]; return key; }
/// <summary> /// 创建秘钥对 /// </summary> /// <param name="length">长度1024的倍数</param> /// <param name="keyType">1.Net的秘钥 2java的秘钥</param> public static KeyValuePair <string, string> CreateKeyPair(string length, int keyType = 1) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024); //.Net的私钥 string prixml = rsa.ToXmlString(true); //.Net的公钥 string pubxml = rsa.ToXmlString(false); switch (keyType) { case 2: //转换 成java的私钥 string prk = RSAKey.RSAPrivateKeyDotNet2Java(prixml); //转换成java的公钥 string puk = RSAKey.RSAPublicKeyDotNet2Java(pubxml); return(new KeyValuePair <string, string>(prk, puk)); default: return(new KeyValuePair <string, string>(prixml, pubxml)); } }
public static RSAKey NetToJava(RSAKey rsakey) { //公钥 byte[] m = Base64.decodeBase64("mX/9zl8rflH5pLaP5P1Qd/9wXwNBSx7OpLlYDnGr7wD0njiDfPSUkgf9oF5NcvZwl24qdJ1SLmrgUtnr+yeXBNZNKaan1xXKISHdlHvbW5G8nJCJW6CuaHMkVw3Y7kwaIIlUdv09vxfjj0AoabttjbtF1kqETzbQ6fK3EN6sY5U="); byte[] e = Base64.decodeBase64("AQAB"); BigInteger b1 = new BigInteger(1, m); BigInteger b2 = new BigInteger(1, e); //私钥 byte[] m1 = Base64.decodeBase64("3RgqP5YOYUXft8YOlDphyaCoof27MSfTD2eVCFVXB5hatrls1fSUcmUuWuGV970sS6KQZZtyWHQ5970sCzKFlq82He8Uoe0JM3axBvd6PbSGjulUJr62qNW5hgkIEfxSRYl8AQsbbusFtks4obfepsfE02cLmmZepnZAdIOWifE="); byte[] e1 = Base64.decodeBase64("QcSZdLbHakolxX4GAjPnuNmwsBdRIsss7o0qeQMh02GPwoEgDfkmW20bv+8Q9FPypEEkYQU/m25ffAFq453QvLegYYi8OvWN+dvgchQRdeb22d+s6xYGGN9DRcPFRE48INde8FBHf/lzVgToV75h1H7g+jB4hLmLeuIuHsB43/0="); BigInteger b11 = new BigInteger(1, m1); BigInteger b21 = new BigInteger(1, e1); //公钥 KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2); RSAPublicKey pubKey = (RSAPublicKey)keyFactory.generatePublic(keySpec); //私钥 RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(b11, b21); RSAPrivateKey priKey = (RSAPrivateKey)keyFactory.generatePrivate(priKeySpec); }
/// <summary> /// Create an RSA key /// </summary> /// <param name="rsa">rsa</param> /// <param name="includePrivate"></param> /// <returns></returns> public static RSAKey CreateRsaKey(RSA rsa, bool includePrivate = true) { Check.Argument.IsNotNull(rsa, nameof(rsa)); string publicKey = rsa.ToJsonString(false); var rsaKey = new RSAKey() { PublicKey = publicKey, Exponent = rsa.ExportParameters(false).Exponent.ToHexString(), Modulus = rsa.ExportParameters(false).Modulus.ToHexString() }; if (includePrivate) { string privateKey = rsa.ToJsonString(true); rsaKey.PrivateKey = privateKey; } return(rsaKey); }
public ServerChat() { listening = false; bufferMessage.Clear(); rsa.GenerateKey(); ecbKey = ECB.GenerateKey(); Package verf = new Package(); verf.SetHeader("Command", "Register"); verf.SetHeader("Public Key n", rsa.Key.n.ToString()); verf.SetHeader("Public Key e", rsa.Key.e.ToString()); Package certf = SendCommand(verf, 2745); BigInteger n = BigInteger.Parse(certf.GetHeader("Public Key n")); BigInteger e = BigInteger.Parse(certf.GetHeader("Public Key e")); certificateKey = new RSAKey(); certificateKey.d = e; certificateKey.n = n; certificate = certf.GetContent(); }
public void Run(ModuleInfo info, CancellationToken token = default(CancellationToken)) { BigInteger Privatek = BigInteger.Parse(info.Parent.ReadString()); BigInteger shared = BigInteger.Parse(info.Parent.ReadString()); string text = info.Parent.ReadString(); var texts = text.Split('.').ToList(); Console.WriteLine(Privatek); Console.WriteLine(shared); Console.WriteLine(text); RSAKey privateKey = new RSAKey(Privatek, shared); var list = new List <BigInteger>(); texts.ForEach(z => list.Add(BigInteger.Parse(z, NumberStyles.Float, CultureInfo.InvariantCulture))); var result = RSAProvider.Decrypt(list, privateKey); //var trueResult = result.Aggregate((x, y) => x + y); //info.Parent.WriteData(trueResult.ToString()); info.Parent.WriteData(result); }
public Chat() { InitializeComponent(); rsa.GenerateKey(); ecbKey = ECB.GenerateKey(); Package verf = new Package(); verf.SetHeader("Command", "Register"); verf.SetHeader("Public Key n", rsa.Key.n.ToString()); verf.SetHeader("Public Key e", rsa.Key.e.ToString()); Package certf = SendCommand(verf, 2745); BigInteger n = BigInteger.Parse(certf.GetHeader("Public Key n")); BigInteger e = BigInteger.Parse(certf.GetHeader("Public Key e")); certificateKey = new RSAKey(); certificateKey.d = e; certificateKey.n = n; certificate = certf.GetContent(); Console.WriteLine("Register Certificate: " + certificate); //certf.Print(); }
public static RSAKey GenerateRSAKeys() { using (var rsa = new RSACryptoServiceProvider(1024)) { RSAKey rsaKey; try { var publicKey = rsa.ToXmlString(false); var privateKey = rsa.ToXmlString(true); rsaKey = new RSAKey(privateKey, publicKey); } catch (Exception ex) { return(null); } finally { rsa.PersistKeyInCsp = false; } return(rsaKey); } }