public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters) { int algId = OidInfo.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, oid.Value, OidGroup.PublicKeyAlgorithm, fallBackToAllGroups: true).AlgId; switch (algId) { case AlgId.CALG_RSA_KEYX: case AlgId.CALG_RSA_SIGN: { byte[] keyBlob = DecodeKeyBlob(CryptDecodeObjectStructType.RSA_CSP_PUBLICKEYBLOB, encodedKeyValue); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportCspBlob(keyBlob); return rsa; } case AlgId.CALG_DSS_SIGN: { byte[] keyBlob = ConstructDSSPublicKeyCspBlob(encodedKeyValue, encodedParameters); DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(); dsa.ImportCspBlob(keyBlob); return dsa; } default: throw new NotSupportedException(SR.NotSupported_KeyAlgorithm); } }
public static bool ValidatePathWithEncodedRSAPKCS1SignatureAndPublicRSAKey(string path, string base64Signature, string publicKey) { try { byte[] signature = Convert.FromBase64String(base64Signature); byte[] data = File.ReadAllBytes(path); SHA256CryptoServiceProvider cryptoTransformSHA256 = new SHA256CryptoServiceProvider(); byte[] sha256Hash = cryptoTransformSHA256.ComputeHash(data); string cleanKey = ""; string[] lines = publicKey.Split(new char[] {'\n', '\r'}); foreach (string line in lines) { cleanKey += line.Trim(); } byte[] publicKeyData = Convert.FromBase64String(cleanKey); RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); provider.ImportCspBlob(publicKeyData); RSAPKCS1SignatureDeformatter formatter = new RSAPKCS1SignatureDeformatter(provider); formatter.SetHashAlgorithm("SHA256"); return formatter.VerifySignature(sha256Hash, signature); } catch (Exception ex) { Console.WriteLine(ex.Message); return false; } }
private void OpenSNKFileButtonClick(object sender, EventArgs e) { var openFileDialog = new OpenFileDialog { Title = "Open your SNK file", Filter = "Strong Name Key file (*.snk)|*.snk|All Files (*.*)|*.*" }; if (openFileDialog.ShowDialog() == DialogResult.OK) { publicKeyTextBox.Clear(); privateKeyTextBox.Clear(); try { var snkBytes = File.ReadAllBytes(openFileDialog.FileName); using (var provider = new RSACryptoServiceProvider()) { provider.ImportCspBlob(snkBytes); publicKeyTextBox.Text = Beautify(provider.ToXmlString(false)); privateKeyTextBox.Text = Beautify(provider.ToXmlString(true)); } } catch (Exception exception) { MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
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 byte[] Encrypt(byte[] key, byte[] plainText) { if (key == null || key.Length == 0) return new byte[0]; if (plainText == null || plainText.Length == 0) return new byte[0]; using (var rsa = new RSACryptoServiceProvider(RSA_KEY_SIZE)) { rsa.ImportCspBlob(key); using (MemoryStream ms = new MemoryStream()) { byte[] buffer = new byte[ENCRYPT_BUFFER_SIZE]; int pos = 0; int copyLength = buffer.Length; while (true) { if (pos + copyLength > plainText.Length) copyLength = plainText.Length - pos; buffer = new byte[copyLength]; Array.Copy(plainText, pos, buffer, 0, copyLength); pos += copyLength; ms.Write(rsa.Encrypt(buffer, false), 0, DECRYPT_BUFFER_SIZE); Array.Clear(buffer, 0, copyLength); if (pos >= plainText.Length) break; } return ms.ToArray(); } } }
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(); } } }
/// <summary> /// RSA签名验证 /// </summary> /// <param name="strKeyPublic">公钥</param> /// <param name="strHashbyteDeformatter">Hash描述</param> /// <param name="strDeformatterData">签名后的结果</param> /// <returns></returns> public bool SignatureDeformatter(string strKeyPublic, string strHashbyteDeformatter, string strDeformatterData) { try { byte[] DeformatterData; byte[] HashbyteDeformatter; HashbyteDeformatter = Convert.FromBase64String(strHashbyteDeformatter); System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); //RSA.FromXmlString(strKeyPublic); RSA.ImportCspBlob(Convert.FromBase64String(strKeyPublic));//载入钥 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); DeformatterData = Convert.FromBase64String(strDeformatterData); if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData)) { return(true); } else { return(false); } } catch (Exception ex) { throw ex; } }
/// <summary> /// Encrypts a packet targeted to a single person /// </summary> /// <param name="packet">The packet to encrypt</param> /// <param name="targetPublicKey">Target's identity public key</param> /// <returns>Encrypted packet</returns> public static DEncodeValue EncryptTargetedPacket(DEncodeValue packet, byte[] targetPublicKey) { var targetCryptCsp = new RSACryptoServiceProvider(); targetCryptCsp.ImportCspBlob(targetPublicKey); var packetStream = new MemoryStream(); var writer = new DEncodeWriter(packetStream); writer.Write(packet); var packetBytes = packetStream.ToArray(); // create a unique packet key var csp = CreatePacketCryptingAlgoInstance(); var key = new byte[32]; var iv = new byte[32]; RngCsp.GetBytes(key); RngCsp.GetBytes(iv); csp.Key = key; csp.IV = iv; // encrypt the packet var cryptedPacketBytes = csp.CreateEncryptor().TransformFinalBlock(packetBytes, 0, packetBytes.Length); // now encrypt the packet key with the target's public key var encryptedKey = targetCryptCsp.Encrypt(key, true); var packetDict = new Dictionary<string, DEncodeValue>(); packetDict.Add("ty", new DEncodeString("targeted")); // type (encrypted, targeted packet) packetDict.Add("ke", new DEncodeArray(encryptedKey)); // packet encryption key (encrypted with target's public key) packetDict.Add("iv", new DEncodeArray(iv)); // IV for the packet encryption packetDict.Add("pa", new DEncodeArray(cryptedPacketBytes)); // wrapped payload packet return new DEncodeDictionary(packetDict); }
//this actually decrypts public static string decrypt(string passed_data_store, int key_used, string passed_data) { string return_data = "error"; System.IO.DirectoryInfo Keys_Dir = new System.IO.DirectoryInfo(System.IO.Path.Combine(passed_data_store, "keys")); string blob = ""; System.Security.Cryptography.RSACryptoServiceProvider provider = new System.Security.Cryptography.RSACryptoServiceProvider(); foreach(System.IO.FileInfo File in Keys_Dir.GetFiles()) { if (File.Name.Split('.')[0] == key_used.ToString()) { using (System.IO.StreamReader reader = File.OpenText()) { blob = reader.ReadToEnd(); String[] str_arr = blob.Split('-'); byte[] encrypted_array = new byte[str_arr.Length]; for(int i = 0; i < str_arr.Length; i++) encrypted_array[i]=Convert.ToByte(str_arr[i], 16); provider.ImportCspBlob(encrypted_array); System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); byte[] science = StringToByteArray(passed_data); byte[] decrtpyerd_array = provider.Decrypt(science, false); return Encoding.UTF8.GetString(decrtpyerd_array); } } } Console.WriteLine("Can not find decryption key"); return return_data; }
public void KeyGenerationTest() { PrivateType pt = new PrivateType(typeof(AsymmetricBlobCryptoProvider)); byte[] key = (byte[])pt.InvokeStatic("GenerateRandomKey"); byte[] encryptedKey; byte[] decryptedKey; var rsa = new RSACryptoServiceProvider(); rsa.ImportCspBlob(testCspBlob); using (ICspProxy cspProxy = new DisposingCspProxy(rsa, rsa.KeySize)) { encryptedKey = cspProxy.Encrypt(key); decryptedKey = cspProxy.Decrypt(encryptedKey); } // The two keys shouldn't be the same... Assert.IsFalse(key.SequenceEqual(encryptedKey)); // And we expect it to grow to the same size as the RSA Key Assert.IsTrue(encryptedKey.Length == 4096 / 8); // Sanity check, it should be 256 bit / 32 bytes and not contain any zeros. Assert.IsTrue(decryptedKey.Length == 256/8, "Key length is incorrect"); Assert.IsTrue(decryptedKey[0] != 0, "Key starts with an empty byte"); // And of course, the round tripped key should match original Assert.IsTrue(key.SequenceEqual(decryptedKey)); }
public ICspProxy GetProvider() { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportCspBlob(CspBlob); return new DisposingCspProxy(rsa, KeySize); }
/// <summary> /// Decrypt this message using this private key /// </summary> /// <param name="dataToDecrypt"> /// The data To decrypt. /// </param> /// <param name="privateKeyInfo"> /// The private Key Info. /// </param> /// <returns> /// The decrypted data. Returns null if cryptographic exception is caught /// </returns> public static string Decrypt(string dataToDecrypt, byte[] privateKeyInfo) { Contract.Requires(dataToDecrypt != null); Contract.Requires(privateKeyInfo != null); Contract.Ensures(!Contract.Result<string>().Equals(dataToDecrypt)); //// The bytearray to hold all of our data after decryption byte[] decryptedBytes; using (var rsa = new RSACryptoServiceProvider()) { byte[] bytesToDecrypt = Convert.FromBase64String(dataToDecrypt); //// Import the private key info rsa.ImportCspBlob(privateKeyInfo); //// No need to subtract padding size when decrypting int blockSize = rsa.KeySize / 8; var buffer = new byte[blockSize]; //// Initializes our array to make sure it can hold at least the amount needed to decrypt. decryptedBytes = new byte[dataToDecrypt.Length]; try { for (int i = 0; i < bytesToDecrypt.Length; i += blockSize) { if (2 * i > bytesToDecrypt.Length && ((bytesToDecrypt.Length - i) % blockSize != 0)) { buffer = new byte[bytesToDecrypt.Length - i]; blockSize = bytesToDecrypt.Length - i; } //// If the amount of bytes we need to decrypt is not enough to fill out a block, only decrypt part of it if (bytesToDecrypt.Length < blockSize) { buffer = new byte[bytesToDecrypt.Length]; blockSize = bytesToDecrypt.Length; } Buffer.BlockCopy(bytesToDecrypt, i, buffer, 0, blockSize); byte[] decryptedBuffer = rsa.Decrypt(buffer, false); decryptedBuffer.CopyTo(decryptedBytes, i); } } catch (CryptographicException e) { Console.Write(e.Message); return null; } finally { //// Clear the RSA key container, deleting generated keys. rsa.PersistKeyInCsp = false; } } //// We encode each byte with UTF8 and then write to a string while trimming off the extra empty data created by the overhead. return Encoding.UTF8.GetString(decryptedBytes).TrimEnd(new[] { '\0' }); }
public static ICspProxyFactory Create(byte[] cspBlob) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.ImportCspBlob(cspBlob); return new DefaultFactory(cspBlob, rsa.KeySize); } }
/// <summary> Creates the key from the information provided </summary> public static RSAPublicKey FromBytes(byte[] bytes) { RSACryptoServiceProvider key = new RSACryptoServiceProvider(); key.ImportCspBlob(bytes); if (key.PublicOnly) return new RSAPublicKey(key); return new RSAPrivateKey(key); }
private static RSACryptoServiceProvider GetPrivateKey(byte[] p12) { var certificate = new X509Certificate2(p12, "notasecret", X509KeyStorageFlags.Exportable); var rsa = (RSACryptoServiceProvider)certificate.PrivateKey; byte[] privateKeyBlob = rsa.ExportCspBlob(true); var privateKey = new RSACryptoServiceProvider(); privateKey.ImportCspBlob(privateKeyBlob); return privateKey; }
public WobUtils(String iss, X509Certificate2 cert) { issuer = iss; RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey; byte[] privateKeyBlob = rsa.ExportCspBlob(true); key = new RSACryptoServiceProvider(); key.ImportCspBlob(privateKeyBlob); }
public override string ExportToXml(byte[] key, bool includePrivate = true, int keySize = 1024) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize)) { rsa.PersistKeyInCsp = false; rsa.ImportCspBlob(key); return rsa.ToXmlString(includePrivate); } }
public WobUtils(String iss, X509Certificate2 cert) { issuer = iss; origins = WebConfigurationManager.AppSettings["Origins"].Split(' '); RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey; byte[] privateKeyBlob = rsa.ExportCspBlob(true); key = new RSACryptoServiceProvider(); key.ImportCspBlob(privateKeyBlob); }
public RSAAsymmetricKey(byte[] cspBlob) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.ImportCspBlob (cspBlob); ImportRSAParameters (rsa.ExportParameters (true)); } }
/// <summary>Extracts a <see cref="Key"/> from the given certificate.</summary> public Initializer FromCertificate(X509Certificate2 certificate) { // Workaround to correctly cast the private key as a RSACryptoServiceProvider type 24. RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certificate.PrivateKey; byte[] privateKeyBlob = rsa.ExportCspBlob(true); Key = new RSACryptoServiceProvider(); Key.ImportCspBlob(privateKeyBlob); return this; }
protected void Page_Load(object sender, EventArgs e) { Person person = CurrentPerson; if (person != null) { pnlPrivatePrayer.Visible = true; string name = person.FullName.Replace(" ", ""); string guid = person.Guid.ToString().Replace("-", ""); string uid = name + guid; hdnDisplayName.Value = person.FullName; hdnPerson.Value = person.Id.ToString(); hdnRoom.Value = name + guid; hdnEmail.Value = person.Email; hdnPhoto.Value = person.PhotoUrl; hdnDate.Value = DateTime.Now.Date.ToShortDateString().Replace("/", ""); var baseDate = new DateTime(1970, 1, 1); var startDate = (DateTime.Now.ToUniversalTime() - baseDate).TotalSeconds; var endDate = ((DateTime.Now.AddHours(1)).ToUniversalTime() - baseDate).TotalSeconds; var payload = new Dictionary<string, object>() { {"aud", ConfigurationManager.AppSettings["FirebaseAud"].ToString() }, {"iat", Math.Truncate(startDate) }, {"exp", Math.Truncate(endDate) }, {"iss", ConfigurationManager.AppSettings["FirebaseIss"].ToString() }, {"sub", ConfigurationManager.AppSettings["FirebaseIss"].ToString() }, {"user_id", uid }, {"scope", "https://www.googleapis.com/auth/identitytoolkit" } }; var header = new Dictionary<string, object>() { {"alg", "RS256" }, {"kid", ConfigurationManager.AppSettings["FirebaseKid"].ToString() }, {"typ", "JWT" } }; string filePath = Server.MapPath(ConfigurationManager.AppSettings["CertFile"]); RSACryptoServiceProvider cert = new X509Certificate2(filePath, ConfigurationManager.AppSettings["CertPassword"], X509KeyStorageFlags.Exportable).PrivateKey as RSACryptoServiceProvider; System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.ImportCspBlob(cert.ExportCspBlob(true)); string token = Jose.JWT.Encode(payload, rsa, Jose.JwsAlgorithm.RS256, extraHeaders: header); hdnToken.Value = token; } else { // add in logic for person not logged in } }
protected void Page_Load(object sender, EventArgs e) { Person person = CurrentPerson; if (person != null) { pnlPrivatePrayer.Visible = true; string name = person.FullName.Replace(" ", ""); string guid = person.Guid.ToString().Replace("-", ""); string uid = name + guid; hdnDisplayName.Value = person.FullName; hdnPerson.Value = person.Id.ToString(); hdnRoom.Value = name + guid; hdnEmail.Value = person.Email; hdnPhoto.Value = person.PhotoUrl; hdnDate.Value = DateTime.Now.Date.ToShortDateString().Replace("/", ""); var baseDate = new DateTime(1970, 1, 1); var startDate = (DateTime.Now.ToUniversalTime() - baseDate).TotalSeconds; var endDate = ((DateTime.Now.AddHours(1)).ToUniversalTime() - baseDate).TotalSeconds; var payload = new Dictionary <string, object>() { { "aud", ConfigurationManager.AppSettings["FirebaseAud"].ToString() }, { "iat", Math.Truncate(startDate) }, { "exp", Math.Truncate(endDate) }, { "iss", ConfigurationManager.AppSettings["FirebaseIss"].ToString() }, { "sub", ConfigurationManager.AppSettings["FirebaseIss"].ToString() }, { "user_id", uid }, { "scope", "https://www.googleapis.com/auth/identitytoolkit" } }; var header = new Dictionary <string, object>() { { "alg", "RS256" }, { "kid", ConfigurationManager.AppSettings["FirebaseKid"].ToString() }, { "typ", "JWT" } }; string filePath = Server.MapPath(ConfigurationManager.AppSettings["CertFile"]); RSACryptoServiceProvider cert = new X509Certificate2(filePath, ConfigurationManager.AppSettings["CertPassword"], X509KeyStorageFlags.Exportable).PrivateKey as RSACryptoServiceProvider; System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); rsa.ImportCspBlob(cert.ExportCspBlob(true)); // string token = Jose.JWT.Encode(payload, rsa, Jose.JwsAlgorithm.RS256, extraHeaders: header); // hdnToken.Value = token; } else { // add in logic for person not logged in } }
//decrypts with private key public static byte[] Decrypt(string key, byte[] data) { var cspParams = new CspParameters { ProviderType = 1 }; var rsaProvider = new RSACryptoServiceProvider(cspParams); rsaProvider.ImportCspBlob(Convert.FromBase64String(key)); var plainData = rsaProvider.Decrypt(data, false); return plainData; }
public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var rsa = new RSACryptoServiceProvider(); rsa.ImportCspBlob(Convert.FromBase64String(ConfigurationManager.AppSettings["PrivateAsymmetricKey"])); var accessToken = new AuthorizationServerAccessToken() { AccessTokenSigningKey = rsa, ResourceServerEncryptionKey = rsa, }; var result = new AccessTokenResult(accessToken); result.AllowRefreshToken = false; return result; }
public string Encrypt(string input, string publicKey, Dictionary<string, object> metadata = null) { CspParameters cspParams = new CspParameters {ProviderType = 1}; RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams); rsaProvider.ImportCspBlob(Convert.FromBase64String(publicKey)); byte[] plainBytes = Encoding.UTF8.GetBytes(input); byte[] encryptedBytes = rsaProvider.Encrypt(plainBytes, false); return Convert.ToBase64String(encryptedBytes); }
public static byte[] Encrypt(string publicKey, byte[] data) { var cspParams = new CspParameters { ProviderType = 1 }; var rsaProvider = new RSACryptoServiceProvider(cspParams); rsaProvider.ImportCspBlob(Convert.FromBase64String(publicKey)); //data is encrypted var encryptedBytes = rsaProvider.Encrypt(data, false); return encryptedBytes; }
public Encrypt(Guid OwnerID, string addedBy) { //Get Public Key and Set Up RSA Encryption myRSA = new RSACryptoServiceProvider(); myRSA.ImportCspBlob(Convert.FromBase64String(ConfigurationSettings.AppSettings["SubKey"])); myRijndael = new RijndaelManaged(); this.ObjectID = Guid.NewGuid(); this.OwnerID = OwnerID; this.addedBY = addedBy; this.SubmissionID = Guid.NewGuid(); }
public string Decrypt(string input, string privateKey, Dictionary<string, object> metadata = null) { var encryptedBytes = Convert.FromBase64String(input); CspParameters cspParams = new CspParameters {ProviderType = 1}; RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams); rsaProvider.ImportCspBlob(Convert.FromBase64String(privateKey)); byte[] plainBytes = rsaProvider.Decrypt(encryptedBytes, false); string plainText = Encoding.UTF8.GetString(plainBytes, 0, plainBytes.Length); return plainText; }
public static byte[] Encrypt(string publicKey, string data) { CspParameters cspParams = new CspParameters { ProviderType = 1 }; RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams); rsaProvider.ImportCspBlob(Convert.FromBase64String(publicKey)); byte[] plainBytes = Encoding.UTF8.GetBytes(data); byte[] encryptedBytes = rsaProvider.Encrypt(plainBytes, false); return encryptedBytes; }
/// <summary>Extracts a <see cref="Key"/> from the given certificate.</summary> public Initializer FromCertificate(X509Certificate2 certificate) { #if NETSTANDARD Key = certificate.GetRSAPrivateKey(); #else // Workaround to correctly cast the private key as a RSACryptoServiceProvider type 24. RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certificate.PrivateKey; byte[] privateKeyBlob = rsa.ExportCspBlob(true); Key = new RSACryptoServiceProvider(); Key.ImportCspBlob(privateKeyBlob); #endif return(this); }
public static string Decrypt(string privateKey, byte[] encryptedBytes) { CspParameters cspParams = new CspParameters { ProviderType = 1 }; RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams); rsaProvider.ImportCspBlob(Convert.FromBase64String(privateKey)); byte[] plainBytes = rsaProvider.Decrypt(encryptedBytes, false); string plainText = Encoding.UTF8.GetString(plainBytes, 0, plainBytes.Length); return plainText; }
public static byte[] Encrypt(byte[] data, KeyPair kp) { byte[] raw; using (var rsa = new RSACryptoServiceProvider()) { rsa.ImportCspBlob(Decompress(Base32.FromBase32String(kp.Public))); raw = rsa.Encrypt(data, true); } return raw; }
/// <summary> /// RSA签名 /// </summary> /// <param name="strKeyPrivate">私钥</param> /// <param name="HashbyteSignature">待签名Hash描述</param> /// <param name="EncryptedSignatureData">签名后的结果</param> /// <returns></returns> public bool SignatureFormatter(string strKeyPrivate, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData) { try { System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.ImportCspBlob(Convert.FromBase64String(strKeyPrivate));//载入钥 //RSA.FromXmlString(strKeyPrivate); System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); //设置签名的算法为MD5 RSAFormatter.SetHashAlgorithm("MD5"); //执行签名 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); return(true); } catch (Exception ex) { throw ex; } }
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]); }
public static byte[] Decrypt(byte[] privKey, byte[] data) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportCspBlob(privKey); byte[] x = rsa.Decrypt(data, false); return x; }