public ExportParameters ( bool includePrivateParameters ) : |
||
includePrivateParameters | bool | |
return |
public static D2LSecurityToken CreateTokenWithTimeRemaining( TimeSpan remaining, Guid? id = null ) { id = id ?? Guid.NewGuid(); var validTo = DateTime.UtcNow + remaining; var validFrom = validTo - TimeSpan.FromHours( 1 ); RSAParameters privateKey; using( var csp = new RSACryptoServiceProvider( Keys.Constants.GENERATED_RSA_KEY_SIZE ) { PersistKeyInCsp = false } ) { privateKey = csp.ExportParameters( includePrivateParameters: true ); } return new D2LSecurityToken( id.Value, validFrom, validTo, keyFactory: () => { var csp = new RSACryptoServiceProvider() { PersistKeyInCsp = false }; csp.ImportParameters( privateKey ); var key = new RsaSecurityKey( csp ); return new Tuple<AsymmetricSecurityKey, IDisposable>( key, csp ); } ); }
static void Main(string[] args) { string KeyContainerName = "MyKeyContainer"; string clearText = "This is the data we want to encrypt!"; CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = KeyContainerName; RSAParameters publicKey; RSAParameters privateKey; using(var rsa = new RSACryptoServiceProvider(cspParams)) { rsa.PersistKeyInCsp = true; publicKey = rsa.ExportParameters(false); privateKey = rsa.ExportParameters(true); rsa.Clear(); } byte[] encrypted = EncryptUsingRSAParam(clearText, publicKey); string decrypted = DecryptUsingRSAParam(encrypted, privateKey); Console.WriteLine("Asymmetric RSA - Using RSA Params"); Console.WriteLine("Encrypted:{0}", Convert.ToBase64String(encrypted)); Console.WriteLine("Decrypted:{0}", decrypted); Console.WriteLine("Asymmetric RSA - Using Persistent Key Container"); encrypted = EncryptUsingContainer(clearText, KeyContainerName); decrypted = DecryptUsingContainer(encrypted, KeyContainerName); Console.WriteLine("Encrypted:{0}", Convert.ToBase64String(encrypted)); Console.WriteLine("Decrypted:{0}", decrypted); Console.ReadLine(); }
static void Main(string[] args) { try { UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte[] dataToEncrypt = ByteConverter.GetBytes("bbbbbbbb"); byte[] encryptedData; byte[] decryptedData; char result; using(RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { encryptedData = RSAEncrypt(dataToEncrypt, RSA.ExportParameters(false), false); foreach (byte number in encryptedData) { result = Convert.ToChar(number); Console.WriteLine($"number: {number} convert: {result}"); } Console.WriteLine($"tam> {encryptedData.Length}"); decryptedData = RSADecrypt(encryptedData, RSA.ExportParameters(true), false); Console.WriteLine($"1 - {ByteConverter.GetString(decryptedData)}"); } } catch (ArgumentNullException) { Console.WriteLine("Encryption failed"); } Console.ReadKey(); }
static void Main(string[] args) { var rsa = new RSACryptoServiceProvider(); _publicKey = rsa.ExportParameters(false); _privateKey = rsa.ExportParameters(true); Console.WriteLine("\n********* Public key info *******************"); printInfo(_publicKey); Console.WriteLine("\n********* Private key info *******************"); printInfo(_privateKey); var message = "I am a plain text message"; var messageContent = Encoding.UTF8.GetBytes(message.ToCharArray()); Console.WriteLine("**** Plain Message ****"); Console.WriteLine(Encoding.UTF8.GetString(messageContent)); var encrypter = new RSACryptoServiceProvider(); encrypter.ImportParameters(_publicKey); var encryptedMessage = encrypter.Encrypt(messageContent, true); Console.WriteLine("**** Encrypted Message ****"); Console.WriteLine(Convert.ToBase64String(encryptedMessage)); var decrypter = new RSACryptoServiceProvider(); decrypter.ImportParameters(_privateKey); var decryptedMessage = decrypter.Decrypt(encryptedMessage, true); Console.WriteLine("**** Decrypted Message ****"); Console.WriteLine(Encoding.UTF8.GetString(decryptedMessage)); }
static OAuthServerHelper() { RSAParameters privateRsaParameters; RSAParameters publicRsaParameters; using (var rsaKeyGen = new RSACryptoServiceProvider(RsaKeySize)) { privateRsaParameters = rsaKeyGen.ExportParameters(true); publicRsaParameters = rsaKeyGen.ExportParameters(false); } Tuple<byte[], byte[]> aesKeyAndIV; using (var aesKeyGen = new AesCryptoServiceProvider()) { aesKeyAndIV = Tuple.Create(aesKeyGen.Key, aesKeyGen.IV); } rsa = new ThreadLocal<RSACryptoServiceProvider>(() => { var result = new RSACryptoServiceProvider(); result.ImportParameters(privateRsaParameters); return result; }); aes = new ThreadLocal<AesCryptoServiceProvider>(() => { var result = new AesCryptoServiceProvider(); result.Key = aesKeyAndIV.Item1; result.IV = aesKeyAndIV.Item2; return result; }); rsaExponent = OAuthHelper.BytesToString(publicRsaParameters.Exponent); rsaModulus = OAuthHelper.BytesToString(publicRsaParameters.Modulus); }
public void CreateNewKey() { mRsa = new RSACryptoServiceProvider(mKeySize); mRsa.PersistKeyInCsp = false; mPublicKey = mRsa.ExportParameters(false); mPrivateKey = mRsa.ExportParameters(true); }
static void Main(string[] args) { // Create message and signature on your end string message = "Here is the license message"; var secret = "wangchunlei"; var converter = new ASCIIEncoding(); byte[] plainText = converter.GetBytes(secret); var rsaWrite = new RSACryptoServiceProvider(); var privateParams = rsaWrite.ExportParameters(true); // Generate the public key / these can be sent to the user. var publicParams = rsaWrite.ExportParameters(false); byte[] signature = rsaWrite.SignData(plainText, new SHA1CryptoServiceProvider()); // Verify from the user's side. Note that only the public parameters // are needed. var rsaRead = new RSACryptoServiceProvider(); rsaRead.ImportParameters(publicParams); if (rsaRead.VerifyData(plainText, new SHA1CryptoServiceProvider(), signature)) { Console.WriteLine("Verified!"); } else { Console.WriteLine("NOT verified!"); } }
public void AssignNewKey() { using (var rsa = new RSACryptoServiceProvider(2048)) { rsa.PersistKeyInCsp = false; //in memory publicKey = rsa.ExportParameters(false); privateKey = rsa.ExportParameters(true); return; //to file File.WriteAllText(@"C:\git\CryptographyDemo\CryptographyDemo\bin\Debug\public.txt", rsa.ToXmlString(false)); File.WriteAllText(@"C:\git\CryptographyDemo\CryptographyDemo\bin\Debug\private.txt", rsa.ToXmlString(true)); } //To key container, stored for windows user const int providerRsaFull = 1; CspParameters cspParams = new CspParameters(providerRsaFull); cspParams.KeyContainerName = "TomsContainer"; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; var rsa2 = new RSACryptoServiceProvider(cspParams); rsa2.PersistKeyInCsp = true; // SHOULD THEN DELETE KEY }
public ProxyRsaKeyParameters(RSACryptoServiceProvider proxy) : base(false, new Math.BigInteger(1, proxy.ExportParameters(false).Modulus), new Math.BigInteger(1, proxy.ExportParameters(false).Exponent)) { this.proxy = proxy; }
public static RSAViewModel rsa2(RSAViewModel model) { try { int keySize = 1024; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize); RSAParameters publickey = rsa.ExportParameters(false); // don't export private key RSAParameters privatekey = rsa.ExportParameters(true); // export private key //\b 123\b0 model.PublicKey = "e=" + ByteToString(publickey.Exponent) + Environment.NewLine + "n=" + ByteToString(publickey.Modulus); model.PrivateKey = "d=" + ByteToString(privatekey.D) + Environment.NewLine + "n=" + ByteToString(publickey.Modulus); rsa.ImportParameters(publickey); byte[] encryptedData = rsa.Encrypt(StringToByte(model.PlainText), true); model.CipherText=ByteToString(encryptedData); rsa.ImportParameters(privatekey); byte[] decryptedData = rsa.Decrypt(encryptedData, true); model.DecryptedText = ByteToAscii(decryptedData); } catch (CryptographicException ex) { } return model; }
public KeyPair GenerateKeypair(EncryptionType encryption) { int modulus; switch (encryption) { case EncryptionType.RSA_512: modulus = 512; break; case EncryptionType.RSA_1024: modulus = 1024; break; case EncryptionType.RSA_1536: modulus = 1536; break; case EncryptionType.RSA_2048: modulus = 2048; break; case EncryptionType.RSA_4096: modulus = 4096; break; default: throw new ArgumentException("encryption"); } KeyPair kp = null; using (var rsa = new RSACryptoServiceProvider(modulus)) { try { var privParams = rsa.ExportParameters(true); var pubParams = rsa.ExportParameters(false); var privBlob = rsa.ToXmlString(true); var pubBlob = rsa.ToXmlString(false); kp = new KeyPair { PrivKey = privBlob, PubKey = pubBlob }; } catch (Exception) { throw; } finally { rsa.PersistKeyInCsp = false; } } return kp; }
public static void CreateKeys(out string publicKey, out string privateKey) { using (var rsa = new RSACryptoServiceProvider()) { publicKey = WritePublicKey(rsa.ExportParameters(false)); privateKey = WritePrivateKey(rsa.ExportParameters(true)); } }
private static void Gravar(RSACryptoServiceProvider rsa) { RSAParameters p = rsa.ExportParameters(false); Gravar("ChavePublica.sec", p); p = rsa.ExportParameters(true); Gravar("ChavePublicaPrivada.sec", p); }
//Use this test to generate a new public/private keypair //[TestMethod] public void RSAParameters() { var rsa = new RSACryptoServiceProvider(); var privateParameters = rsa.ExportParameters(true); var publicParameters = rsa.ExportParameters(false); Debug.WriteLine(rsa.ToXmlString(true)); Debug.WriteLine(rsa.ToXmlString(false)); }
public void AssignNewKey() { using (var rsa = new RSACryptoServiceProvider(2048)) { rsa.PersistKeyInCsp = false; _publicKey = rsa.ExportParameters(false); _privateKey = rsa.ExportParameters(true); } }
/// <summary> /// Used to acquire a public key and privately store the private key, intended to be used /// to establish initial trust with a new account. /// </summary> /// <returns>The public version of the key</returns> public static RSAParameters GetPubKey() { using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSAParameters val = RSA.ExportParameters(false); vault.Add(Encoding.ASCII.GetString(val.Modulus), RSA.ExportParameters(true)); return val; } }
/// <summary> /// 测试 生成非对称密钥. /// </summary> public static void DoTest() { // Generate a public/private key pair. RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); // 每当创建不对称算法类的新实例时,都生成一个公钥/私钥对。创建该类的新实例后,可以用以下两种方法之一提取密钥信息: // ToXMLString 方法,它返回密钥信息的 XML 表示形式。 Console.WriteLine("仅仅包含公钥的情况!"); Console.WriteLine(RSA.ToXmlString(false)); Console.WriteLine("同时包含公钥与私钥的情况!"); Console.WriteLine(RSA.ToXmlString(true)); // ExportParameters 方法,它返回保存密钥信息的 RSAParameters 结构。 // 将使用 RSACryptoServiceProvider 创建的密钥信息导出为 RSAParameters 对象。 RSAParameters RSAKeyInfo = RSA.ExportParameters(false); // 取得目标的 公钥的 XML 信息. string xmlString = RSA.ToXmlString(false); // Create a UnicodeEncoder to convert between byte array and string. UnicodeEncoding ByteConverter = new UnicodeEncoding(); string source = "Data to Encrypt 这个是一个用于测试加密的文本信息!"; //Create byte arrays to hold original, encrypted, and decrypted data. byte[] dataToEncrypt = ByteConverter.GetBytes(source); byte[] encryptedData; Console.WriteLine("原始文本信息:{0}", source); Console.WriteLine("原始数据!"); ByteArrayOutput.Print(dataToEncrypt); // 这里创建一个新的 RSACryptoServiceProvider RSACryptoServiceProvider RSA2 = new RSACryptoServiceProvider(); // 通过 XML 字符串中的密钥信息初始化 RSA 对象。 RSA2.FromXmlString(xmlString); // 公钥加密. encryptedData = RSAEncrypt(dataToEncrypt, RSA2.ExportParameters(false), false); Console.WriteLine("公钥加密后的数据!"); ByteArrayOutput.Print(encryptedData); byte[] decryptedData; // 解密 decryptedData = RSADecrypt(encryptedData, RSA.ExportParameters(true), false); Console.WriteLine("私钥解密后的数据!"); ByteArrayOutput.Print(decryptedData); // 输出. Console.WriteLine("私钥解密后的文本: {0}", ByteConverter.GetString(decryptedData)); }
public MFTestResults RsaTest_ExportImportTest() { bool testResult = true; try { using (Session session = new Session("", MechanismType.RSA_PKCS)) using (CryptoKey privateKey = CryptoKey.LoadKey(session, m_importKeyPrivate)) { string dataToSign = "This is a simple message to be encrypted"; byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(dataToSign); using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(privateKey)) { RSAParameters kp1 = rsa.ExportParameters(true); byte[] sig = rsa.SignData(data); rsa.ImportParameters(kp1); RSAParameters kp2 = rsa.ExportParameters(true); testResult &= CompareByteArray(kp1.D, kp2.D); testResult &= CompareByteArray(kp1.DP, kp2.DP); testResult &= CompareByteArray(kp1.DQ, kp2.DQ); testResult &= CompareByteArray(kp1.Exponent, kp2.Exponent); testResult &= CompareByteArray(kp1.InverseQ, kp2.InverseQ); testResult &= CompareByteArray(kp1.Modulus, kp2.Modulus); testResult &= CompareByteArray(kp1.P, kp2.P); testResult &= CompareByteArray(kp1.Q, kp2.Q); testResult &= CompareByteArray(m_importKeyPrivate[2].Value, kp1.Modulus); testResult &= CompareByteArray(m_importKeyPrivate[3].Value, kp1.Exponent); testResult &= CompareByteArray(m_importKeyPrivate[4].Value, kp1.D); testResult &= CompareByteArray(m_importKeyPrivate[5].Value, kp1.P); testResult &= CompareByteArray(m_importKeyPrivate[6].Value, kp1.Q); testResult &= CompareByteArray(m_importKeyPrivate[7].Value, kp1.DP); testResult &= CompareByteArray(m_importKeyPrivate[8].Value, kp1.DQ); testResult &= CompareByteArray(m_importKeyPrivate[9].Value, kp1.InverseQ); testResult &= rsa.VerifyData(data, sig); } } } catch (Exception ex) { Log.Exception("Unexpected Exception", ex); testResult = false; } return (testResult ? MFTestResults.Pass : MFTestResults.Fail); }
public static void GenerateKeys(out byte[] publicKey, out byte[] privateKey) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(KeySize); /* windows phone 7 doesn't support ExportCspBlob privateKey = rsa.ExportCspBlob(true); publicKey = rsa.ExportCspBlob(false); */ privateKey = FromRSAParametersToBinary(rsa.ExportParameters(true), true); publicKey = FromRSAParametersToBinary(rsa.ExportParameters(false), false); }
static void RSAEncrypt() { UnicodeEncoding bytConvertor = new UnicodeEncoding(); byte[] plainData = bytConvertor.GetBytes("Sample data"); RSACryptoServiceProvider RSAServiceProvider = new RSACryptoServiceProvider(); byte[] enData = Encrypt(plainData, RSAServiceProvider.ExportParameters(false)); Console.WriteLine("Encrypted Output: {0}", bytConvertor.GetString(enData)); byte[] deData = Decrypt(enData, RSAServiceProvider.ExportParameters(true)); Console.WriteLine("Decrypted Output: {0}", bytConvertor.GetString(deData)); }
public void ImportKeys(string xmlString = "") { using (var rsa = new RSACryptoServiceProvider(KEY_SIZE)) { if (!string.IsNullOrWhiteSpace(xmlString)) rsa.FromXmlString(xmlString); rsa.PersistKeyInCsp = false; _publicKey = rsa.ExportParameters(false); _privateKey = rsa.ExportParameters(true); } }
private void uxGenBtn_Click(object sender, EventArgs e) { RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAKeyInfo = RSA.ExportParameters(true); RSA.PersistKeyInCsp = false; uxKeyText.Text = RSA.ToXmlString(true); }
static void rsaEncr() { using (var rsa = new RSACryptoServiceProvider(1024)) { try { //RSAParameters privateKey = rsa.ExportParameters(true); RSAParameters publicKey = rsa.ExportParameters(false); var bytes = asd.ConvertPublicKey(publicKey); File.WriteAllBytes("test.pem", bytes); ////var asnMessage = AsnKeyBuilder.PublicKeyToX509(publicKey); //var asnMessage = AsnKeyBuilder.PrivateKeyToPKCS8(privateKey); //var asnBytes = asnMessage.GetBytes(); X509Certificate2 cert = new X509Certificate2(bytes, "", X509KeyStorageFlags.MachineKeySet); //var a = new AsymmetricAlgorithm() //Console.WriteLine(); } finally { rsa.PersistKeyInCsp = false; } } }
static public byte[] RSAEncrypt(int bits, byte[] dataToEncrypt, RSAParameters rsaKeyInfo, bool doOAEPPadding) { try { byte[] encryptedData; //Create a new instance of RSACryptoServiceProvider. using (var rsa = new RSACryptoServiceProvider(bits)) { //Import the RSA Key information. This only needs //toinclude the public key information. rsa.ImportParameters(rsaKeyInfo); var rsaExportParameters = rsa.ExportParameters(true); var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa); rsaFormatter.SetHashAlgorithm("SHA256"); //Encrypt the passed byte array and specify OAEP padding. //OAEP padding is only available on Microsoft Windows XP or //later. encryptedData = rsa.Encrypt(dataToEncrypt, doOAEPPadding); } return encryptedData; } //Catch and display a CryptographicException //to the console. catch (CryptographicException e) { Console.WriteLine(e.Message); return null; } }
private void ImportPubKey_Click(object sender, EventArgs e) { openFileDialog1.InitialDirectory = SrcFolder; if (openFileDialog1.ShowDialog() == DialogResult.OK) { string fName = openFileDialog1.FileName; if (fName != null) { FileInfo fInfo = new FileInfo(fName); // Pass the file name without the path. string name = fInfo.FullName; StreamReader sr = new StreamReader(name); cspp.KeyContainerName = keyName; rsa = new RSACryptoServiceProvider(2048, cspp); string keytxt = sr.ReadToEnd(); rsa.FromXmlString(keytxt); rsa.PersistKeyInCsp = true; DataContainer.publicKey = rsa.ExportParameters(false); if (rsa.PublicOnly == true) { label1.Text = "Key: Public Only"; } else { label1.Text = "Key: Full Key Pair for: " + cspp.KeyContainerName; } sr.Close(); } } }
private void pictureBox1_Click(object sender, EventArgs e) { try { OpenFileDialog opf = new OpenFileDialog(); opf.Title = ""; opf.ShowDialog(); //string fc = System.IO.File.ReadAllText(opf.FileName); UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte[] dataToEncrypt = ByteConverter.GetBytes(System.IO.File.ReadAllText(opf.FileName)); byte[] encryptedData; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { encryptedData = encryptionfuncs.RSADecrypt(dataToEncrypt, RSA.ExportParameters(true), false); } System.IO.File.WriteAllBytes(opf.FileName, encryptedData); MessageBox.Show("File decrypted."); } catch (Exception) { } }
protected override void OnConnect() { base.OnConnect(); m_rsa = new RSACryptoServiceProvider(); RSAParameters para = m_rsa.ExportParameters(false); SendRSAKey(para.Modulus, para.Exponent); }
public RSASigner(RSACryptoServiceProvider provider) { _rsaCrypto = provider; _blockLength = _rsaCrypto.ExportParameters(false).Modulus.Length; _maxBlockLengthWithPadding = _blockLength - Padding; _algorithm = SHA1.Create(); }
public override void Encrypt() { //RSA Rsa = new RSA(); //base.Component.Text = Rsa.encode(base.Component.tp.Text); try { UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte[] encryptedData; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.ImportParameters(RSA.ExportParameters(false)); byte[] Data = ByteConverter.GetBytes(base.Component.tp.Text.ToString()); encryptedData = RSA.Encrypt(Data , false); } base.Component.Text = ByteConverter.GetString(encryptedData); } //Catch and display a CryptographicException //to the console. catch (CryptographicException e) { Console.WriteLine(e.Message); base.Component.Text = base.Component.tp.Text.ToString(); } }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; CspParameters csp = new CspParameters(); csp.Flags = CspProviderFlags.UseMachineKeyStore; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp); RSAParameters para = rsa.ExportParameters(true); StringBuilder model = new StringBuilder(); for (int i = 0; i < para.Modulus.Length; i++) { model.Append(para.Modulus[i].ToString("X2")); } StringBuilder exponent = new StringBuilder(); for (int i = 0; i <para.Exponent.Length; i ++) { exponent.Append(para.Exponent[i].ToString("X2")); } XElement list = new XElement("list"); XElement pri = new XElement("private", new XAttribute("key", rsa.ToXmlString(true))); XElement pub = new XElement("public", new XAttribute("model", model.ToString()),new XAttribute("exponent",exponent.ToString())); list.Add(pri); list.Add(pub); context.Response.Write(list.ToString()); }
internal static bool GetKey(bool isServer, out RSAParameters CSPRSAPARAM) { CSPRSAPARAM = default(RSAParameters); RSACryptoServiceProvider rsaCrypt = null; bool result; try { string _rsaKey = ConfigurationSettings.AppSettings["RSAKey"].ToString(); if (_rsaKey != string.Empty) { rsaCrypt = new RSACryptoServiceProvider(); rsaCrypt.FromXmlString(_rsaKey.Replace("(", "<").Replace(")", ">")); CSPRSAPARAM = rsaCrypt.ExportParameters(isServer); result = true; } else { result = false; } } catch (Exception ex) { string _msg = ex.ToString(); result = false; } finally { if (rsaCrypt != null) { rsaCrypt.Clear(); } rsaCrypt = null; } return result; }
public static RSAParameters RSAKeysFromXmlString(string nKey, bool nIncludePrivateParameters) { RSACryptoServiceProvider.UseMachineKeyStore = true; var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.FromXmlString(nKey); return(rsa.ExportParameters(nIncludePrivateParameters)); }
public static string decrypt(string elementToDesencrypt, string pathPublicKey) { string pem = System.IO.File.ReadAllText(pathPublicKey); byte[] Buffer = getBytesFromPEMFile(pem, "RSA PRIVATE KEY"); System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); System.Security.Cryptography.RSAParameters rsaParam = rsa.ExportParameters(false); rsaParam.Modulus = Buffer; rsa.ImportParameters(rsaParam); byte[] text = Encoding.UTF8.GetBytes(elementToDesencrypt); //Convert.FromBase64String(elementToDesencrypt) byte[] encryptedMessageByte = rsa.Decrypt(text, false); return(Convert.ToBase64String(encryptedMessageByte)); }
private void CreateAsmKeys_Click(object sender, EventArgs e) { DataContainer.User = username.Text; DialogResult dialogResult = MessageBox.Show("This will overwrite any existing keys for " + DataContainer.User.ToString() + ". Do you want to continue?", "WARNING", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { MessageBox.Show("New KeySet Created"); cspp.KeyContainerName = DataContainer.User; rsa = new RSACryptoServiceProvider(2048, cspp); //store a key pair in the key container. rsa.PersistKeyInCsp = true; if (rsa.PublicOnly == true) { label1.Text = "Key: " + cspp.KeyContainerName + " - Public Only"; } else { label1.Text = "Key: " + cspp.KeyContainerName + " - Full Key Pair"; } string promptValue = ShowDialog("Enter a file name", "New File"); string keyFileName = PubKeyFile + promptValue + ".txt"; Directory.CreateDirectory(EncrFolder); StreamWriter sw = new StreamWriter(keyFileName, false); sw.Write(rsa.ToXmlString(false)); sw.Close(); MessageBox.Show("Public Key Exported to:" + keyFileName); DataContainer.privateKey = rsa.ExportParameters(true); } else if (dialogResult == DialogResult.No) { //do nothing } }
private async Task CreateKeyForUser() { var csp = new System.Security.Cryptography.RSACryptoServiceProvider(1024); var rsakeyparam = csp.ExportParameters(true); var privkey = RSAConverter.ExportPrivateKey(csp); //var publicKey = RSAConverter.ExportPublicKey(csp); var publickeybytes = csp.ExportCspBlob(false); var publicKey = Convert.ToBase64String(publickeybytes); SelectedUser.RsaPublicKey = publicKey; var rsakeydata = System.Text.Encoding.UTF8.GetBytes(privkey); await JSRuntime.SaveFile(rsakeydata, $"{SelectedUser.Username}.pem"); SaveUser(); }
static void Main() { //lets take a new CSP with a new 2048 bit rsa key pair var csp = new System.Security.Cryptography.RSACryptoServiceProvider(2048); //how to get the private key var privKey = csp.ExportParameters(true); //and the public key ... var pubKey = csp.ExportParameters(false); //converting the public key into a string representation string pubKeyString = ""; { //we need some buffer var sw = new System.IO.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(); } //converting it back { //get a stream from the string var sr = new System.IO.StringReader(pubKeyString); //we need a deserializer var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters)); //get the object back from the stream pubKey = (RSAParameters)xs.Deserialize(sr); } //conversion for the private key is no black magic either ... omitted //we have a public key ... let's get a new csp and load that key csp = new RSACryptoServiceProvider(); csp.ImportParameters(pubKey); //we need some data to encrypt var plainTextData = "foobar"; //for encryption, always handle bytes... var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(plainTextData); //apply pkcs#1.5 padding and encrypt our data var bytesCypherText = csp.Encrypt(bytesPlainTextData, false); //we might want a string representation of our cypher text... base64 will do var cypherText = Convert.ToBase64String(bytesCypherText); /* * some transmission / storage / retrieval * * and we want to decrypt our cypherText */ //first, get our bytes back from the base64 string ... bytesCypherText = Convert.FromBase64String(cypherText); //we want to decrypt, therefore we need a csp and load our private key csp = new RSACryptoServiceProvider(); csp.ImportParameters(privKey); //decrypt and strip pkcs#1.5 padding bytesPlainTextData = csp.Decrypt(bytesCypherText, false); //get our original plainText back... plainTextData = System.Text.Encoding.Unicode.GetString(bytesPlainTextData); }
//=============================================================================== // Name: Function IALUGenerator_GenKey // Input: // ByRef Lic As ActiveLock3.ProductLicense - Product license // ByVal InstCode As String - Installation Code sent by the user // ByVal RegisteredLevel As String - Registration Level for the license. Default is "0" // Output: // String - Liberation key for the license // Purpose: Given the Installation Code, generates an Activelock license liberation key. // Remarks: None //=============================================================================== private string IALUGenerator_GenKey(ref ActiveLock3_6NET.ProductLicense Lic, string InstCode, [System.Runtime.InteropServices.OptionalAttribute, System.Runtime.InteropServices.DefaultParameterValueAttribute("0")] // ERROR: Optional parameters aren't supported in C# string RegisteredLevel) { // Take request code and decrypt it. string strReq = null; // 05.13.05 - ialkan Modified to merge DLLs into one strReq = modBase64.Base64_Decode(ref InstCode); // strReq now contains the {LockCode + vbLf + User} string string strLock = string.Empty; string strUser = string.Empty; GetLockAndUserFromInstallCode(strReq, ref strLock, ref strUser); Lic.Licensee = strUser; // registration date string strRegDate = null; // registered level Lic.RegisteredLevel = RegisteredLevel; strRegDate = Lic.RegisteredDate; string strEncrypted = null; // @todo Rethink this bit about encrypting the dates. // We need to keep in mind that the app does not have access to the private key, so and any decryption that requires private key // would not be possible. // Perhaps instead of encrypting, we could do MD5 hash of (regdate+lockcode)? //ActiveLockEventSink_ValidateValue strRegDate, strEncrypted // hash it //strEncrypted = ActiveLock3.MD5Hash(strEncrypted) strEncrypted = strRegDate; // get software codes ProductInfo ProdInfo = null; ProdInfo = IALUGenerator_RetrieveProduct(Lic.ProductName, Lic.ProductVer); Lic.ProductKey = ProdInfo.VCode; string strLic = null; strLic = Lic.ToString_Renamed() + Constants.vbLf + strLock; System.Diagnostics.Debug.WriteLine("strLic: " + Constants.vbCrLf + strLic); if (modALUGEN.strLeft(ProdInfo.VCode, 3) != "RSA") { // sign it string strSig = null; strSig = new string(Strings.Chr(0), 1024); // 05.13.05 - ialkan Modified to merge DLLs into one. Moved RSASign into a module strSig = modActiveLock.RSASign(ProdInfo.VCode, ProdInfo.GCode, strLic); // Create liberation key. This will be a base-64 encoded string of the whole license. string strLicKey = null; // 05.13.05 - ialkan Modified to merge DLLs into one strLicKey = modBase64.Base64_Encode(ref strSig); // update Lic with license key Lic.LicenseKey = strLicKey; // Print some info for debugging purposes System.Diagnostics.Debug.WriteLine("VCode: " + ProdInfo.VCode); System.Diagnostics.Debug.WriteLine("Lic: " + strLic); System.Diagnostics.Debug.WriteLine("Lic hash: " + modMD5.Hash(ref strLic)); System.Diagnostics.Debug.WriteLine("LicKey: " + strLicKey); System.Diagnostics.Debug.WriteLine("Sig: " + strSig); System.Diagnostics.Debug.WriteLine("Verify: " + modActiveLock.RSAVerify(ProdInfo.VCode, strLic, modBase64.Base64_Decode(ref strLicKey))); System.Diagnostics.Debug.WriteLine("===================================================="); } else { try { System.Security.Cryptography.RSACryptoServiceProvider rsaCSP = new System.Security.Cryptography.RSACryptoServiceProvider(); string strPublicBlob = null; string strPrivateBlob = null; strPublicBlob = ProdInfo.VCode; strPrivateBlob = ProdInfo.GCode; if (modALUGEN.strLeft(ProdInfo.GCode, 6) == "RSA512") { strPrivateBlob = modALUGEN.strRight(ProdInfo.GCode, Strings.Len(ProdInfo.GCode) - 6); } else { strPrivateBlob = modALUGEN.strRight(ProdInfo.GCode, Strings.Len(ProdInfo.GCode) - 7); } // import private key params into instance of RSACryptoServiceProvider rsaCSP.FromXmlString(strPrivateBlob); RSAParameters rsaPrivateParams = default(RSAParameters); //stores private key rsaPrivateParams = rsaCSP.ExportParameters(true); rsaCSP.ImportParameters(rsaPrivateParams); byte[] userData = Encoding.UTF8.GetBytes(strLic); AsymmetricSignatureFormatter asf = new RSAPKCS1SignatureFormatter(rsaCSP); HashAlgorithm algorithm = new SHA1Managed(); asf.SetHashAlgorithm(algorithm.ToString()); byte[] myhashedData = null; // a byte array to store hash value string myhashedDataString = null; myhashedData = algorithm.ComputeHash(userData); myhashedDataString = BitConverter.ToString(myhashedData).Replace("-", string.Empty); byte[] mysignature = null; // holds signatures mysignature = asf.CreateSignature(algorithm); string mySignatureBlock = null; mySignatureBlock = Convert.ToBase64String(mysignature); Lic.LicenseKey = mySignatureBlock; } catch (Exception ex) { modActiveLock.Set_Locale(modActiveLock.regionalSymbol); Err().Raise(AlugenGlobals.alugenErrCodeConstants.alugenProdInvalid, modTrial.ACTIVELOCKSTRING, ex.Message); } } // Serialize it into a formatted string string strLibKey = string.Empty; Lic.Save(ref strLibKey); return(strLibKey); }