public static LicenseServerConfiguration ReadConfiguration(string config, string existingRSAPublicKey = null) { try { var serializedData = MessagePackSerializer.Deserialize <SerializedLSC>(Convert.FromBase64String(config)); var extractedConfig = MessagePackSerializer.Deserialize <LicenseServerConfiguration>(serializedData.LSC); using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(2048)) { if (existingRSAPublicKey != null) { rsa.FromXmlString(existingRSAPublicKey); } else { rsa.FromXmlString(extractedConfig.RSAPublicKey); } if (rsa.VerifyData(serializedData.LSC, serializedData.Signature, System.Security.Cryptography.HashAlgorithmName.SHA256, System.Security.Cryptography.RSASignaturePadding.Pkcs1)) { // ok return(extractedConfig); } else { return(null); } } } catch (Exception ex) { return(null); } return(null); }
private void SaveButton_Click(object sender, EventArgs e) { UpdateList lst = new UpdateList(); List <Update> updates = new List <Update>(); foreach (Update u in listBox1.Items) { updates.Add(u); } lst.Updates = updates.ToArray(); lst.SignedHash = ""; System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.FromXmlString(m_privateKey); System.Xml.Serialization.XmlSerializer sr = new System.Xml.Serialization.XmlSerializer(typeof(UpdateList)); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { sr.Serialize(ms, lst); ms.Position = 0; lst.SignedHash = Convert.ToBase64String(rsa.SignData(ms, System.Security.Cryptography.SHA1.Create())); } using (System.IO.FileStream fs = new System.IO.FileStream(UpdateFile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) sr.Serialize(fs, lst); }
public static string Decrypt(string input, string key) { System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.FromXmlString(key); return(System.Text.Encoding.UTF8.GetString(rsa.Decrypt(ByteArrayFromString(input), false))); }
public bool SignatureDeformatter(string p_strHashbyteDeformatter, string p_strDeformatterData) { bool result; try { byte[] rgbHash = System.Convert.FromBase64String(p_strHashbyteDeformatter); System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider(); rSACryptoServiceProvider.FromXmlString(this.p_strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter rSAPKCS1SignatureDeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(rSACryptoServiceProvider); rSAPKCS1SignatureDeformatter.SetHashAlgorithm("MD5"); byte[] rgbSignature = System.Convert.FromBase64String(p_strDeformatterData); if (rSAPKCS1SignatureDeformatter.VerifySignature(rgbHash, rgbSignature)) { result = true; } else { result = false; } } catch { result = false; } return(result); }
private void buttonGenerateKey_Click(object sender, RoutedEventArgs e) { if (textUsername.Text.ToString().Equals("")) { MessageBox.Show("Username not defined"); return; } if (textPassword.Text.ToString().Equals("")) { MessageBox.Show("Password not defined"); return; } if (textKey.Text.ToString().Equals("")) { MessageBox.Show("Key not defined"); return; } string stringToCrypted = textUsername.Text.ToString() + ":" + textPassword.Text.ToString(); string text = textKey.Text.ToString(); var RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(text); byte[] machainechiffre = RSA.Encrypt(Encoding.Unicode.GetBytes(stringToCrypted), false); System.IO.File.WriteAllBytes(@"logNewUser.info", machainechiffre); MessageBox.Show("logNewUser.info généré"); }
static byte[] RSAEncrypt(byte[] bContent, string PublicKey) { System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(PublicKey); byte[] encryptedData = RSA.Encrypt(bContent, false); return(encryptedData); }
/// <summary> /// Will attempt to unregister a client from a server. /// </summary> /// <param name="serviceProxy">The server's service proxy. (Provides callback methods to the server.)</param> /// <param name="client">The client to unregister.</param> public void Unregister(IService serviceProxy, IClient client) { if ((serviceProxy != null) && (client != null)) { var boolConverter = new dodSON.Core.Converters.TypeSerializer <bool>(); var transportDataConverter = new dodSON.Core.Converters.TypeSerializer <TransportData>(); var clientConfigurationConverter = new dodSON.Core.Converters.TypeSerializer <IClientConfiguration>(); // ######## HELLO (create tunnel) // create public/private keys System.Security.Cryptography.RSACryptoServiceProvider serverCryptoProvider = null; var clientCryptoProvider = AsymmetricCryptoProvider; var clientPublicKey = clientCryptoProvider.ToXmlString(false); var clientPrivateKey = clientCryptoProvider.ToXmlString(true); var request = transportDataConverter.ToByteArray( new TransportData() { Alpha = ContextFor("Hello"), Beta = client.Id, Gamma = System.Text.Encoding.Unicode.GetBytes(clientPublicKey), Delta = null, Epsilon = null }); var response = transportDataConverter.FromByteArray(serviceProxy.RegistrationChannel(RegistrationTypeEnum.Unregister, request)); // ######## test for HELLO if ((response.Alpha == ContextFor("Hello")) && (response.Beta == client.Id)) { // ######## get server public key var serverPublicKey = System.Text.Encoding.Unicode.GetString(response.Gamma); serverCryptoProvider = AsymmetricCryptoProvider; serverCryptoProvider.FromXmlString(serverPublicKey); // ######## meet challenge request = transportDataConverter.ToByteArray( new TransportData() { Alpha = ContextFor("Challenge"), Beta = client.Id, Gamma = null, Delta = null, Epsilon = PrepareForTransport(ChallengeEvidence, serverCryptoProvider, TransportPartsLengthInBytes) }); if (boolConverter.FromByteArray(serviceProxy.RegistrationChannel(RegistrationTypeEnum.Unregister, request))) { request = transportDataConverter.ToByteArray( new TransportData() { Alpha = ContextFor("Unregister"), Beta = client.Id, Gamma = null, Delta = PrepareForTransport(clientConfigurationConverter.ToByteArray(client.ClientConfiguration), serverCryptoProvider, TransportPartsLengthInBytes), Epsilon = PrepareForTransport(ChallengeEvidence, serverCryptoProvider, TransportPartsLengthInBytes) }); serviceProxy.RegistrationChannel(RegistrationTypeEnum.Unregister, request); } } } }
/*暗号化*/ public static string Encrypt(string str, string publicKey) { System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.FromXmlString(publicKey); byte[] data = System.Text.Encoding.UTF8.GetBytes(str); byte[] encryptedData = rsa.Encrypt(data, false); return(System.Convert.ToBase64String(encryptedData)); }
private static async System.Threading.Tasks.Task <ResultType> TaskMain(Fee.Crypt.OnCryptTask_CallBackInterface a_callback_interface, byte[] a_binary, string a_key, Fee.TaskW.CancelToken a_cancel) #endif { ResultType t_ret; { t_ret.binary = null; t_ret.errorstring = null; } try{ //ハッシュの計算。 byte[] t_hash_binary = null; using (System.Security.Cryptography.SHA1Managed t_sha1 = new System.Security.Cryptography.SHA1Managed()){ t_hash_binary = t_sha1.ComputeHash(a_binary); } if (t_hash_binary == null) { t_ret.binary = null; t_ret.errorstring = "Task_CreateSignaturePrivateKey : hash == null"; } else { using (System.Security.Cryptography.RSACryptoServiceProvider t_rsa = new System.Security.Cryptography.RSACryptoServiceProvider()){ t_rsa.FromXmlString(a_key); //証明書作成。 System.Security.Cryptography.RSAPKCS1SignatureFormatter t_formatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(t_rsa); t_formatter.SetHashAlgorithm("SHA1"); t_ret.binary = t_formatter.CreateSignature(t_hash_binary); } } }catch (System.Exception t_exception) { t_ret.binary = null; t_ret.errorstring = "Task_CreateSignaturePrivateKey : " + t_exception.Message; } if (a_cancel.IsCancellationRequested() == true) { t_ret.binary = null; t_ret.errorstring = "Task_CreateSignaturePrivateKey : Cancel"; a_cancel.ThrowIfCancellationRequested(); } if (t_ret.binary == null) { if (t_ret.errorstring == null) { t_ret.errorstring = "Task_CreateSignaturePrivateKey : null"; } } return(t_ret); }
public string SignatureFormatter(string m_strHashbyteSignature) { byte[] rgbHash = System.Convert.FromBase64String(m_strHashbyteSignature); System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider(); rSACryptoServiceProvider.FromXmlString(this.p_strKeyPrivate); System.Security.Cryptography.RSAPKCS1SignatureFormatter rSAPKCS1SignatureFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(rSACryptoServiceProvider); rSAPKCS1SignatureFormatter.SetHashAlgorithm("MD5"); byte[] inArray = rSAPKCS1SignatureFormatter.CreateSignature(rgbHash); return(System.Convert.ToBase64String(inArray)); }
public static byte[] RSAEncrypt(byte[] input) { byte[] encrypted; using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(2048)) { rsa.PersistKeyInCsp = false; rsa.FromXmlString(publickey); encrypted = rsa.Encrypt(input, false); } return(encrypted); }
/// <summary> /// 校验License /// </summary> /// <param name="license"></param> static LicenseData ValidateLicense(string license) { if (string.IsNullOrEmpty(license)) { throw new LicenseException("License不可为空", 0); } var rsaProvider = new System.Security.Cryptography.RSACryptoServiceProvider(); rsaProvider.FromXmlString(_publicKey); var licenseDataStr = rsaProvider.DecryptUsePublic(license);//sample: hwId={string},ed={yyyy-MM-dd}; if (string.IsNullOrEmpty(licenseDataStr)) { throw new LicenseException("无效License, errorCode=1", 1); } var licenseData = licenseDataStr.Split(','); if (licenseData.Length != 3) { throw new LicenseException("无效License, errorCode=2", 2); } if (licenseData[0].Length < 4)//第1组数据SN,前3位为sn=,如果小于4位数据不正确,sn格式为XXXX-XXXX-XXXX-XXXX。 { throw new LicenseException("无效License, errorCode=3", 3); } if (licenseData[1].Length < 6)//第2组数据为硬件ID,前5位为hwId=,如果小于6位表示数据不正确。 { throw new LicenseException("无效License, errorCode=4", 4); } if (licenseData[2].Length < 4)//第3组数据为过期时间,前3位为ed=,如果小于4位表示数据不正确。 { throw new LicenseException("无效License, errorCode=5", 5); } var sn = licenseData[0].Substring(3); var hwId = licenseData[1].Substring(5); var localHardwareId = HardwareInfo.GetHardwareId(); if (!localHardwareId.Equals(hwId, StringComparison.OrdinalIgnoreCase)) { throw new LicenseException("无效License, errorCode=4,1", 41); } var ed = licenseData[2].Substring(3); var expiredDate = DateTime.Parse(ed); if (expiredDate < DateTime.Today) { throw new LicenseException("无效License, errorCode=5,1", 51); } return(new LicenseData { SerialNumber = sn, HardwareId = hwId, ExpiredDate = expiredDate }); }
public string Decrypt(string cipherText, string privateKey, bool padding) { var cipherBytes = Convert.FromBase64String(cipherText); using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(4096)) { rsa.FromXmlString(privateKey); var plainBytes = rsa.Decrypt(cipherBytes, padding); var plainText = System.Text.Encoding.ASCII.GetString(plainBytes); return(plainText); } }
private string GetFileHash() { if (SelectPackageFile.ShowDialog(this) == DialogResult.OK) { System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.FromXmlString(m_privateKey); System.Security.Cryptography.SHA1 sha = System.Security.Cryptography.SHA1.Create(); using (System.IO.FileStream fs = new System.IO.FileStream(SelectPackageFile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) return(Convert.ToBase64String(rsa.SignHash(sha.ComputeHash(fs), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA1")))); } return(null); }
/// <summary> /// Prepares data by encrypting it into smaller chucks. /// </summary> /// <param name="data">The data to prepare.</param> /// <param name="xmlPublicKey">An XML string representation of a Public Key.</param> /// <returns>A list of byte arrays encrypted and split into smaller chucks.</returns> public static List <byte[]> PrepareForTransport(byte[] data, string xmlPublicKey) { var list = new List <byte[]>(); // create encryptor from public key System.Security.Cryptography.RSACryptoServiceProvider transportEncryptor = new System.Security.Cryptography.RSACryptoServiceProvider(DefaultRSAKeyLengthInBits); transportEncryptor.FromXmlString(xmlPublicKey); // foreach (var item in Common.ByteArrayHelper.SplitByteArray(data, DefaultTransportChuckSize)) { list.Add(transportEncryptor.Encrypt(item, true)); } return(list); }
/// <summary> /// Restores data by decrypting and joining all of the parts together. /// </summary> /// <param name="parts">A list of byte arrays encrypted and split into smaller chucks.</param> /// <param name="xmlPrivateKey">An XML string representation of a Private Key.</param> /// <returns>A byte array decrypted and reassembled from the <paramref name="parts"/>.</returns> public static byte[] RestoreFromTransport(List <byte[]> parts, string xmlPrivateKey) { var list = new List <byte[]>(); // create encryptor from private key System.Security.Cryptography.RSACryptoServiceProvider transportEncryptor = new System.Security.Cryptography.RSACryptoServiceProvider(DefaultRSAKeyLengthInBits); transportEncryptor.FromXmlString(xmlPrivateKey); // foreach (var item in parts) { list.Add(transportEncryptor.Decrypt(item, true)); } return(Common.ByteArrayHelper.RestoreByteArray(list)); }
//------------------------------------------------- public static string RsaDecrypt(string s, string key) { var encryptedBytes = System.Convert.FromBase64String(s); var doOaepPadding = false; var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(1024); // Import the RSA Key information. rsa.FromXmlString(key); // Export RSA key to RSAParameters and include: // false - Only public key required for encryption. // true - Private key required for decryption. // Encrypt the passed byte array and specify OAEP padding. var decryptedBytes = rsa.Decrypt(encryptedBytes, doOaepPadding); var decryptedString = System.Text.Encoding.UTF8.GetString(decryptedBytes); return decryptedString; }
public static byte[] Hash(this string conteudo, string chave = null) { byte[] res; System.Security.Cryptography.MD5 hash = System.Security.Cryptography.MD5.Create(); byte[] md5 = hash.ComputeHash(Encoding.Default.GetBytes(conteudo)); // Depois disso executo o algortimo de RSA com minha chave pública e expoente 3, com um bloco de 128 bytes de acordo com o PAF-ECF. using (System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider()) { RSA.FromXmlString(chave ?? _chave); res = RSA.Encrypt(md5, false); } return(res); }
/// <summary> /// 秘密鍵を使って文字列を復号化する /// </summary> /// <param name="str">Encryptメソッドにより暗号化された文字列</param> /// <param name="privateKey">復号化に必要な秘密鍵(XML形式)</param> /// <returns>復号化された文字列</returns> public static string Decrypt(string str, string privateKey) { //RSACryptoServiceProviderオブジェクトの作成 System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); //秘密鍵を指定 rsa.FromXmlString(privateKey); //復号化する文字列をバイト配列に byte[] data = System.Convert.FromBase64String(str); //復号化する byte[] decryptedData = rsa.Decrypt(data, false); //結果を文字列に変換 return System.Text.Encoding.UTF8.GetString(decryptedData); }
public static string DecryptString(string inputString, int dwKeySize, string xmlString) { var rsaCryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider(dwKeySize); rsaCryptoServiceProvider.FromXmlString(xmlString); int base64BlockSize = ((dwKeySize / 8) % 3 != 0) ? (((dwKeySize / 8) / 3) * 4) + 4 : ((dwKeySize / 8) / 3) * 4; int iterations = inputString.Length / base64BlockSize; var arrayList = new System.Collections.ArrayList(); for (int i = 0; i < iterations; i++) { byte[] encryptedBytes = Convert.FromBase64String(inputString.Substring(base64BlockSize * i, base64BlockSize)); Array.Reverse(encryptedBytes); arrayList.AddRange(rsaCryptoServiceProvider.Decrypt(encryptedBytes, true)); } return(Encoding.UTF32.GetString(arrayList.ToArray(Type.GetType("System.Byte")) as byte[])); }
public static bool VerifyDigitalSignature(byte[] bytes, byte[] signature, string publicKey) { using (var sha = new System.Security.Cryptography.SHA256Managed()) { var hashData = sha.ComputeHash(bytes); using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider()) { rsa.FromXmlString(publicKey); var rsaDeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(rsa); rsaDeformatter.SetHashAlgorithm("SHA256"); return(rsaDeformatter.VerifySignature(hashData, signature)); } } }
/// <summary> /// RSA加密 /// </summary> /// <param name="byteArr_UTF8Content">加密内容</param> /// <param name="publickey">公钥(可空)</param> /// <returns>加密内容</returns> public static byte[] Encrypt(byte[] byteArr_UTF8Content, string publickey = "") { if (publickey.IsNullOrEmpty()) { publickey = sPublicKey; } System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.FromXmlString(publickey); int keySize = rsa.KeySize / 8; int bufferSize = keySize - 11; byte[] buffer = new byte[bufferSize]; byte[] r = null; using (System.IO.MemoryStream msInput = new System.IO.MemoryStream(byteArr_UTF8Content)) { using (System.IO.MemoryStream msOutput = new System.IO.MemoryStream()) { int readLen = msInput.Read(buffer, 0, bufferSize); while (readLen > 0) { byte[] dataToEncrypt = new byte[readLen]; Array.Copy ( sourceArray: buffer, sourceIndex: 0, destinationArray: dataToEncrypt, destinationIndex: 0, length: readLen ); byte[] encrypted = rsa.Encrypt(rgb: dataToEncrypt, fOAEP: false); msOutput.Write(encrypted, 0, encrypted.Length); readLen = msInput.Read(buffer, 0, bufferSize); } r = msOutput.ToArray(); // 获得全部加密结果 rsa.Clear(); } } return(r); }
//公钥加密函数 public string RSAEncryptPub(string orgstr) { try { System.Security.Cryptography.RSACryptoServiceProvider myrsa = new System.Security.Cryptography.RSACryptoServiceProvider(); myrsa.FromXmlString(publicKey); //把你要加密的内容转换成byte[] byte[] PlainTextBArray = (new UnicodeEncoding()).GetBytes(orgstr); //使用.NET中的Encrypt方法加密 byte[] CypherTextBArray = myrsa.Encrypt(PlainTextBArray, false); //最后吧加密后的byte[]转换成Base64String,加密后的内容 return(Convert.ToBase64String(CypherTextBArray)); } catch (Exception ex) { throw ex; } }
public static byte[] CreateDigitalSignature(byte[] bytes, string privateKey) { using (var sha = new System.Security.Cryptography.SHA256Managed()) { var hashData = sha.ComputeHash(bytes); using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider()) { rsa.FromXmlString(privateKey); var rsaFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(rsa); rsaFormatter.SetHashAlgorithm("SHA256"); var signedValue = rsaFormatter.CreateSignature(hashData); return(signedValue); } } }
/// <summary> /// 公開鍵を使って文字列を暗号化する /// </summary> /// <param name="str">暗号化する文字列</param> /// <param name="publicKey">暗号化に使用する公開鍵(XML形式)</param> /// <returns>暗号化された文字列</returns> public static string Encrypt(string str, string publicKey) { //RSACryptoServiceProviderオブジェクトの作成 System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); //公開鍵を指定 rsa.FromXmlString(publicKey); //暗号化する文字列をバイト配列に byte[] data = System.Text.Encoding.UTF8.GetBytes(str); //暗号化する //(XP以降の場合のみ2項目にTrueを指定し、OAEPパディングを使用できる) byte[] encryptedData = rsa.Encrypt(data, false); //Base64で結果を文字列に変換 return System.Convert.ToBase64String(encryptedData); }
//私钥解密函数 public string RSADecryptPrv(string privKey, string encstr) { try { System.Security.Cryptography.RSACryptoServiceProvider myrsa = new System.Security.Cryptography.RSACryptoServiceProvider(); //得到私钥 myrsa.FromXmlString(privKey); //把原来加密后的String转换成byte[] byte[] PlainTextBArray = Convert.FromBase64String(encstr); //使用.NET中的Decrypt方法解密 byte[] DypherTextBArray = myrsa.Decrypt(PlainTextBArray, false); //转换解密后的byte[],得到加密前的内容 string outstr = (new UnicodeEncoding()).GetString(DypherTextBArray); return(outstr); } catch (Exception ex) { throw ex; } }
private static async System.Threading.Tasks.Task <ResultType> TaskMain(Fee.Crypt.OnCryptTask_CallBackInterface a_callback_interface, byte[] a_binary, string a_key, Fee.TaskW.CancelToken a_cancel) #endif { ResultType t_ret; { t_ret.binary = null; t_ret.errorstring = null; } try{ using (System.Security.Cryptography.RSACryptoServiceProvider t_rsa = new System.Security.Cryptography.RSACryptoServiceProvider()){ t_rsa.FromXmlString(a_key); t_ret.binary = t_rsa.Decrypt(a_binary, false); } }catch (System.Exception t_exception) { t_ret.binary = null; t_ret.errorstring = "Task_DecryptPrivateKey : " + t_exception.Message; } if (a_cancel.IsCancellationRequested() == true) { t_ret.binary = null; t_ret.errorstring = "Task_DecryptPrivateKey : Cancel"; a_cancel.ThrowIfCancellationRequested(); } if (t_ret.binary == null) { if (t_ret.errorstring == null) { t_ret.errorstring = "Task_DecryptPrivateKey : null"; } } return(t_ret); }
public static string EncryptString(string inputString, int dwKeySize, string xmlString) { var rsaCryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider(dwKeySize); rsaCryptoServiceProvider.FromXmlString(xmlString); int keySize = dwKeySize / 8; byte[] bytes = Encoding.UTF32.GetBytes(inputString); int maxLength = keySize - 42; int dataLength = bytes.Length; int iterations = dataLength / maxLength; StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i <= iterations; i++) { byte[] tempBytes = new byte[(dataLength - maxLength * i > maxLength) ? maxLength : dataLength - maxLength * i]; Buffer.BlockCopy(bytes, maxLength * i, tempBytes, 0, tempBytes.Length); byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt(tempBytes, true); Array.Reverse(encryptedBytes); stringBuilder.Append(Convert.ToBase64String(encryptedBytes)); } return(stringBuilder.ToString()); }
private string Encrypt(string text) { // Use OAEP padding (PKCS#1 v2). var doOaepPadding = true; // ------------------------------------------------ // RSA Keys // ------------------------------------------------ var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); //Get the xml params returned form getPublicKey which contains the public key information var xmlParams = publicKeyTextBox.Text; // Import parameters from XML string. rsa.FromXmlString(xmlParams); // Export RSA key to RSAParameters and include: // false - Only public key required for encryption. // Export parameters and include only Public Key (Modulus + Exponent) // required for encryption. var rsaParamsPublic = rsa.ExportParameters(false); // ------------------------------------------------ // Encrypt // ------------------------------------------------ var decryptedBytes = System.Text.Encoding.UTF8.GetBytes(text); // Create a new instance of RSACryptoServiceProvider. rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); // Import the RSA Key information. rsa.ImportParameters(rsaParamsPublic); // Encrypt byte array. var encryptedBytes = rsa.Encrypt(decryptedBytes, doOaepPadding); // Convert bytes to base64 string. var encryptedString = System.Convert.ToBase64String(encryptedBytes); return(encryptedString); }
/// <summary> /// Imports key information via xml. /// </summary> /// <param name="inKeyXML">new key information as xml string</param> public void setNewKeyInformationXML(string inKeyXML) { csp.FromXmlString(inKeyXML); }
/// <summary> /// RSA解密算法 /// </summary> /// <param name="Source">要解密的字符串</param> /// <returns>解密后的结果字符串</returns> public static string RSA_Decode(byte[] Source) { string str; System.Security.Cryptography.RSACryptoServiceProvider provider = new System.Security.Cryptography.RSACryptoServiceProvider(); provider.FromXmlString("<RSAKeyValue><Modulus>pZGIiC3CxVYpTJ4dLylSy2TLXW+R9EyRZ39ekSosvRKf7iPuz4oPlHqjssh4Glbj/vTUIMFzHFC/9zC56GggNLfZBjh6fc3adq5cXGKlU74kAyM2z7gdYlUHtLT/GwDp4YcQKeSb9GjcvsXbUp0mrzI/axzueLIqK+R07rnv3yc=</Modulus><Exponent>AQAB</Exponent><P>0wCnxVUMgu+Uqp3UJ18bp9Ahdad36wDMwa0tmHxZJUvBZEfcYpsxmSHLpTUBCcAIg2eJL5g/iK9LrIwDBvUZ+w==</P><Q>yOB6ZwG9TuXMRPCA9cFTKCoHEsreDZluptHEfG3HvnS1lp5xwRCHXVuh7VWOM0G2gnZ/JWwWIfcqf30UTWvTxQ==</Q><DP>BTc67nHPwVzSu/TyzZZYRKmsahAdsr1uUktJmT9ZpMZenW/5Tqavby2arxbEU81faIAir/5/c42BvV4opP9iCQ==</DP><DQ>QETR5LMBxoRvXn80Q2yfFnKb4L9XXDKC3IywuL7G8YCVuKLo8kQ/ivcOT8jXvj6ADi2rcGWsjyFtT2zNWhftoQ==</DQ><InverseQ>jwpY6fpkzwtLOABZQncXMC4h7VbYrx+sZeSrBFXAgw1WMSs9YsT6EQcDRjpGt7JAkP14nSTSIVJNd23jZURCLw==</InverseQ><D>cw6SqcfbLVV198d9EnQOFEgkRvcsn2/CMAFET27WjkHuIAiagWE4+H7NWYWUaQFvCZNMAsNMYiX/cSFMYCRUFBBgkPqaqQ3+3qCs/kKiWpDjRwX8eXrMAnWniFDEoxc229Mxl4QZrcYKVRxrCIq8wKamuoWgwN0M+3CAiLwLvNk=</D></RSAKeyValue>"); try { str = System.Text.Encoding.UTF8.GetString(provider.Decrypt(Source, true)); } catch (System.Exception) { return ""; } return str; }
public string encrypt(string publicKey, string plainText) { System.Security.Cryptography.CspParameters cspParams = null; System.Security.Cryptography.RSACryptoServiceProvider rsaProvider = null; byte[] plainBytes = null; byte[] encryptedBytes = null; string result = ""; try { cspParams = new System.Security.Cryptography.CspParameters(); cspParams.ProviderType = 1; rsaProvider = new System.Security.Cryptography.RSACryptoServiceProvider(cspParams); rsaProvider.FromXmlString(publicKey); plainBytes = System.Text.Encoding.UTF8.GetBytes(plainText); encryptedBytes = rsaProvider.Encrypt(plainBytes, false); result = Convert.ToBase64String(encryptedBytes); } catch (Exception ex) { } return result; }
/// <summary> /// RSA加密算法 /// </summary> /// <param name="Source">要加密的字符串</param> /// <returns>加密后的结果字符串</returns> public static byte[] RSA_Encode(string Source) { System.Security.Cryptography.RSACryptoServiceProvider provider = new System.Security.Cryptography.RSACryptoServiceProvider(); provider.FromXmlString("<RSAKeyValue><Modulus>pZGIiC3CxVYpTJ4dLylSy2TLXW+R9EyRZ39ekSosvRKf7iPuz4oPlHqjssh4Glbj/vTUIMFzHFC/9zC56GggNLfZBjh6fc3adq5cXGKlU74kAyM2z7gdYlUHtLT/GwDp4YcQKeSb9GjcvsXbUp0mrzI/axzueLIqK+R07rnv3yc=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"); return provider.Encrypt(System.Text.Encoding.UTF8.GetBytes(Source), true); }
private string GetFileHash() { if (SelectPackageFile.ShowDialog(this) == DialogResult.OK) { System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.FromXmlString(m_privateKey); System.Security.Cryptography.SHA1 sha = System.Security.Cryptography.SHA1.Create(); using (System.IO.FileStream fs = new System.IO.FileStream(SelectPackageFile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) return Convert.ToBase64String(rsa.SignHash(sha.ComputeHash(fs), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA1"))); } return null; }
public static void FloatingResult(LAResult result, ActivationData activation, string machineCode, HttpListenerContext context, int signmetod = 1, List <ActivationData> activations = null) { if (signmetod == 1) { var licenseKeyToReturn = new LicenseKeyPI { }; if (activations != null) { licenseKeyToReturn.ActivatedMachines = activations.Select(x => new ActivationDataPIV3 { FriendlyName = x.FriendlyName, IP = x.IP, Time = ToUnixTimestamp(x.Time.Value), Mid = $"floating:{x.Mid}", FloatingExpires = ToUnixTimestamp(x.FloatingExpires.Value) }).ToList(); } else { licenseKeyToReturn.ActivatedMachines = new List <ActivationDataPIV3>() { new ActivationDataPIV3 { Mid = $"floating:{machineCode}", Time = ToUnixTimestamp(activation.Time.Value), FriendlyName = activation.FriendlyName, IP = activation.IP, FloatingExpires = ToUnixTimestamp(activation.FloatingExpires.Value) } }; } licenseKeyToReturn.Block = result.LicenseKey.Block; licenseKeyToReturn.Created = ToUnixTimestamp(result.LicenseKey.Created); licenseKeyToReturn.Expires = ToUnixTimestamp(result.LicenseKey.Expires); if (licenseKeyToReturn != null) { licenseKeyToReturn.Customer = new CustomerPI { CompanyName = result.LicenseKey.Customer.CompanyName, Created = ToUnixTimestamp(result.LicenseKey.Customer.Created), Email = result.LicenseKey.Customer.Email, Id = result.LicenseKey.Customer.Id, Name = result.LicenseKey.Customer.Name }; } licenseKeyToReturn.DataObjects = result.LicenseKey.DataObjects; licenseKeyToReturn.F1 = result.LicenseKey.F1; licenseKeyToReturn.F2 = result.LicenseKey.F2; licenseKeyToReturn.F3 = result.LicenseKey.F3; licenseKeyToReturn.F4 = result.LicenseKey.F4; licenseKeyToReturn.F5 = result.LicenseKey.F5; licenseKeyToReturn.F6 = result.LicenseKey.F6; licenseKeyToReturn.F7 = result.LicenseKey.F7; licenseKeyToReturn.F8 = result.LicenseKey.F8; licenseKeyToReturn.GlobalId = result.LicenseKey.GlobalId; licenseKeyToReturn.MaxNoOfMachines = result.LicenseKey.MaxNoOfMachines; licenseKeyToReturn.ID = result.LicenseKey.ID; licenseKeyToReturn.Key = result.LicenseKey.Key; licenseKeyToReturn.Notes = result.LicenseKey.Notes; licenseKeyToReturn.Period = result.LicenseKey.Period; licenseKeyToReturn.TrialActivation = result.LicenseKey.TrialActivation; licenseKeyToReturn.ProductId = result.LicenseKey.ProductId; licenseKeyToReturn.SignDate = ToUnixTimestamp(DateTime.UtcNow); var data = Newtonsoft.Json.JsonConvert.SerializeObject(licenseKeyToReturn); var signature = ""; byte[] dataSign = System.Text.UTF8Encoding.UTF8.GetBytes(data); System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(2048); rsa.FromXmlString(Program.RSAServerKey); byte[] signedData = rsa.SignData(dataSign, "SHA256"); signature = Convert.ToBase64String(signedData); var result2 = Newtonsoft.Json.JsonConvert.SerializeObject(new RawResponse { LicenseKey = Convert.ToBase64String(dataSign), Signature = signature, Message = "", Result = ResultType.Success }); ReturnResponse(result2, context); } else { } }
/// <summary> /// Initiates an syncronous check for updates /// </summary> /// <param name="force">A value indicating if the duration and user-enabled check should be bypassed</param> public void CheckForUpdates(bool force) { try { if (m_config == null) { System.Xml.Serialization.XmlSerializer src = new System.Xml.Serialization.XmlSerializer(typeof(Config)); using (System.IO.FileStream fs = new System.IO.FileStream(m_configFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) m_config = (Config)src.Deserialize(fs); } //This throws an exception if somethings broken m_config.CheckValid(); if (!m_config.Enabled && !force) return; if (m_lastCheck == null) { string file = m_config.ApplicationName + ".xml"; foreach (char c in System.IO.Path.GetInvalidFileNameChars()) file = file.Replace(c, '-'); file = System.IO.Path.Combine(System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "FreshKeeper"), file); if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(file))) System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(file)); if (System.IO.File.Exists(file)) { System.Xml.Serialization.XmlSerializer srl = new System.Xml.Serialization.XmlSerializer(typeof(LastCheck)); using (System.IO.FileStream fs = new System.IO.FileStream(m_configFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) m_lastCheck = (LastCheck)srl.Deserialize(fs); } else m_lastCheck = new LastCheck(); } if (Duplicati.Library.Core.Timeparser.ParseTimeInterval(m_config.CheckInterval, m_lastCheck.Time) > DateTime.Now) return; Random r = new Random(); string url = m_config.Urls[r.Next(0, m_config.Urls.Length)]; System.Net.WebClient wc = new System.Net.WebClient(); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.PreserveWhitespace = true; //Make sure we don't alter the document using (System.IO.MemoryStream ms = new System.IO.MemoryStream(wc.DownloadData(url))) doc.Load(ms); string hash = doc["UpdateList"].Attributes["SignedHash"].Value; doc["UpdateList"].Attributes["SignedHash"].Value = ""; System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.FromXmlString(m_config.PublicKey); UpdateList lst = null; using(System.IO.MemoryStream ms = new System.IO.MemoryStream()) { doc.Save(ms); if (!rsa.VerifyData(ms.ToArray(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA1"), Convert.FromBase64String(hash))) throw new Exception("Failed to verify signature"); ms.Position = 0; System.Xml.Serialization.XmlSerializer sr = new System.Xml.Serialization.XmlSerializer(typeof(UpdateList)); lst = (UpdateList)sr.Deserialize(ms); lst.SignedHash = hash; } if (lst == null || lst.Updates == null || lst.Updates.Length == 0) return; Update newest = lst.Updates[0]; foreach(Update u in lst.Updates) if (u.Version > newest.Version && (!u.BugfixUpdate || (u.BugfixUpdate && m_config.NotifyOnRevisionChange))) newest = u; if (newest.Version > m_config.LocalVersion) if (Updateavailable != null) Updateavailable(this, newest); } catch (Exception ex) { RaiseErrorEvent(ex); return; } }
private void SaveButton_Click(object sender, EventArgs e) { UpdateList lst = new UpdateList(); List<Update> updates = new List<Update>(); foreach (Update u in listBox1.Items) updates.Add(u); lst.Updates = updates.ToArray(); lst.SignedHash = ""; System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.FromXmlString(m_privateKey); System.Xml.Serialization.XmlSerializer sr = new System.Xml.Serialization.XmlSerializer(typeof(UpdateList)); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { sr.Serialize(ms, lst); ms.Position = 0; lst.SignedHash = Convert.ToBase64String(rsa.SignData(ms, System.Security.Cryptography.SHA1.Create())); } using (System.IO.FileStream fs = new System.IO.FileStream(UpdateFile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) sr.Serialize(fs, lst); }
/// <summary> /// 请求服务器进行加密。如果加密失败,连接将被断开,且抛出异常。 /// </summary> public void RequestEncryption() { try { // 请求服务器 RSA 公钥 var ret = Send(new byte[] { (byte)InternalCalls.RequestRSAPublicKey }, 0, 1, block: true, extraFlags: MessageFlags.InternalCalls); var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.PersistKeyInCsp = false; var keyxml = Encoding.UTF8.GetString(ret.Value.Array, ret.Value.Offset, ret.Value.Count); rsa.FromXmlString(keyxml); // 随机产生一个 AES 密钥和 IV,并发送给服务器 var aesKeyAndIV = RandomHelper.NextStrongRandomByteArray(32, false); // 将 AES 密钥信息通过 RSA 加密 var keyEncrypted = new byte[] { (byte)InternalCalls.SendAESKeysViaRSA }.Concat(rsa.Encrypt(aesKeyAndIV, true)).ToArray(); ret = Send(keyEncrypted, 0, keyEncrypted.Length, block: true, extraFlags: MessageFlags.InternalCalls); // 判断返回值是否成功 if (ret.HasValue && ret.Value.Count == 1 && ret.Value.Array[ret.Value.Offset] == 0) { AesKey = aesKeyAndIV.Take(16).ToArray(); AesIV = aesKeyAndIV.Skip(16).ToArray(); IsEncrypted = true; return; } closeSocket(); throw new Exception("请求加密失败"); } catch (Exception ex) { throw new Exception("请求加密失败", ex); } }
/// <summary> /// Initiates an syncronous check for updates /// </summary> /// <param name="force">A value indicating if the duration and user-enabled check should be bypassed</param> public void CheckForUpdates(bool force) { try { if (m_config == null) { System.Xml.Serialization.XmlSerializer src = new System.Xml.Serialization.XmlSerializer(typeof(Config)); using (System.IO.FileStream fs = new System.IO.FileStream(m_configFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) m_config = (Config)src.Deserialize(fs); } //This throws an exception if somethings broken m_config.CheckValid(); if (!m_config.Enabled && !force) { return; } if (m_lastCheck == null) { string file = m_config.ApplicationName + ".xml"; foreach (char c in System.IO.Path.GetInvalidFileNameChars()) { file = file.Replace(c, '-'); } file = System.IO.Path.Combine(System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "FreshKeeper"), file); if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(file))) { System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(file)); } if (System.IO.File.Exists(file)) { System.Xml.Serialization.XmlSerializer srl = new System.Xml.Serialization.XmlSerializer(typeof(LastCheck)); using (System.IO.FileStream fs = new System.IO.FileStream(m_configFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) m_lastCheck = (LastCheck)srl.Deserialize(fs); } else { m_lastCheck = new LastCheck(); } } if (Duplicati.Library.Core.Timeparser.ParseTimeInterval(m_config.CheckInterval, m_lastCheck.Time) > DateTime.Now) { return; } Random r = new Random(); string url = m_config.Urls[r.Next(0, m_config.Urls.Length)]; System.Net.WebClient wc = new System.Net.WebClient(); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.PreserveWhitespace = true; //Make sure we don't alter the document using (System.IO.MemoryStream ms = new System.IO.MemoryStream(wc.DownloadData(url))) doc.Load(ms); string hash = doc["UpdateList"].Attributes["SignedHash"].Value; doc["UpdateList"].Attributes["SignedHash"].Value = ""; System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.FromXmlString(m_config.PublicKey); UpdateList lst = null; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { doc.Save(ms); if (!rsa.VerifyData(ms.ToArray(), System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA1"), Convert.FromBase64String(hash))) { throw new Exception("Failed to verify signature"); } ms.Position = 0; System.Xml.Serialization.XmlSerializer sr = new System.Xml.Serialization.XmlSerializer(typeof(UpdateList)); lst = (UpdateList)sr.Deserialize(ms); lst.SignedHash = hash; } if (lst == null || lst.Updates == null || lst.Updates.Length == 0) { return; } Update newest = lst.Updates[0]; foreach (Update u in lst.Updates) { if (u.Version > newest.Version && (!u.BugfixUpdate || (u.BugfixUpdate && m_config.NotifyOnRevisionChange))) { newest = u; } } if (newest.Version > m_config.LocalVersion) { if (Updateavailable != null) { Updateavailable(this, newest); } } } catch (Exception ex) { RaiseErrorEvent(ex); return; } }