public RecordType AddRecord(string OName, string OPoint) { byte[] Name = Convert.FromBase64String(OName); byte[] Point = Convert.FromBase64String(OPoint); StreamReader sr = new StreamReader(Server.MapPath("App_Data\rightcolor_private.xml")); string ALL = sr.ReadToEnd(); sr.Close(); RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048); RSA.FromXmlString(ALL); string RealName = System.Text.Encoding.UTF8.GetString(RSA.Decrypt(Name, false)); long RealPoint = long.Parse(System.Text.Encoding.UTF8.GetString(RSA.Decrypt(Point, false))); RecordType AllowInsert = RecordType.None; long ForeverMax = (from inc in Data.Records orderby inc.Point descending select inc.Point).Skip(9).Take(1).SingleOrDefault(); if (RealPoint > ForeverMax) { AllowInsert = RecordType.Forever; goto Insert; } long MonthMax = (from inc in Data.Records where inc.AddDate > DateTime.Now.AddMonths(-1) orderby inc.Point descending select inc.Point).Skip(9).Take(1).SingleOrDefault(); if (RealPoint > MonthMax) { AllowInsert = RecordType.Month; goto Insert; } long WeekMax = (from inc in Data.Records where inc.AddDate > DateTime.Now.AddDays(-7) orderby inc.Point descending select inc.Point).Skip(9).Take(1).SingleOrDefault(); if (RealPoint > WeekMax) { AllowInsert = RecordType.Week; goto Insert; } long DayMax = (from inc in Data.Records where inc.AddDate > DateTime.Now.AddDays(-1) orderby inc.Point descending select inc.Point).Skip(9).Take(1).SingleOrDefault(); if (RealPoint > DayMax) { AllowInsert = RecordType.Day; } Insert: if (AllowInsert != RecordType.None) { Record NewRecord = new Record(); NewRecord.Person = RealName; NewRecord.Point = RealPoint; NewRecord.AddDate = DateTime.Now; Data.Records.InsertOnSubmit(NewRecord); Data.SubmitChanges(); } return AllowInsert; }
public UsrNamePassword(string encUsername, string encPassword) { CspParameters cspParams = new CspParameters(); cspParams.Flags = CspProviderFlags.UseMachineKeyStore; var myRSA = new RSACryptoServiceProvider(cspParams); if (HttpContext.Current.Session == null || HttpContext.Current.Session[CfcWebService.CertificateKey] == null) this.UserName = this.Password = null; else { myRSA.FromXmlString((string)HttpContext.Current.Session[CfcWebService.CertificateKey]); this.UserName = Encoding.UTF8.GetString(myRSA.Decrypt(CfcWebService.ToHexByte(encUsername), false)); this.Password = Encoding.UTF8.GetString(myRSA.Decrypt(CfcWebService.ToHexByte(encPassword), false)); } }
public byte[] Decrypt(byte[] key, byte[] cypher) { if (key == null || key.Length == 0) return new byte[0]; if (cypher == null || cypher.Length == 0) return new byte[0]; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(RSA_KEY_SIZE)) { rsa.ImportCspBlob(key); using (MemoryStream ms = new MemoryStream(cypher.Length)) { int pos = 0; byte[] buffer = new byte[DECRYPT_BUFFER_SIZE]; int copyLength = buffer.Length; while (true) { Array.Copy(cypher, pos, buffer, 0, copyLength); pos += copyLength; var plaintText = rsa.Decrypt(buffer, false); ms.Write(plaintText, 0, plaintText.Length); Array.Clear(plaintText, 0, plaintText.Length); Array.Clear(buffer, 0, copyLength); if (pos >= cypher.Length) break; } return ms.ToArray(); } } }
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)); }
public static string Decrypt(byte [] data) { if (data == null) return null; using (RSACryptoServiceProvider provider = new RSACryptoServiceProvider(Container)) { byte[] buf = null; try { buf = provider.Decrypt( data, false ); } catch { } if (buf == null) return null; else return Encoding.UTF8.GetString(buf); } }
public byte[] Decrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding) { RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSA.ImportParameters(RSAKeyInfo); return RSA.Decrypt(DataToDecrypt, DoOAEPPadding); }
static void Main() { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(File.ReadAllText("public.key")); if (!rsa.PublicOnly) Console.WriteLine("Otworzyłeś klucz prywatny!"); //szyfracja kluczem prywatnym lub publicznym byte[] encrypt = rsa.Encrypt(Encoding.UTF8.GetBytes("Test"), false); if (!rsa.PublicOnly) { byte[] decrypt = rsa.Decrypt(encrypt, false); string result = Encoding.UTF8.GetString(decrypt); Console.WriteLine(result); } else{ File.WriteAllBytes("out.f", encrypt); Console.WriteLine("Deszyfracja jest niemożliwa gdyź posiadasz tylko klucz publiczny"); Console.WriteLine("Wynik końcowy został zapisany do pliku \"out.f\""); } Console.ReadKey(); }
public DigitalSignatureVerificationResult VerifySignature(DigitalSignatureVerificationArguments arguments) { var res = new DigitalSignatureVerificationResult(); try { var rsaProviderSender = new RSACryptoServiceProvider(); rsaProviderSender.FromXmlString(arguments.PublicKeyForSignatureVerification.ToString()); var deformatter = new RSAPKCS1SignatureDeformatter(rsaProviderSender); deformatter.SetHashAlgorithm(_hashingService.HashAlgorithmCode()); var hashResult = _hashingService.Hash(arguments.CipherText); res.SignaturesMatch = deformatter.VerifySignature(hashResult.HashedBytes, arguments.Signature); if (res.SignaturesMatch) { var rsaProviderReceiver = new RSACryptoServiceProvider(); rsaProviderReceiver.FromXmlString(arguments.FullKeyForDecryption.ToString()); var decryptedBytes = rsaProviderReceiver.Decrypt(Convert.FromBase64String(arguments.CipherText), false); res.DecodedText = Encoding.UTF8.GetString(decryptedBytes); } res.Success = true; } catch (Exception ex) { res.ExceptionMessage = ex.Message; } return res; }
/// <summary> /// 从base64字符串解密 /// </summary> /// <param name="privateKey"></param> /// <param name="content"></param> /// <param name="size"></param> /// <returns></returns> public static string DecryptFromBase64(RSAParameters privateKey, string content, int size = 1024) { var rsa = new RSACryptoServiceProvider(size); rsa.ImportParameters(privateKey); var cipherbytes = rsa.Decrypt(content.Base64ToBytes(), false); return cipherbytes.FromUtf8Bytes(); }
/// <summary> /// Metoda za asimetrično dekriptiranje /// </summary> /// <param name="file"></param> public void AsymetriycDecrypt(string file) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); RSACryptoServiceProvider.UseMachineKeyStore = false; StreamReader streamReader = new StreamReader("privatni_kljuc.txt"); string privateKey = streamReader.ReadToEnd(); rsa.FromXmlString(privateKey); streamReader.Close(); int indexEcb = file.LastIndexOf(".rsa"); string zapis = file.Substring(0, indexEcb); FileStream fstreamU = File.OpenRead(file), fstreamO = new FileStream(zapis, FileMode.Create, FileAccess.ReadWrite); BinaryWriter bw = new BinaryWriter(fstreamO); BinaryReader binReader = new BinaryReader(fstreamU); byte[] bytes = binReader.ReadBytes((int)fstreamU.Length); binReader.Close(); byte[] decrypt = rsa.Decrypt(bytes, false); bw.Write(decrypt); bw.Flush(); bw.Close(); bw.Dispose(); fstreamU.Close(); fstreamU.Dispose(); }
public static string Decrypt(this string stringToDecrypt, string key) { if (string.IsNullOrEmpty(stringToDecrypt)) { throw new ArgumentException("An empty string value cannot be encrypted."); } if (string.IsNullOrEmpty(key)) { throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key."); } //var cspp = new CspParameters { KeyContainerName = key }; var cspp = new CspParameters { KeyContainerName = key, Flags = CspProviderFlags.UseMachineKeyStore }; var rsa = new RSACryptoServiceProvider(cspp) { PersistKeyInCsp = true }; var decryptArray = stringToDecrypt.Split(new[] { "-" }, StringSplitOptions.None); var decryptByteArray = Array.ConvertAll(decryptArray, (s => Convert.ToByte(byte.Parse(s, System.Globalization.NumberStyles.HexNumber)))); byte[] bytes = rsa.Decrypt(decryptByteArray, true); string result = System.Text.Encoding.UTF8.GetString(bytes); return result; }
public void Run() { var _exportKey = new RSACryptoServiceProvider(); string publicKeyXML = _exportKey.ToXmlString(false); string privateKeyXML = _exportKey.ToXmlString(true); var ByteConverter = new UnicodeEncoding(); byte[] dataToEncrypt = ByteConverter.GetBytes("My Secret Data!"); byte[] encryptedData; using (var RSA = new RSACryptoServiceProvider()) { RSA.FromXmlString(publicKeyXML); encryptedData = RSA.Encrypt(dataToEncrypt, false); } byte[] decryptedData; using (var RSA = new RSACryptoServiceProvider()) { RSA.FromXmlString(privateKeyXML); decryptedData = RSA.Decrypt(encryptedData, false); } string decryptedString = ByteConverter.GetString(decryptedData); Console.WriteLine(decryptedString); // Displays: My Secret Data! } }
// 複合化 public static byte[] Decript(String privateKey, byte[] src) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(privateKey); return rsa.Decrypt(src, false); }
// Decrypt method public string Decrypt( string b64String ) { try { byte[] ciphertext = Convert.FromBase64String(b64String); CspParameters RSAParams = new CspParameters(); RSAParams.Flags = CspProviderFlags.UseMachineKeyStore; //create new instance of RSACryptoServiceProvider RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(RSAParams); //import public and private RSA parameters from Xml file //StreamReader reader = new StreamReader("PublicPrivateKey.xml"); //string publicPrivateKeyXml = reader.ReadToEnd(); //reader.Close(); rsa.FromXmlString(this.publicPrivateKeyXml); //read ciphertext, decrypt it to plaintext byte[] plainbytes = rsa.Decrypt( ciphertext, false); //fOAEP needs high encryption pack return Encoding.ASCII.GetString(plainbytes) ; } catch ( CryptographicException cx ) { throw new CryptographicException( cx.Message) ; } }
public static string Decrypt(string encryptedText) { StringBuilder stringBuilder = new StringBuilder(); RSACryptoServiceProvider.UseMachineKeyStore = true; using (RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider()) { mojoEncryptionConfiguration config = mojoEncryptionConfiguration.GetConfig(); if (config.RsaKey.Length == 0) { log.Error("CryptoHelper.LoadRsaKey failed to load key from config, key was an empty string."); throw new ArgumentException("CryptoHelper.LoadRsaKey failed to load key from config, key was an empty string."); } rsaProvider.FromXmlString(config.RsaKey); byte[] decryptedStr = rsaProvider.Decrypt(StringToByteArray(encryptedText.Trim()), false); for (int i = 0; i <= decryptedStr.Length - 1; i++) { stringBuilder.Append(Convert.ToChar(decryptedStr[i])); } } return stringBuilder.ToString(); }
public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString) { System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider(); rSACryptoServiceProvider.FromXmlString(xmlPrivateKey); byte[] bytes = rSACryptoServiceProvider.Decrypt(DecryptString, false); return(new System.Text.UnicodeEncoding().GetString(bytes)); }
/// <summary> /// decrypts a string with a key inside the xmlstring /// </summary> /// <param name="DataToDecrypt">data to decrypt</param> /// <param name="xml">xmlstring taken from an RSACryptoServiceProvider object</param> /// <returns>decrypted string</returns> public static string RSADecrypt(string DataToDecrypt, string xml) { try { byte[] decryptedData; //Create a new instance of RSACryptoServiceProvider. using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.FromXmlString(xml); //Decrypt the passed byte array and specify OAEP padding. //OAEP padding is only available on Microsoft Windows XP or //later. decryptedData = RSA.Decrypt(Convert.FromBase64String(DataToDecrypt), false); } return Encoding.UTF8.GetString(decryptedData); } //Catch and display a CryptographicException //to the console. catch (CryptographicException e) { Console.WriteLine(e.ToString()); return null; } }
public static Boolean Test(int keySize) { Boolean bRes = true; Byte[] abPlain = { 0, 1, 2, 3, 4, 5, 6, 7 }; Byte[] abCipher = null; int kl = keySize; try { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(kl)) { abCipher = rsa.Encrypt(abPlain); Log.Comment("Cipher is : "); PrintByteArray(abCipher); abCipher = rsa.Decrypt(abCipher); } Log.Comment("Decrypted plaintext is : "); PrintByteArray(abCipher); if (!Compare(abPlain, abCipher)) { bRes = false; Log.Comment("Failed to decrypt to the original plaintext"); } } catch (Exception e) { Log.Comment("Exception ocured :\n" + e.ToString()); bRes = false; } return bRes; }
public static byte[] DecryptRSA(byte[] data, byte[] key) { var csp = new CspParameters(); csp.Flags = CspProviderFlags.UseMachineKeyStore; using (var rsa = new RSACryptoServiceProvider(_dwSize, csp)) using (var ms = new MemoryStream()) { //Create seed, create RSA blob, replace logic rsa.ImportCspBlob(key); for (int i = 0; i < data.Length; i += _chunkSize) { int amount = Math.Min(_chunkSize, data.Length - i); byte[] buffer = new byte[amount]; Buffer.BlockCopy(data, i, buffer, 0, amount); byte[] decrypted = rsa.Decrypt(buffer, false); ms.Write(decrypted, 0, decrypted.Length); } return ms.ToArray(); } }
public static void EncryptSomeText() { //Init keys GeneratePublicAndPrivateKeys(); UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte[] dataToEncrypt = ByteConverter.GetBytes("My ultra secret message!"); byte[] encryptedData; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.FromXmlString(publicKeyXML); encryptedData = RSA.Encrypt(dataToEncrypt, false); } byte[] decryptedData; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.FromXmlString(privateKeyXML); decryptedData = RSA.Decrypt(encryptedData, false); } string decryptedString = ByteConverter.GetString(decryptedData); Console.WriteLine(decryptedString); }
/// <summary> /// Decrypt a base 64 string hash /// </summary> /// <param name="hash">The encrypted hash</param> /// <param name="signature">the private key signature</param> /// <returns>If is valid return decrypt hash, else return empty string</returns> public static string Decrypt(string hash, byte[] signature) { if (!VerifyHash(hash, signature)) return string.Empty; try { var provider = new RSACryptoServiceProvider(); provider.ImportParameters(PrivateParams); var encryptedbuffer = Convert.FromBase64String(hash); var decryptedbuffer = provider.Decrypt(encryptedbuffer, false); var arrayList = new ArrayList(); arrayList.AddRange(decryptedbuffer); var converted = arrayList.ToArray(typeof(byte)) as byte[]; if (converted != null) return Encoding.ASCII.GetString(converted); return string.Empty; } catch { return string.Empty; } }
/// <summary> /// 解密 /// </summary> /// <param name="privateKey">私钥</param> /// <param name="data">要解密的数据</param> /// <returns></returns> public virtual string Decode(string privateKey, string data) { var rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(privateKey); var cipherbytes = rsa.Decrypt(Convert.FromBase64String(data), false); return Encoding.UTF8.GetString(cipherbytes); }
public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString) { RSACryptoServiceProvider provider1 = new RSACryptoServiceProvider(); provider1.FromXmlString(xmlPrivateKey); byte[] buffer1 = provider1.Decrypt(DecryptString, false); return new UnicodeEncoding().GetString(buffer1); }
static void Main(string[] args) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); string publicKeyXML = rsa.ToXmlString(false); string privateKeyXML = rsa.ToXmlString(true); UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte[] dataToEncrypt = ByteConverter.GetBytes("My secret data!"); Console.WriteLine("Encrypting: {0}", ByteConverter.GetString(dataToEncrypt)); byte[] encryptedData; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.FromXmlString(publicKeyXML); encryptedData = RSA.Encrypt(dataToEncrypt, false); } Console.WriteLine("Encrypted data: {0}", ByteConverter.GetString(encryptedData)); byte[] decryptedData; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.FromXmlString(privateKeyXML); decryptedData = RSA.Decrypt(encryptedData, false); } string decryptedString = ByteConverter.GetString(decryptedData); Console.WriteLine("Decrypted data: {0}", decryptedString); Console.WriteLine("Press a key to exit"); Console.ReadKey(); }
private static byte[] ExchangeKeys(string sesskey, Socket sock) { try { using(RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(sesskey); var b = BitConverter.GetBytes(0); Utilities.Receive_Exact(sock, b, 0, b.Length); var len = BitConverter.ToInt32(b, 0); if(len > 4000) throw new ArgumentException("Buffer Overlflow in Encryption key exchange!"); byte[] sessionkey = new byte[len]; Utilities.Receive_Exact(sock, sessionkey, 0, len); sessionkey = rsa.Decrypt(sessionkey, true);//decrypt the session key //hash the key and send it back to prove that I received it correctly byte[] sessionkeyhash = SHA256.Create().ComputeHash(sessionkey); //send it back to the client byte[] intBytes = BitConverter.GetBytes(sessionkeyhash.Length); sock.Send(intBytes); sock.Send(sessionkeyhash); Debug.WriteLine("Key Exchange completed!"); return sessionkey; } } catch(Exception e) { Debug.WriteLine(e.Message); return null; } }
public static bool TryDecryptStream(Stream inputStream, Stream outputStream, Stream keyStream) { try { string keyXml; using (StreamReader keyStreamReader = new StreamReader(CloneStream(keyStream)))//Create new stream as to not dispose keyStream { keyXml = keyStreamReader.ReadToEnd(); } using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(keyXml); var bytes = rsa.Decrypt(StreamUtility.GetBytes(inputStream), false); outputStream.Write(bytes, 0, bytes.Length); outputStream.Position = 0; } return true; } catch (Exception) { return false; } }
static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding) { try { byte[] decryptedData; //Create a new instance of RSACryptoServiceProvider. using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { //Import the RSA Key information. This needs //to include the private key information. RSA.ImportParameters(RSAKeyInfo); //Decrypt the passed byte array and specify OAEP padding. //OAEP padding is only available on Microsoft Windows XP or //later. decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding); } return decryptedData; } //Catch and display a CryptographicException //to the console. catch (CryptographicException e) { Console.WriteLine(e.ToString()); return null; } }
public static string DecryptData(byte[] data, string keyFile) { RSACryptoServiceProvider Algorithm = new RSACryptoServiceProvider(); ReadKey(Algorithm, keyFile); byte[] ClearData = Algorithm.Decrypt(data, true); return Convert.ToString(Encoding.UTF8.GetString(ClearData)); }
public static string Text_Decryption(string text, int bits, string encryption_key) { string result = String.Empty; ArrayList list = new ArrayList(); try { RSACryptoServiceProvider rsacsp = new RSACryptoServiceProvider(bits); rsacsp.FromXmlString(encryption_key); int blockSizeBase64 = (bits / 8 % 3 != 0) ? (((bits / 8) / 3) * 4) + 4 : ((bits / 8) / 3) * 4; int iterations = text.Length / blockSizeBase64; for (int i = 0; i < iterations; i++) { Byte[] encrypted_bytes = Convert.FromBase64String(text.Substring(blockSizeBase64 * i, blockSizeBase64)); Array.Reverse(encrypted_bytes); list.AddRange(rsacsp.Decrypt(encrypted_bytes, true)); } } catch (Exception e) { result = "<Error>" + e.Message + "</Error>"; } result = Encoding.UTF32.GetString((Byte[])list.ToArray(typeof(Byte))); return result; }
public byte[] Decrypt(byte[] Data, int Offset, int Length) { if (Length % DecChunkSize != 0) { throw new Exception("Invalid length"); } using (MemoryStream stream = new MemoryStream(Data.Length)) { int LengthLeft = Length; if (PrivateKey != null && PrivateKey.Length > 0) { rsa.FromXmlString(PrivateKey); } for (int i = Offset; i < Length; i += DecChunkSize) { byte[] temp = new byte[DecChunkSize]; Array.Copy(Data, i, temp, 0, DecChunkSize); byte[] decrypted = rsa.Decrypt(temp, PkcsPadding); stream.Write(decrypted, 0, decrypted.Length); if (LengthLeft >= DecChunkSize) { LengthLeft -= DecChunkSize; } } return(stream.ToArray()); } }
public static string DecryptString(string inputString, int dwKeySize, string xmlString) { // TODO: Add Proper Exception Handlers RSACryptoServiceProvider rsaCryptoServiceProvider = new 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; ArrayList arrayList = new ArrayList(); for (int i = 0; i < iterations; i++) { byte[] encryptedBytes = Convert.FromBase64String( inputString.Substring(base64BlockSize * i, base64BlockSize)); // Be aware the RSACryptoServiceProvider reverses the order of // encrypted bytes after encryption and before decryption. // If you do not require compatibility with Microsoft Cryptographic // API (CAPI) and/or other vendors. // Comment out the next line and the corresponding one in the // EncryptString function. Array.Reverse(encryptedBytes); arrayList.AddRange(rsaCryptoServiceProvider.Decrypt( encryptedBytes, true)); } return Encoding.UTF32.GetString(arrayList.ToArray( Type.GetType("System.Byte")) as byte[]); }
/// <summary> /// Decrypts a string which was previously encrypted with the Encrypt method /// </summary> /// <param name="cipher">The encrypted byte array</param> /// <param name="privateKey">The private key used to decrypt the data</param> /// <returns>A byte array containing the decrypted value</returns> public static string Decrypt(string cipher, RSAParameters privateKey) { using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider()) { //ImportParameters sets the keySize according to the size used to create the privateKey rsa.ImportParameters(privateKey); int base64BlockSize = ((rsa.KeySize / 8) % 3 != 0) ? (((rsa.KeySize / 8) / 3) * 4) + 4 : ((rsa.KeySize / 8) / 3) * 4; int iterations = cipher.Length / base64BlockSize; //var arrayList = new ArrayList(); var fullBytes = new byte[0]; for (int i = 0; i < iterations; i++) { byte[] encryptedBytes = Convert.FromBase64String(cipher.Substring(base64BlockSize * i, base64BlockSize)); // Be aware the RSACryptoServiceProvider reverses the order of // encrypted bytes after encryption and before decryption. // If you do not require compatibility with Microsoft Cryptographic // API (CAPI) and/or other vendors. // Comment out the next line and the corresponding one in the // EncryptString function. Array.Reverse(encryptedBytes); var bytes = rsa.Decrypt(encryptedBytes, true); var len = fullBytes.Length; Array.Resize(ref fullBytes, len + bytes.Length); Array.Copy(bytes, 0, fullBytes, len, bytes.Length); //arrayList.AddRange(bytes); } return(Encoding.UTF32.GetString(fullBytes)); //return Encoding.UTF32.GetString(arrayList.ToArray(Type.GetType("System.Byte")) as byte[]); } }
/// <summary> /// Decrypt cipher by private key. /// </summary> /// <param name="dataBytes">Need to decrypt the data</param> /// <param name="fOEAP"></param> /// <returns></returns> public byte[] DecryptByPrivateKey(byte[] dataBytes, bool fOEAP) { if (PrivateRsa is null) { throw new ArgumentException("private key can not null"); } return(PrivateRsa.Decrypt(dataBytes, fOEAP)); }
public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString) { System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider(); rSACryptoServiceProvider.FromXmlString(xmlPrivateKey); byte[] rgb = System.Convert.FromBase64String(m_strDecryptString); byte[] bytes = rSACryptoServiceProvider.Decrypt(rgb, false); return(new System.Text.UnicodeEncoding().GetString(bytes)); }
/// <summary> /// RSA解密数据 /// </summary> /// <param name="ciphertext">要解密数据</param> /// <param name="KeyContainerName">密匙容器的名称</param> /// <returns></returns> public static string RSADecrypt(string ciphertext, string KeyContainerName = null) { System.Security.Cryptography.CspParameters param = new System.Security.Cryptography.CspParameters(); param.KeyContainerName = KeyContainerName ?? "default"; //密匙容器的名称,保持加密解密一致才能解密成功 using (System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(param)) { byte[] encryptdata = Convert.FromBase64String(ciphertext); byte[] decryptdata = rsa.Decrypt(encryptdata, false); return(System.Text.Encoding.ASCII.GetString(decryptdata)); } }
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)); }
/// <summary> /// キーコンテナに格納された秘密鍵を使って、文字列を復号化する /// </summary> /// <param name="str">Encryptメソッドにより暗号化された文字列</param> /// <param name="containerName">キーコンテナ名</param> /// <returns>復号化された文字列</returns> public static string DecryptByContainer(string str, string containerName) { //CspParametersオブジェクトの作成 System.Security.Cryptography.CspParameters cp = new System.Security.Cryptography.CspParameters(); //キーコンテナ名を指定する cp.KeyContainerName = containerName; //CspParametersを指定してRSACryptoServiceProviderオブジェクトを作成 System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cp); //復号化する byte[] data = System.Convert.FromBase64String(str); byte[] decryptedData = rsa.Decrypt(data, false); return(System.Text.Encoding.UTF8.GetString(decryptedData)); }
static public string RSADecrypt(string sValue, string sPrvKey) { // RSA 복호화. byte [] inbuf = Convert.FromBase64String(sPrvKey); sPrvKey = (new UTF8Encoding()).GetString(inbuf); System.Security.Cryptography.RSACryptoServiceProvider oDec = new System.Security.Cryptography.RSACryptoServiceProvider(); //복호화 oDec.FromXmlString(sPrvKey); byte [] srcbuf = Convert.FromBase64String(sValue); byte [] decbuf = oDec.Decrypt(srcbuf, false); string sDec = (new UTF8Encoding()).GetString(decbuf, 0, decbuf.Length); return(sDec); }
/// <summary> /// 公開鍵を使って復号化する /// </summary> /// <param name="str">復号化するデータ</param> /// <returns>復号化されたデータ</returns> public static byte[] DecryptBigData(byte[] targetData) { try { //RSACryptoServiceProviderオブジェクトの作成 var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(KeySize); //秘密鍵を指定 rsa.FromXmlString(privateKey); int blockNumber = targetData.Length; blockNumber /= rsa.KeySize / 8; if (targetData.Length % (rsa.KeySize / 8) != 0) { blockNumber++; } byte[] resultData = new byte[targetData.Length]; int resultOffset = 0; for (int index = 0; index < blockNumber; index++) { //復号化する int tempSize = rsa.KeySize / 8; if (targetData.Length - index * tempSize < tempSize) { tempSize = targetData.Length - index * tempSize; } byte[] tempData = new byte[tempSize]; Buffer.BlockCopy(targetData, index * (rsa.KeySize / 8), tempData, 0, tempSize); byte[] decryptedData = rsa.Decrypt(tempData, false); Buffer.BlockCopy(decryptedData, 0, resultData, resultOffset, decryptedData.Length); resultOffset += decryptedData.Length; } Array.Resize(ref resultData, resultOffset); //結果を文字列に変換 return(resultData); } catch (Exception ex) { string exe = ex.Message; } return(null); }
/// <summary> /// 秘密鍵を使って文字列を復号化する /// </summary> /// <param name="str">Encryptメソッドにより暗号化された文字列</param> /// <returns>復号化された文字列</returns> public static string ClientDecrypt(string str) { try { //RSACryptoServiceProviderオブジェクトの作成 var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(KeySize); //秘密鍵を指定 rsa.FromXmlString(clientPrivateKey); //復号化する文字列をバイト配列に byte[] data = System.Convert.FromBase64String(str); //復号化する byte[] decryptedData = rsa.Decrypt(data, false); //結果を文字列に変換 return(System.Text.Encoding.UTF8.GetString(decryptedData)); } catch (Exception) { } return(null); }
public static byte[] RSADecrypt(byte[] privateKey, byte[] dataToDecrypt) { // helper to RSA decrypt a given blob // PROV_RSA_AES == 24 var cspParameters = new System.Security.Cryptography.CspParameters(24); using (var rsaProvider = new System.Security.Cryptography.RSACryptoServiceProvider(cspParameters)) { try { rsaProvider.PersistKeyInCsp = false; rsaProvider.ImportCspBlob(privateKey); byte[] dataToDecryptRev = new byte[256]; Buffer.BlockCopy(dataToDecrypt, 0, dataToDecryptRev, 0, dataToDecrypt.Length); // ... Array.Copy? naw... :( Array.Reverse(dataToDecryptRev); // ... don't ask me how long it took to realize this :( byte[] dec = rsaProvider.Decrypt(dataToDecryptRev, false); // no padding return(dec); } catch (Exception e) { Console.WriteLine("Error decryption domain key: {0}", e.Message); } finally { rsaProvider.PersistKeyInCsp = false; rsaProvider.Clear(); } } return(new byte[0]); }
private static byte[] decrypt(byte[] data, string privateKey, string input_charset) { System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = RSAFromPkcs8.DecodePemPrivateKey(privateKey); new System.Security.Cryptography.SHA1CryptoServiceProvider(); return(rSACryptoServiceProvider.Decrypt(data, false)); }
public static byte[] Decrypt(byte[] privKey, byte[] data) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportCspBlob(privKey); byte[] x = rsa.Decrypt(data, false); return x; }