public static void SignHash_NullArray() { using (var rsa = new RSACryptoServiceProvider()) { Assert.Throws<ArgumentNullException>(() => rsa.SignHash(null, "SHA384")); } }
public static void ExportImportPublicOnly() { byte[] expectedExport = ByteUtils.HexToByteArray( "0602000000a40000525341310004000001000100e19a01644b82962a224781d1f60c2cc373b" + "798df541343f63c638f45fa96e11049c8d9e88bd56483ec3c2d56e9460d2b1140191841761c1523840221b0e" + "b6401dc4d09c54bf75cea25d9e191572fb2ec92c3559b35b3ef3fa695171bb1fddeb469792e49f0d17c769d0" + "a37f6a4a6584af39878eb21f9ba9eae8be9c39eac6ae0"); byte[] exported; using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(TestData.CspTestKey); exported = rsa.ExportCspBlob(includePrivateParameters: false); } Assert.Equal(expectedExport, exported); using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportCspBlob(exported); byte[] exported2 = rsa.ExportCspBlob(includePrivateParameters: false); Assert.Equal(exported, exported2); Assert.Throws<CryptographicException>(() => rsa.ExportCspBlob(includePrivateParameters: true)); } }
public static void ApiInterop_OldToNew_Positional() { using (var rsa = new RSACryptoServiceProvider()) { byte[] oldSignature = rsa.SignData(s_dataToSign, 3, 2, "SHA384"); Assert.True(rsa.VerifyData(s_dataToSign, 3, 2, oldSignature, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1)); } }
public static RSA GetRSAPrivateKey(this X509Certificate2 certificate) { if (certificate == null) { throw new ArgumentNullException("certificate"); } if (!certificate.HasPrivateKey || !IsRSA(certificate)) { return null; } using (SafeCertContextHandle certificateContext = X509Native.GetCertificateContext(certificate)) using (SafeNCryptKeyHandle privateKeyHandle = X509Native.TryAcquireCngPrivateKey(certificateContext)) { if (privateKeyHandle == null) { if (LocalAppContextSwitches.DontReliablyClonePrivateKey) return (RSA)certificate.PrivateKey; // fall back to CAPI if we cannot acquire the key using CNG. RSACryptoServiceProvider rsaCsp = (RSACryptoServiceProvider)certificate.PrivateKey; CspParameters cspParameters = DSACertificateExtensions.CopyCspParameters(rsaCsp); RSACryptoServiceProvider clone = new RSACryptoServiceProvider(cspParameters); return clone; } CngKey key = CngKey.Open(privateKeyHandle, CngKeyHandleOpenOptions.None); return new RSACng(key); } }
public void initialize() { this._hash_code = this.GetHashCode().ToString(); this._user_cryptor = new RSACryptoServiceProvider(); this._server_cryptor = new RSACryptoServiceProvider(2048); this._server_public_key = this._server_cryptor.ToXmlString(false); }
public static void LargeKeyImportExport() { RSAParameters imported = TestData.RSA16384Params; using (RSA rsa = new RSACryptoServiceProvider()) { try { rsa.ImportParameters(imported); } catch (CryptographicException) { // The key is pretty big, perhaps it was refused. return; } RSAParameters exported = rsa.ExportParameters(false); Assert.Equal(exported.Modulus, imported.Modulus); Assert.Equal(exported.Exponent, imported.Exponent); Assert.Null(exported.D); exported = rsa.ExportParameters(true); AssertKeyEquals(ref imported, ref exported); } }
/// <summary> /// A string extension method that encrypts the string. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="key">The key.</param> /// <returns>The encrypted string.</returns> /// <example> /// <code> /// using Microsoft.VisualStudio.TestTools.UnitTesting; /// using Z.ExtensionMethods; /// /// namespace ExtensionMethods.Examples /// { /// [TestClass] /// public class System_String_EncryptRSA /// { /// [TestMethod] /// public void EncryptRSA() /// { /// // Type /// string @this = "Fizz"; /// /// // Examples /// string value = @this.EncryptRSA("Buzz"); // return Encrypted string; /// /// // Unit Test /// Assert.AreEqual("Fizz", value.DecryptRSA("Buzz")); /// } /// } /// } /// </code> /// </example> public static string EncryptRSA(this string @this, string key) { var cspp = new CspParameters {KeyContainerName = key}; var rsa = new RSACryptoServiceProvider(cspp) {PersistKeyInCsp = true}; byte[] bytes = rsa.Encrypt(Encoding.UTF8.GetBytes(@this), true); return BitConverter.ToString(bytes); }
public static void DefaultKeySize() { using (var rsa = new RSACryptoServiceProvider()) { Assert.Equal(1024, rsa.KeySize); } }
public static void DecryptSavedAnswerUnusualExponent() { byte[] cipherBytes = { 0x55, 0x64, 0x05, 0xF7, 0xBF, 0x99, 0xD8, 0x07, 0xD0, 0xAC, 0x1B, 0x1B, 0x60, 0x92, 0x57, 0x95, 0x5D, 0xA4, 0x5B, 0x55, 0x0E, 0x12, 0x90, 0x24, 0x86, 0x35, 0xEE, 0x6D, 0xB3, 0x46, 0x3A, 0xB0, 0x3D, 0x67, 0xCF, 0xB3, 0xFA, 0x61, 0xBB, 0x90, 0x6D, 0x6D, 0xF8, 0x90, 0x5D, 0x67, 0xD1, 0x8F, 0x99, 0x6C, 0x31, 0xA2, 0x2C, 0x8E, 0x99, 0x7E, 0x75, 0xC5, 0x26, 0x71, 0xD1, 0xB0, 0xA5, 0x41, 0x67, 0x19, 0xF7, 0x40, 0x04, 0xBE, 0xB2, 0xC0, 0x97, 0xFB, 0xF6, 0xD4, 0xEF, 0x48, 0x5B, 0x93, 0x81, 0xF8, 0xE1, 0x6A, 0x0E, 0xA0, 0x74, 0x6B, 0x99, 0xC6, 0x23, 0xF5, 0x02, 0xDE, 0x47, 0x49, 0x1E, 0x9D, 0xAE, 0x55, 0x20, 0xB5, 0xDE, 0xA0, 0x04, 0x32, 0x37, 0x4B, 0x24, 0xE4, 0x64, 0x1B, 0x1B, 0x4B, 0xC0, 0xC7, 0x30, 0x08, 0xA6, 0xAE, 0x50, 0x86, 0x08, 0x34, 0x70, 0xE5, 0xB0, 0x3B, }; byte[] output; using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(TestData.UnusualExponentParameters); output = rsa.Decrypt(cipherBytes, true); } Assert.Equal(TestData.HelloBytes, output); }
public static void PaddedExport() { // OpenSSL's numeric type for the storage of RSA key parts disregards zero-valued // prefix bytes. // // The .NET 4.5 RSACryptoServiceProvider type verifies that all of the D breakdown // values (P, DP, Q, DQ, InverseQ) are exactly half the size of D (which is itself // the same size as Modulus). // // These two things, in combination, suggest that we ensure that all .NET // implementations of RSA export their keys to the fixed array size suggested by their // KeySize property. RSAParameters diminishedDPParamaters = TestData.DiminishedDPParamaters; RSAParameters exported; using (RSA rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(diminishedDPParamaters); exported = rsa.ExportParameters(true); } // DP is the most likely to fail, the rest just otherwise ensure that Export // isn't losing data. AssertKeyEquals(ref diminishedDPParamaters, ref exported); }
private static void GenerateKey(Func<RSA, int> getSize) { int keySize; using (var rsa = new RSACryptoServiceProvider()) { keySize = getSize(rsa); } using (var rsa = new RSACryptoServiceProvider(keySize)) { Assert.Equal(keySize, rsa.KeySize); // Some providers may generate the key in the constructor, but // all of them should have generated it before answering ExportParameters. RSAParameters keyParameters = rsa.ExportParameters(false); ImportExport.ValidateParameters(ref keyParameters); // KeySize should still be what we set it to originally. Assert.Equal(keySize, rsa.KeySize); // KeySize describes the size of the modulus in bits // So, 8 * the number of bytes in the modulus should be the same value. Assert.Equal(keySize, keyParameters.Modulus.Length * 8); } }
public static void CreateKey_LegacyProvider_RoundtripBlob() { const int KeySize = 512; CspParameters cspParameters = new CspParameters(PROV_RSA_FULL); byte[] blob; using (var rsa = new RSACryptoServiceProvider(KeySize, cspParameters)) { CspKeyContainerInfo containerInfo = rsa.CspKeyContainerInfo; Assert.Equal(PROV_RSA_FULL, containerInfo.ProviderType); Assert.Equal(KeySize, rsa.KeySize); blob = rsa.ExportCspBlob(true); } using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportCspBlob(blob); CspKeyContainerInfo containerInfo = rsa.CspKeyContainerInfo; // The provider information is not persisted in the blob Assert.Equal(PROV_RSA_AES, containerInfo.ProviderType); Assert.Equal(KeySize, rsa.KeySize); } }
public static void LargeKeyCryptRoundtrip() { byte[] output; using (var rsa = new RSACryptoServiceProvider()) { try { rsa.ImportParameters(TestData.RSA16384Params); } catch (CryptographicException) { // The key is pretty big, perhaps it was refused. return; } byte[] crypt = rsa.Encrypt(TestData.HelloBytes, true); Assert.Equal(rsa.KeySize, crypt.Length * 8); output = rsa.Decrypt(crypt, true); } Assert.Equal(TestData.HelloBytes, output); }
public static void DecryptSavedAnswer() { byte[] cipherBytes = { 0x35, 0x6F, 0x8F, 0x2C, 0x4D, 0x1A, 0xAC, 0x6D, 0xE7, 0x52, 0xA5, 0xDF, 0x26, 0x54, 0xA6, 0x34, 0xF5, 0xBB, 0x14, 0x26, 0x1C, 0xE4, 0xDC, 0xA2, 0xD8, 0x4D, 0x8F, 0x1C, 0x55, 0xD4, 0xC7, 0xA7, 0xF2, 0x3C, 0x99, 0x77, 0x9F, 0xE4, 0xB7, 0x34, 0xA6, 0x28, 0xB2, 0xC4, 0xFB, 0x6F, 0x85, 0xCA, 0x19, 0x21, 0xCA, 0xC1, 0xA7, 0x8D, 0xAE, 0x95, 0xAB, 0x9B, 0xA9, 0x88, 0x5B, 0x44, 0xC6, 0x9B, 0x44, 0x26, 0x71, 0x5D, 0x02, 0x3F, 0x43, 0x42, 0xEF, 0x4E, 0xEE, 0x09, 0x87, 0xEF, 0xCD, 0xCF, 0xF9, 0x88, 0x99, 0xE8, 0x49, 0xF7, 0x8F, 0x9B, 0x59, 0x68, 0x20, 0xF3, 0xA7, 0xB2, 0x94, 0xA4, 0x23, 0x70, 0x83, 0xD9, 0xAC, 0xE7, 0x5E, 0xEE, 0xE9, 0x7B, 0xE4, 0x4F, 0x73, 0x2E, 0x9B, 0xD8, 0x2A, 0x75, 0xFB, 0x6C, 0xB9, 0x39, 0x6D, 0x72, 0x8A, 0x9C, 0xCD, 0x58, 0x1A, 0x27, 0x79, 0x97, }; byte[] output; using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(TestData.RSA1024Params); output = rsa.Decrypt(cipherBytes, true); } Assert.Equal(TestData.HelloBytes, output); }
public static void ExportAutoKey() { RSAParameters privateParams; RSAParameters publicParams; int keySize; using (RSA rsa = new RSACryptoServiceProvider()) { keySize = rsa.KeySize; // We've not done anything with this instance yet, but it should automatically // create the key, because we'll now asked about it. privateParams = rsa.ExportParameters(true); publicParams = rsa.ExportParameters(false); // It shouldn't be changing things when it generated the key. Assert.Equal(keySize, rsa.KeySize); } Assert.Null(publicParams.D); Assert.NotNull(privateParams.D); ValidateParameters(ref publicParams); ValidateParameters(ref privateParams); Assert.Equal(privateParams.Modulus, publicParams.Modulus); Assert.Equal(privateParams.Exponent, publicParams.Exponent); }
public static string FromPrivateRSAParameters(this RSAParameters privateKey) { using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(privateKey); return rsa.ToXmlString(includePrivateParameters: true); } }
public static RSAParameters ToPublicRSAParameters(this string publicKeyXml) { using (var rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(publicKeyXml); return rsa.ExportParameters(includePrivateParameters: false); } }
public static string ToPublicKeyXml(this RSAParameters publicKey) { using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(publicKey); return rsa.ToXmlString(includePrivateParameters: false); } }
public static void ApiInterop_NewToOld() { using (var rsa = new RSACryptoServiceProvider()) { byte[] newSignature = rsa.SignData(s_dataToSign, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1); Assert.True(rsa.VerifyData(s_dataToSign, "SHA384", newSignature)); } }
/// <summary> /// Sign the XML String of SamlResponse /// </summary> /// <param name="xmlString"></param> /// <returns>Digital signed SamlReponse string</returns> public static String signSamlElement(String xmlString) { // Create a new CspParameters object to specify a key container. CspParameters cspParams = new CspParameters(); cspParams.Flags = CspProviderFlags.UseMachineKeyStore; // cspParams.KeyContainerName = "GOOGLE"; // cspParams.ProviderName = "HF"; string pb = "<RSAKeyValue><Modulus>wTI341fDKEG9mV9VDFRj/XKf5nZxfadISavENRbwPlKZBipYAi6zgVNPJ7nhSH4qdXqphOreXFFmwsg8JzxHLJRJ8yjIfiG3ORuRaHO0dpTslSQ4wz5qVroj4avI3m5pL6jFgtaWJkWlr7uzq4xrdKwu+wZiOaNNCFjqUo18ycE=</Modulus><Exponent>AQAB</Exponent><P>86FAPMQJey3PrI+PBPnMgn8xzR3qy/WBjUihKn+Fb9tP7GipWD9oi3tkdR/KZfBcvSoacDQqxMg8Y+aY90glGQ==</P><Q>ywFrg+GccDYsFwOZJsgzC8FXBQf9jalFbfuRdjrrH0Cd2JqHXC/nrpc7YB3qOORaWSuxWorGdN3+o42qszX26Q==</Q><DP>L3udDnrSsjxCfopYQIsDDegGZ8jN60SFJGkkaCkEc8GVuSjI4JczJAQ/lwhEJUwMdx3Om1G/iCzSgFIAPCnGeQ==</DP><DQ>HX0nUREE2IgF/5HWPXv3bk23hlOS0XE1VLSmfLYyUWfhhgVshEexL/tn9J5j17/UH//o0241ReS5iKibk0zTgQ==</DQ><InverseQ>IC++K/C2NT5w01BYp5dcB1sXmWH32oFB1bmgcAkwK2VbQm9a9Xt1YdXtMVUEkxln7Inciny8oEfwdDiUjc82KQ==</InverseQ><D>byvGnTvTQUcTIz6IYh/tqdpbyPI/PF8Wac49iY85j6NYCwQywI6/HJwj4GhGCsEPDasYATRl4Bm3WD6A3tMA4NUw/RYfdutL2vDXjYXZMETWnABeeTdPK9haPw/NrcvhWRkGqNyeHG1soqmrF/x/0Xh5EYTv4KtrIJrPpKFajAE=</D></RSAKeyValue>"; // Create a new RSA signing key and save it in the container. RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(); /* RSACryptoServiceProvider rsaKey; if (System.Web.HttpContext.Current == null) // WinForm rsaKey = new RSACryptoServiceProvider(); else // WebForm - Uses Machine store for keys rsaKey = new RSACryptoServiceProvider(cspParams); */ rsaKey.FromXmlString(pb); /* X509Certificate2 cert = new X509Certificate2(@"C:\certificate.pfx", ""); RSACryptoServiceProvider rsaKey = cert.PrivateKey as RSACryptoServiceProvider;*/ // Create a new XML document XmlDocument xmlDoc = new XmlDocument(); // Load an XML String into the XmlDocument object xmlDoc = Util.createXmlDom(xmlString); // Sign the XML document SignXml(xmlDoc, rsaKey); // convert XmlDocument to String /* MemoryStream stream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(stream, null); writer.Formatting = Formatting.Indented; xmlDoc.Save(writer); StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8); stream.Position = 0; string res = sr.ReadToEnd(); sr.Close(); stream.Close(); return res; * */ return xmlDoc.OuterXml; }
public static void PublicOnly_DefaultKey() { using (var rsa = new RSACryptoServiceProvider()) { // This will call the key into being, which should create a public/private pair, // therefore it should not be public-only. Assert.False(rsa.PublicOnly); } }
public static void PublicOnly_WithPrivateKey() { using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportParameters(TestData.RSA1024Params); Assert.False(rsa.PublicOnly); } }
private static byte[] Decrypt(string privateKeyXml, byte[] encryptedBytes, RsaKeyLengths rsaKeyLength) { using (var RSA = new RSACryptoServiceProvider((int) rsaKeyLength)) { RSA.FromXmlString(privateKeyXml); byte[] bytes = RSA.Decrypt(encryptedBytes, DoOAEPPadding); return bytes; } }
public static RsaKeyPair CreatePublicAndPrivateKeyPair(RsaKeyLengths rsaKeyLength = RsaKeyLengths.Bit2048) { var rsaProvider = new RSACryptoServiceProvider((int)rsaKeyLength); return new RsaKeyPair { PrivateKey = rsaProvider.ToXmlString(true), PublicKey = rsaProvider.ToXmlString(false), }; }
/// <summary> /// A string extension method that decrypt a string. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="key">The key.</param> /// <returns>The decrypted string.</returns> /// <example> /// <code> /// using Microsoft.VisualStudio.TestTools.UnitTesting; /// using Z.ExtensionMethods; /// /// namespace ExtensionMethods.Examples /// { /// [TestClass] /// public class System_String_DecryptRSA /// { /// [TestMethod] /// public void DecryptRSA() /// { /// // Type /// string @this = "7E-24-A5-CF-8E-7A-83-52-90-CA-81-6F-26-04-7C-E6-F4-25-47-26-A9-55-04-83-32-78-1A-C0-E4-5D-90-66-A6-E1-58-59-A8-48-E1-20-21-B9-FE-84-31-53-52-9B-45-E1-B2-93-71-92-DA-29-5B-99-D1-41-19-9C-3E-13-4B-2B-BC-08-94-31-A4-F9-B9-0A-04-2F-C6-78-B1-47-27-11-2C-E6-AF-BF-A8-F2-F3-F6-4E-CB-EB-79-5E-80-C6-A1-0A-D7-7C-F1-16-0E-41-14-4E-76-7E-9E-DD-61-BF-11-5E-62-79-2D-C4-11-D2-F6-3D-7F-DD-87-C4-4E"; /// /// // Examples /// string value = @this.DecryptRSA("Buzz"); // return "Fizz"; /// /// // Unit Test /// Assert.AreEqual("Fizz", value); /// } /// } /// } /// </code> /// </example> public static string DecryptRSA(this string @this, string key) { var cspp = new CspParameters {KeyContainerName = key}; var rsa = new RSACryptoServiceProvider(cspp) {PersistKeyInCsp = true}; string[] decryptArray = @this.Split(new[] {"-"}, StringSplitOptions.None); byte[] decryptByteArray = Array.ConvertAll(decryptArray, (s => Convert.ToByte(byte.Parse(s, NumberStyles.HexNumber)))); byte[] bytes = rsa.Decrypt(decryptByteArray, true); return Encoding.UTF8.GetString(bytes); }
private static byte[] Encrypt(string publicKeyXml, byte[] bytes, RsaKeyLengths rsaKeyLength = RsaKeyLengths.Bit2048) { byte[] encryptedBytes; using (var RSA = new RSACryptoServiceProvider((int) rsaKeyLength)) { RSA.FromXmlString(publicKeyXml); encryptedBytes = RSA.Encrypt(bytes, DoOAEPPadding); } return encryptedBytes; }
public static void CreateKey_LegacyProvider() { CspParameters cspParameters = new CspParameters(PROV_RSA_FULL); using (var rsa = new RSACryptoServiceProvider(cspParameters)) { CspKeyContainerInfo containerInfo = rsa.CspKeyContainerInfo; Assert.Equal(PROV_RSA_FULL, containerInfo.ProviderType); } }
public TTCPClient(IPEndPoint pArgEndPoint, RSACryptoServiceProvider pPublicServerKey) { this.PublicServerRsaKey = pPublicServerKey; this.pEndPoint = pArgEndPoint; this.pClient = new TcpClient(); this.ConnectNow (); this.pClientStream = pClient.GetStream(); this.StartListening(); this.StartSendingThread(); }
static ApplicationWebService() { var dwKeySize = (0x100) * 8; var MaxData = (dwKeySize - 384) / 8 + 37; // JVM multithreading, which thread will generate the key, and is it thread safe later? RSA = new RSACryptoServiceProvider( dwKeySize: dwKeySize, parameters: new CspParameters { } ); }
public static void AssignParameter() { const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "SpiderContainer1"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); }
public RSAParameters ParseRSAKeyInfo(RSAKeySetIdentity rsaKeySet) { RSAParameters rsaParams; int startIndex = rsaKeySet.RSA_PrivateKey.IndexOf(BEGIN_RSA_PRIVATE_KEY, StringComparison.Ordinal); int endIndex = rsaKeySet.RSA_PrivateKey.IndexOf(END_RSA_PRIVATE_KEY, StringComparison.Ordinal); if (startIndex < 0 || endIndex < 0) { throw new ArgumentException("Invalid key data"); } string keyData = rsaKeySet.RSA_PrivateKey.Substring(startIndex + BEGIN_RSA_PRIVATE_KEY.Length, endIndex - startIndex - BEGIN_RSA_PRIVATE_KEY.Length).Replace("\r\n", ""); byte[] keyBlobBytes = Convert.FromBase64String(keyData); using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportCspBlob(keyBlobBytes); rsaParams = rsa.ExportParameters(true); } return(rsaParams); }
/// <summary> /// 生成并保存 RSA 公钥与私钥 /// </summary> /// <param name="directoryPath">存放密钥的文件夹路径</param> /// <returns></returns> public static RSAParameters GenerateAndSaveKey(string directoryPath) { if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } RSAParameters publicKeys, privateKeys; using (var rsa = new RSACryptoServiceProvider(2048)) { try { privateKeys = rsa.ExportParameters(true); publicKeys = rsa.ExportParameters(false); } finally { rsa.PersistKeyInCsp = false; } } File.WriteAllText(Path.Combine(directoryPath, "key.private.rsa"), JsonConvert.SerializeObject(privateKeys)); File.WriteAllText(Path.Combine(directoryPath, "key.public.rsa"), JsonConvert.SerializeObject(publicKeys)); return(privateKeys); }
/// <summary> /// borrowed from https://stackoverflow.com/a/54323524 /// </summary> private static RSACryptoServiceProvider getKeyProvider() { string key = File.ReadAllText("oauth-public.key"); key = key.Replace("-----BEGIN PUBLIC KEY-----", ""); key = key.Replace("-----END PUBLIC KEY-----", ""); key = key.Replace("\n", ""); var keyBytes = Convert.FromBase64String(key); var asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes); var rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter; var rsaParameters = new RSAParameters { Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned(), Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned() }; var rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(rsaParameters); return(rsa); }
public bool SendKey(byte[] key) { SessionData sd = GetSession(OperationContext.Current.SessionId); if (sd != null) { try { RSACryptoServiceProvider privateKey = (RSACryptoServiceProvider)myCertificate.PrivateKey; byte[] result = privateKey.Decrypt(key, true); sd.AesAlgorithm = new AES128_ECB(result); return(true); } catch (Exception e) { lock (objLock) { clientSessions.Remove(sd.Address); } Console.WriteLine(e.Message); } } return(false); }
public string EncryptHashRSA <T>(T data, string privateKey_RSA) { using (var rsa = new RSACryptoServiceProvider()) { try { RSAParameters RSAKey; { var sr = new StringReader(privateKey_RSA); var xs = new XmlSerializer(typeof(RSAParameters)); RSAKey = (RSAParameters)xs.Deserialize(sr); } rsa.ImportParameters(RSAKey); var json = JsonSerializer.Serialize <T>(data); Console.WriteLine("Serialized data in EncryptHashRSA is:"); Console.WriteLine(json); Console.WriteLine(); var byteData = Encoding.UTF8.GetBytes(json); var encryptedHash = rsa.SignData(byteData, new MD5CryptoServiceProvider()); var base64Encrypted = Convert.ToBase64String(encryptedHash); Console.WriteLine("Encrypted hash in EncryptHashRSA is:"); Console.WriteLine(base64Encrypted); Console.WriteLine(); return(base64Encrypted); } finally { rsa.PersistKeyInCsp = false; } } }
public static string RSADecrypt(string content, string privateKeyPem, string charset) { try { RSACryptoServiceProvider rsaCsp = LoadCertificateFile(privateKeyPem); if (string.IsNullOrEmpty(charset)) { charset = DEFAULT_CHARSET; } byte[] data = Convert.FromBase64String(content); int maxBlockSize = rsaCsp.KeySize / 8; //解密块最大长度限制 if (data.Length <= maxBlockSize) { byte[] cipherbytes = rsaCsp.Decrypt(data, false); return(Encoding.GetEncoding(charset).GetString(cipherbytes)); } MemoryStream crypStream = new MemoryStream(data); MemoryStream plaiStream = new MemoryStream(); Byte[] buffer = new Byte[maxBlockSize]; int blockSize = crypStream.Read(buffer, 0, maxBlockSize); while (blockSize > 0) { Byte[] toDecrypt = new Byte[blockSize]; Array.Copy(buffer, 0, toDecrypt, 0, blockSize); Byte[] cryptograph = rsaCsp.Decrypt(toDecrypt, false); plaiStream.Write(cryptograph, 0, cryptograph.Length); blockSize = crypStream.Read(buffer, 0, maxBlockSize); } return(Encoding.GetEncoding(charset).GetString(plaiStream.ToArray())); } catch (Exception ex) { throw new AopException("DecryptContent = " + content + ",charset = " + charset, ex); } }
/// <summary> /// 签名验证 /// </summary> /// <param name="str">待验证的字符串</param> /// <param name="sign">加签之后的字符串</param> /// <returns>签名是否符合</returns> public bool SignCheck(string str, string sign, string str_publicKey) { try { byte[] bt = Encoding.GetEncoding("utf-8").GetBytes(str); var sha256 = new SHA256CryptoServiceProvider(); byte[] rgbHash = sha256.ComputeHash(bt); RSACryptoServiceProvider key = new RSACryptoServiceProvider(); key.FromXmlString(str_publicKey); RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key); deformatter.SetHashAlgorithm("SHA256"); byte[] rgbSignature = Convert.FromBase64String(sign); if (deformatter.VerifySignature(rgbHash, rgbSignature)) { return(true); } return(false); } catch { return(false); } }
/// <summary> /// Computes an RSA/SHA1 PKCS#1 v1.5 signature. /// </summary> public static byte[] RsaPkcs15Sha1_Sign( ArraySegment <byte> dataToSign, X509Certificate2 signingCertificate) { // extract the private key. RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)signingCertificate.PrivateKey; if (rsa == null) { throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "No private key for certificate."); } // compute the hash of message. MemoryStream istrm = new MemoryStream(dataToSign.Array, dataToSign.Offset, dataToSign.Count, false); SHA1 hash = new SHA1Managed(); byte[] digest = hash.ComputeHash(istrm); istrm.Close(); // create the signature. return(rsa.SignHash(digest, "SHA1")); }
private static void AddPermissionToCertificate(X509Certificate2 cert) { RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider; if (rsa == null) { return; } string keyfilepath = FindKey(rsa.CspKeyContainerInfo.UniqueKeyContainerName); FileInfo file = new FileInfo(System.IO.Path.Combine(keyfilepath, rsa.CspKeyContainerInfo.UniqueKeyContainerName)); FileSecurity fs = file.GetAccessControl(); SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); fs.AddAccessRule(new FileSystemAccessRule("NETWORK SERVICE", FileSystemRights.FullControl, AccessControlType.Allow)); fs.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.Read, AccessControlType.Allow)); fs.AddAccessRule(new FileSystemAccessRule("RHEV-M Admins", FileSystemRights.FullControl, AccessControlType.Allow)); fs.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.Read, AccessControlType.Allow)); file.SetAccessControl(fs); }
public void MakeKey() { //lets take a new CSP with a new 2048 bit rsa key pair RSACryptoServiceProvider csp = new RSACryptoServiceProvider(2048); //how to get the private key RSAParameters privKey = csp.ExportParameters(true); //and the public key ... RSAParameters pubKey = csp.ExportParameters(false); //converting the public key into a string representation string pubKeyString; { //we need some buffer var sw = new StringWriter(); //we need a serializer var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters)); //serialize the key into the stream xs.Serialize(sw, pubKey); //get the string from the stream pubKeyString = sw.ToString(); File.WriteAllText(pubKeyPath, pubKeyString); } string privKeyString; { //we need some buffer var sw = new StringWriter(); //we need a serializer var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters)); //serialize the key into the stream xs.Serialize(sw, privKey); //get the string from the stream privKeyString = sw.ToString(); File.WriteAllText(priKeyPath, privKeyString); } }
public static string Decryption(string strText) { string privateKeyXml = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot" + "/Keys/privateKey.xml"); using (var rsa = new RSACryptoServiceProvider(1024)) { try { FromXml(rsa, privateKeyXml); var resultBytes = Convert.FromBase64String(strText); var decryptedBytes = rsa.Decrypt(resultBytes, true); var decryptedData = Encoding.UTF8.GetString(decryptedBytes); return(decryptedData.ToString()); } catch (Exception ex) { throw ex; } finally { rsa.PersistKeyInCsp = false; } } }
private RSACryptoServiceProvider ComputeKey() { var certificateCollection = new X509Certificate2Collection(); certificateCollection.Import(Data, Password, X509KeyStorageFlags.Exportable); foreach (var certificate in certificateCollection) { if (!certificate.HasPrivateKey) { continue; } var key = certificate.PrivateKey as RSACryptoServiceProvider; var exportParameters = key.ExportParameters(includePrivateParameters: true); var cspParameters = new CspParameters { ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider" }; var result = new RSACryptoServiceProvider(cspParameters); result.ImportParameters(exportParameters); return(result); } throw new ArgumentException("The provided certificate does not have any private keys."); }
private string RSAEncrypt(string input, int size) { var data = Encoding.UTF8.GetBytes(input); using (var rsa = new RSACryptoServiceProvider(size)) { try { rsa.FromXmlString(input); var encryptedData = rsa.Encrypt(data, true); Console.WriteLine(Convert.ToString(encryptedData)); return(Convert.ToString(encryptedData)); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(""); } finally { rsa.PersistKeyInCsp = false; } } }
// Keys public static string Encrypt(string privateKeyText, string plainText) { // Variables CspParameters cspParams = null; byte[] plainBytes = null; byte[] encryptedBytes = null; // Select target CSP cspParams = new CspParameters(); cspParams.ProviderType = 1; // PROV_RSA_FULL //cspParams.ProviderName; // CSP name using (RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams)) { // Import public key rsaProvider.FromXmlString(privateKeyText); // Encrypt plain text plainBytes = Encoding.Unicode.GetBytes(plainText); encryptedBytes = rsaProvider.Encrypt(plainBytes, false); } return(Convert.ToBase64String(encryptedBytes)); }
/// <summary> /// 对文本进行签名 /// </summary> /// <param name="strToSign">被签名的文本</param> /// <param name="senderPrivateKeyXml">签名者的私钥(XML格式)</param> /// <returns>文本Hash值的签名/null</returns> public static string SenderHashAndSign(string strToSign, string senderPrivateKeyXml) { if (string.IsNullOrEmpty(strToSign) || string.IsNullOrEmpty(senderPrivateKeyXml)) { return(null); } string signature = null; using (RSACryptoServiceProvider myRsa = new RSACryptoServiceProvider()) { SHA1Managed hash = new SHA1Managed(); byte[] dataToSign = Encoding.UTF8.GetBytes(strToSign); byte[] hashedData; myRsa.FromXmlString(senderPrivateKeyXml); hashedData = hash.ComputeHash(dataToSign); var tmp = myRsa.SignHash(hashedData, CryptoConfig.MapNameToOID("SHA1")); signature = Convert.ToBase64String(tmp); } return(signature); }
public string GetDigitalSignature(Transaction umemeTrans) { // retrieve public key||@"C:\PegPayCertificates1\Orange\41.202.229.3.cer" string text = umemeTrans.CustRef + umemeTrans.CustName + umemeTrans.CustomerTel + umemeTrans.VendorTranId + umemeTrans.VendorCode + umemeTrans.Password + umemeTrans.PaymentDate + umemeTrans.Teller + umemeTrans.TransactionAmount + umemeTrans.Narration + umemeTrans.TransactionType; string certificate = @"E:\Certs\pegasus.pfx"; X509Certificate2 cert = new X509Certificate2(certificate, "Tingate710", X509KeyStorageFlags.UserKeySet); RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey; // Hash the data SHA1Managed sha1 = new SHA1Managed(); ASCIIEncoding encoding = new ASCIIEncoding(); byte[] data = encoding.GetBytes(text); byte[] hash = sha1.ComputeHash(data); // Sign the hash byte[] digitalCert = rsa.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")); string strDigCert = Convert.ToBase64String(digitalCert); return(strDigCert); }
public static string Decryption(string strText) { var testData = Encoding.UTF8.GetBytes(strText); using (var rsa = new RSACryptoServiceProvider(2048)) { try { var base64Encrypted = strText; // server decrypting data with private key rsa.FromXmlString(privateKey); var resultBytes = Convert.FromBase64String(base64Encrypted); var decryptedBytes = rsa.Decrypt(resultBytes, true); var decryptedData = Encoding.UTF8.GetString(decryptedBytes); return(decryptedData.ToString()); } finally { rsa.PersistKeyInCsp = false; } } }
public static void Main(String[] args) { try { // Generate a signing key. RSACryptoServiceProvider Key = new RSACryptoServiceProvider(); // Create an XML file to sign. CreateSomeXml("Example.xml"); Console.WriteLine("New XML file created."); // Sign the XML that was just created and save it in a // new file. SignXmlFile("Example.xml", "signedExample.xml", Key); Console.WriteLine("XML file signed."); // Verify the signature of the signed XML. Console.WriteLine("Verifying signature..."); bool result = VerifyXmlFile("SignedExample.xml", Key); // Display the results of the signature verification to // the console. if (result) { Console.WriteLine("The XML signature is valid."); } else { Console.WriteLine("The XML signature is not valid."); } } catch (CryptographicException e) { Console.WriteLine(e.Message); } }
// We can provide a default implementation of ToXmlString because we require // every RSA implementation to implement ImportParameters // If includePrivateParameters is false, this is just an XMLDSIG RSAKeyValue // clause. If includePrivateParameters is true, then we extend RSAKeyValue with // the other (private) elements. public string GetXmlStringInNotSupportPlatform(RSACryptoServiceProvider provider, bool includePrivateParameters) { // From the XMLDSIG spec, RFC 3075, Section 6.4.2, an RSAKeyValue looks like this: /* * <element name="RSAKeyValue"> * <complexType> * <sequence> * <element name="Modulus" type="ds:CryptoBinary"/> * <element name="Exponent" type="ds:CryptoBinary"/> * </sequence> * </complexType> * </element> */ // we extend appropriately for private components RSAParameters rsaParams = provider.ExportParameters(includePrivateParameters); StringBuilder sb = new StringBuilder(); sb.Append("<RSAKeyValue>"); // Add the modulus sb.Append("<Modulus>" + Convert.ToBase64String(rsaParams.Modulus) + "</Modulus>"); // Add the exponent sb.Append("<Exponent>" + Convert.ToBase64String(rsaParams.Exponent) + "</Exponent>"); if (includePrivateParameters) { // Add the private components sb.Append("<P>" + Convert.ToBase64String(rsaParams.P) + "</P>"); sb.Append("<Q>" + Convert.ToBase64String(rsaParams.Q) + "</Q>"); sb.Append("<DP>" + Convert.ToBase64String(rsaParams.DP) + "</DP>"); sb.Append("<DQ>" + Convert.ToBase64String(rsaParams.DQ) + "</DQ>"); sb.Append("<InverseQ>" + Convert.ToBase64String(rsaParams.InverseQ) + "</InverseQ>"); sb.Append("<D>" + Convert.ToBase64String(rsaParams.D) + "</D>"); } sb.Append("</RSAKeyValue>"); return(sb.ToString()); }
public static TResult Generate <TResult>(Func <string, string, TResult> success) { var cspParams = new CspParameters() { ProviderType = 1, // PROV_RSA_FULL Flags = CspProviderFlags.UseArchivableKey, KeyNumber = (int)KeyNumber.Exchange, }; using (var rsaProvider = new RSACryptoServiceProvider(2048, cspParams)) { // Export public key var publicKey = Convert.ToBase64String( Encoding.ASCII.GetBytes( rsaProvider.ToXmlString(false))); // Export private/public key pair var privateKey = Convert.ToBase64String( Encoding.ASCII.GetBytes( rsaProvider.ToXmlString(true))); return(success(publicKey, privateKey)); } }
public void GeneratePublicAndPrivateKeyData(string strToEncrypt) { try { // Create a UnicodeEncoder to convert between byte array and string. var ByteConverter = new UnicodeEncoding(); // Create byte arrays to hold original, encrypted, and decrypted data. byte[] dataToEncrypt = ByteConverter.GetBytes(strToEncrypt); byte[] encryptedData; byte[] decryptedData; // Create a new instance of RSACryptoServiceProvider to generate public and private key data. using (var RSA = new RSACryptoServiceProvider()) { // Pass the data to ENCRYPT, // the public key information (using RSACryptoServiceProvider.ExportParameters(false), and a boolean flag specifying no OAEP padding. encryptedData = RSAEncrypt(dataToEncrypt, RSA.ExportParameters(false), false); // Pass the data to DECRYPT, // the private key information (using RSACryptoServiceProvider.ExportParameters(true), and a boolean flag specifying no OAEP padding. decryptedData = RSADecrypt(encryptedData, RSA.ExportParameters(true), false); // Display the encrypted text to the console. Console.WriteLine("Encrypted {0}", Convert.ToBase64String(encryptedData, 0, encryptedData.Length)); // Display the decrypted plaintext to the console. Console.WriteLine("Decrypted plaintext {0}", ByteConverter.GetString(decryptedData)); } } catch (ArgumentNullException) { // Catch this exception in case the encryption did not succeed. Console.WriteLine("Encryption failed."); } }
public static byte[] GetKeyHash(this RSACryptoServiceProvider rsa, string entropy) { int entropyLength = Encoding.UTF8.GetByteCount(entropy); RSAParameters rsaParams = rsa.ExportParameters(false); byte[] shaInput; byte[] shaOutput; int i = 0; shaInput = new byte[rsaParams.Modulus.Length + rsaParams.Exponent.Length + entropyLength]; rsaParams.Modulus.CopyTo(shaInput, i); i += rsaParams.Modulus.Length; rsaParams.Exponent.CopyTo(shaInput, i); i += rsaParams.Exponent.Length; i += Encoding.UTF8.GetBytes(entropy, 0, entropy.Length, shaInput, i); using (SHA256 sha = SHA256.Create()) { shaOutput = sha.ComputeHash(shaInput); } return(shaOutput); }
public void ParserCanSignAuthnRequestWithRsaKey() { // Arrange var key = new RSACryptoServiceProvider(); var evilKey = new RSACryptoServiceProvider(); var binding = new HttpRedirectBindingBuilder() { Request = string.Empty.PadLeft(500, 'a'), //SigningCertificate = key }; var url = new Uri("http://localhost/?" + binding.ToQuery()); // Act var parser = new HttpRedirectBindingParser(url); // Assert Assert.True(parser.IsSigned); Assert.True(parser.IsRequest); Assert.True(!parser.IsResponse); Assert.True(parser.CheckSignature(key)); Assert.False(parser.CheckSignature(evilKey)); }
private static void Main() { Stopwatch time = new Stopwatch(); UnicodeEncoding ByteConverter = new UnicodeEncoding(); RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); time.Start(); byte[] text = Encoding.UTF8.GetBytes("aliakseicharniauski"); byte[] crypted = RSAcl.Encryption(text, RSA.ExportParameters(false), false); string cryptedText = Convert.ToBase64String(crypted); time.Stop(); Console.WriteLine($"Зашифрованное сообщение: {cryptedText} | {(float)time.ElapsedMilliseconds / 1000} секунд"); time.Reset(); time.Start(); string decryptedText = RSAcl.Decryption(crypted, RSA.ExportParameters(true), false); time.Stop(); Console.WriteLine($"Расшифрованное сообщение: {decryptedText} | {(float)time.ElapsedMilliseconds / 1000} секунд"); Console.ReadKey(); }
public void NotifyCSEncryptedSessionKeyMessage(IService service, ProudSession session, NotifyCSEncryptedSessionKeyMessage message) { using (var rsa = new RSACryptoServiceProvider(1024)) { rsa.ImportCspBlob(message.Key); session.EncryptContext = new EncryptContext(128 /*_filter.Config.EncryptedMessageKeyLength*/); byte[] blob; using (var w = new BinaryWriter(new PooledMemoryStream(service.ArrayPool))) { w.Write((byte)1); w.Write((byte)2); w.Write((byte)0); w.Write((byte)0); w.Write(26625); w.Write(41984); var encrypted = rsa.Encrypt(session.EncryptContext.RC4.Key, false); w.Write(encrypted.Reverse()); blob = w.ToArray(); } session.Send(new NotifyCSSessionKeySuccessMessage(blob)); } }
public static string Encrypt(string data) { var rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(ChiavePubblica); var dataToEncrypt = _encoder.GetBytes(data); var encryptedByteArray = rsa.Encrypt(dataToEncrypt, false).ToArray(); var length = encryptedByteArray.Count(); var item = 0; var sb = new StringBuilder(); foreach (var x in encryptedByteArray) { item++; sb.Append(x); if (item < length) { sb.Append(","); } } return(sb.ToString()); }
// Load private and or public key information from the key store. // This overloaded version of the method loads the information from the user // section if "useMachineStore" is false, otherwise it loads the information // from the machine section. The method will return false if the entry does // not exist. public bool LoadFromContainer(string containerName, bool useMachineStore) { // Create new cryptographic service provider parameters object CspParameters cspParameters = new CspParameters(); // Set the container name, which in this case is the MAC address cspParameters.KeyContainerName = containerName; // This flag indicates that the entry must exist. Without setting this // the application will return a random key. This flag is also what causes // an error to be thrown in the following try-catch. cspParameters.Flags = CspProviderFlags.UseExistingKey; // Set the machine store flag if necessary if (useMachineStore) { cspParameters.Flags |= CspProviderFlags.UseMachineKeyStore; } // If this throws an error then the entry does not exist try { // Create temporary RSA encryption in order to load the information from the // key store and import into classes' RSA encryption object. using (RSACryptoServiceProvider tempRsa = new RSACryptoServiceProvider(cspParameters)) { // Import key information from the key store to the current class RSA // encryption object. _rsa.ImportParameters(tempRsa.ExportParameters(!tempRsa.PublicOnly)); } } catch { // The entry does not exist return(false); } // The entry was retrieved return(true); }
public void TestRSASigning() { HttpRedirectBindingBuilder binding = new HttpRedirectBindingBuilder(); RSACryptoServiceProvider key = new RSACryptoServiceProvider(); binding.signingKey = key; binding.Request = string.Empty.PadLeft(500, 'a'); // Parse the result Uri url = new Uri("http://localhost/?" + binding.ToQuery()); HttpRedirectBindingParser parser = new HttpRedirectBindingParser(url); Assert.That(parser.IsSigned); Assert.That(parser.IsRequest); Assert.That(!parser.IsResponse); Assert.That(parser.CheckSignature(key)); // Create a new key set, and check that it can not verify the signature. RSACryptoServiceProvider evilKey = new RSACryptoServiceProvider(); Assert.IsFalse(parser.CheckSignature(evilKey)); }
private void ImprtPubKey_Click(object sender, EventArgs e) { try { StreamReader sr = new StreamReader(PubKeyFile); cspp.KeyContainerName = keyName; rsa = new RSACryptoServiceProvider(cspp); string keytxt = sr.ReadToEnd(); rsa.FromXmlString(keytxt); rsa.PersistKeyInCsp = true; if (rsa.PublicOnly == true) { label1.Text = "Key: " + cspp.KeyContainerName + " - Container contains only public key"; } else { label1.Text = "Key: " + cspp.KeyContainerName + " - Container contains Full Key Pair"; } sr.Close(); } catch (Exception ex) { MessageBox.Show("Cannot import Public Key\r\n" + ex.Message); } }
/// <summary> /// Gets the decrypted password using the RSA private key which can be found in the /// PEM file for the key pair. /// </summary> /// <param name="rsaPrivateKey">The RSA private key from the PEM file</param> /// <returns>The decrypted password</returns> public string GetDecryptedPassword(string rsaPrivateKey) { RSAParameters rsaParams; try { rsaParams = new PemReader(new StringReader(rsaPrivateKey.Trim())).ReadPrivatekey(); } catch (Exception e) { throw new AmazonEC2Exception("Invalid RSA Private Key", e); } RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(rsaParams); byte[] encryptedBytes = Convert.FromBase64String(this.PasswordData); var decryptedBytes = rsa.Decrypt(encryptedBytes, false); string decrypted = Encoding.UTF8.GetString(decryptedBytes); return(decrypted); }