public JObject products() { List <Product> productList = Product.GetProducts(); JArray signedProductList = new JArray(); foreach (Product product in productList) { JObject jsonProduct = new JObject(); jsonProduct.Add("id", product.GetProductID()); jsonProduct.Add("name", product.GetProductName()); jsonProduct.Add("euros", product.GetPriceEuros()); jsonProduct.Add("cents", product.GetPriceCents()); string productJSONString = jsonProduct.ToString(); string productSignedHash = RSAEncrypter.GetRSAEncrypter().Sign(productJSONString); JObject signedProduct = new JObject(); signedProduct.Add("product", productJSONString); signedProduct.Add("sign", productSignedHash); signedProductList.Add(signedProduct); } JObject response = new JObject(); response.Add("products", signedProductList); response.Add("key", RSAEncrypter.GetRSAEncrypter().GetPEMPublicKey()); return(response); }
public Startup(IConfiguration configuration) { Database db = Database.GetDatabase(); RSAEncrypter rsa = RSAEncrypter.GetRSAEncrypter(); Configuration = configuration; }
public void WorkCorrectly_WithString(string firstPrime, string secondPrime, string value) { var encryptionResult = RSAEncrypter.EncryptString(firstPrime, secondPrime, value); encryptionResult.encryptedValue.Should().NotBe(value); RSAEncrypter.DecryptString(encryptionResult.secretKey.Exponent, encryptionResult.secretKey.Module, encryptionResult.encryptedValue).Should().Be(value); }
public JObject register([Microsoft.AspNetCore.Mvc.FromBody] JObject data) { string name = data["name"].ToString(); string username = data["username"].ToString(); string password = data["password"].ToString(); int credit = data["credit_card_no"].ToObject <int>(); string key = data["public_key"].ToString(); JObject ret = new JObject(); ret.Add("user_id", Client.RegisterUser(name, username, password, key, credit).GetClientID().ToString()); ret.Add("server_key", RSAEncrypter.GetRSAEncrypter().GetPEMPublicKey()); return(ret); }
public byte[] CheckIn() { byte[] privateKey = new byte[0]; // Get the client's certificate from the current operation context X509Certificate2 clientCertificate = SecurityHelper.GetCertificate(OperationContext.Current); // Get the client's name from the certificate string clientName = SecurityHelper.GetName(clientCertificate); // Log the successful authentication EventLogger.AuthenticationSuccess(clientName); // Encrypt the private key with the client's certificate public key privateKey = RSAEncrypter.Encrypt(StringConverter.ToString(PrivateKey), clientCertificate); return(privateKey); }
private static SecureString GetKey() { SecureString key = new SecureString(); try { using (WCFServiceClient client = new WCFServiceClient()) { // Get client's certificate from the client credentials X509Certificate2 clientCertificate = SecurityHelper.GetCertificate(client); // Check in with the WCFService to receive the private key byte[] encryptedKey = client.CheckIn(); // If the encrypted key is null or empty, the service denied the request if (encryptedKey != null && encryptedKey.Length > 0) { // Decrypt the encrypted key data string privateKey = RSAEncrypter.Decrypt(encryptedKey, clientCertificate); // Clear the encrypted key data for security reasons Array.Clear(encryptedKey, 0, encryptedKey.Length); // Convert the decrypted key into a secure string key = StringConverter.ToSecureString(privateKey); // Clear the unsecure key for security reasons privateKey = string.Empty; Console.WriteLine("Private key retrieved from the service"); } else { Console.WriteLine("Unable to retrieve the private key from the service"); } } } catch (Exception e) { Console.WriteLine("[ERROR] {0}", e.Message); } return(key); }
public void WorkCorrectly_WithFile(string firstPrime, string secondPrime) { var defaultPath = Environment.CurrentDirectory + "test.txt"; File.WriteAllLines(defaultPath, GenerateFileContent(250, 100)); var encryptionResult = RSAEncrypter.EncryptFile(defaultPath, firstPrime, secondPrime); File.ReadLines(encryptionResult.newPath).Should().NotEqual(File.ReadLines(defaultPath)); var decryptionResult = RSAEncrypter.DecryptFile(encryptionResult.newPath, encryptionResult.secretKey.Exponent, encryptionResult.secretKey.Module); File.ReadLines(decryptionResult).Should().Equal(File.ReadLines(defaultPath)); File.Delete(defaultPath); File.Delete(encryptionResult.newPath); File.Delete(decryptionResult); }
static void Main(string[] args) { Console.WriteLine("** RSA **"); var rsaKey = RsaKey.CreateRsaKey(); var plaintext = "Hello world 123456789/*-+!@#$%^&*()-=_+"; var publicKey = rsaKey.PublicKey; var privateKey = rsaKey.PrivateKey; //var exponent = rsaKey.Exponent; //var modulus = rsaKey.Modulus; var encrypted = RSAEncrypter.RSAEncrypt(publicKey, plaintext, RSAEncryptionPadding.OaepSHA512); var decrypted = RSADecrypter.RSADecrypt(privateKey, encrypted, RSAEncryptionPadding.OaepSHA512); Console.WriteLine("Encrypted: " + encrypted); Console.WriteLine("Decrypted: " + decrypted); //Console.WriteLine("publicKey: {0} privateKey: {1}", publicKey, privateKey); Console.ReadKey(); }
static void Main(string[] args) { RSACryptoServiceProvider signatureRSA = new RSACryptoServiceProvider(); // Генерация RSA ключей RSAParameters publicRSAKeyInfo, privateRSAKeyInfo; try { using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { Byte[] buffer = RSA.ExportParameters(true).D; string converted_D = BitConverter.ToString(buffer).Replace("-", "|"); buffer = RSA.ExportParameters(true).Modulus; string converted_N = BitConverter.ToString(buffer).Replace("-", "|"); Console.WriteLine("Ключевая пара RSA: \n\tD=" + converted_D + ",\n\tN=" + converted_N); publicRSAKeyInfo = RSA.ExportParameters(false); privateRSAKeyInfo = RSA.ExportParameters(true); } } catch (ArgumentNullException) { Console.WriteLine("RSA шифрование провалилось."); return; } if (args.Length != 1 && args.Length != 2) { Console.WriteLine("Ожидалось 1 или 2 аргумента"); return; } string fileContent = System.IO.File.ReadAllText(args[0]); byte[] sim_encrypted = { }; byte[] keyRijndael = { }; byte[] ivRijndael = { }; byte[] senderSignature = { }; byte[] originalSHA; // Шифруем документ с помощью симметричного шифрования AES(Rijndael) // Ключ шифрования AES шифруем с помощью RSA, используя его публичный ключ // Также генерируем цифровую подпись try { string original = fileContent; using (RijndaelManaged myRijndael = new RijndaelManaged()) { myRijndael.GenerateKey(); myRijndael.GenerateIV(); sim_encrypted = RijndaelEncrypter.EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV); Console.WriteLine("Исходный документ: {0}", original); keyRijndael = RSAEncrypter.RSAEncrypt(myRijndael.Key, publicRSAKeyInfo, false); ivRijndael = RSAEncrypter.RSAEncrypt(myRijndael.IV, publicRSAKeyInfo, false); // Генерация цифровой подписи originalSHA = SHA.GetSHA(Encoding.UTF8.GetBytes(original)); senderSignature = RSAEncrypter.RSAEncrypt(SHA.GetSHA(Encoding.UTF8.GetBytes(original)), signatureRSA.ExportParameters(false), false); } } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); return; } // Проверка цифровой подписи byte[] encryptedSignature = RSADecrypter.RSADecrypt(senderSignature, signatureRSA.ExportParameters(true), false); if (!Enumerable.SequenceEqual(encryptedSignature, originalSHA)) { Console.WriteLine("Ненастоящая цифровая подпись"); return; } // Вначале расшифровываем параметры симметричного шифрования с помощью закрытого ключа. // А потом используем полученный ключ AES для расшифровки основного текста string roundtrip = RijndaelDecrypter.DecryptStringFromBytes(sim_encrypted, RSADecrypter.RSADecrypt(keyRijndael, privateRSAKeyInfo, false), RSADecrypter.RSADecrypt(ivRijndael, privateRSAKeyInfo, false)); Console.WriteLine("Расшифрованный текст: {0}", roundtrip); }