/// <summary> /// Decrypts data using the private key. /// </summary> public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { unsafe { return EncryptOrDecrypt(data, padding, Interop.NCrypt.NCryptDecrypt); } }
private static void TestEncryptDecryptRoundTrip(byte[] plainText, RSAEncryptionPadding paddingMode, int expectedCipherSize) { using (RSA rsaCng = new RSACng()) { byte[] cipher = rsaCng.Encrypt(plainText, paddingMode); // RSACng.Encrypt() is intentionally non-deterministic so we can verify that we got back a cipher of the right length // but nothing about the contents. Assert.Equal(expectedCipherSize, cipher.Length); // But we can test to see that it decrypts back to the original. byte[] plainTextAgain = rsaCng.Decrypt(cipher, paddingMode); Assert.Equal<byte>(plainText, plainTextAgain); } }
// // Conveniently, Encrypt() and Decrypt() are identical save for the actual P/Invoke call to CNG. Thus, both // APIs invoke this common helper with the "transform" parameter determining whether encryption or decryption is done. // private byte[] EncryptOrDecrypt(byte[] data, RSAEncryptionPadding padding, EncryptOrDecryptAction encryptOrDecrypt) { if (data == null) throw new ArgumentNullException(nameof(data)); if (padding == null) throw new ArgumentNullException(nameof(padding)); unsafe { using (SafeNCryptKeyHandle keyHandle = GetDuplicatedKeyHandle()) { switch (padding.Mode) { case RSAEncryptionPaddingMode.Pkcs1: return EncryptOrDecrypt(keyHandle, data, AsymmetricPaddingMode.NCRYPT_PAD_PKCS1_FLAG, null, encryptOrDecrypt); case RSAEncryptionPaddingMode.Oaep: { using (SafeUnicodeStringHandle safeHashAlgorithmName = new SafeUnicodeStringHandle(padding.OaepHashAlgorithm.Name)) { BCRYPT_OAEP_PADDING_INFO paddingInfo = new BCRYPT_OAEP_PADDING_INFO() { pszAlgId = safeHashAlgorithmName.DangerousGetHandle(), // It would nice to put randomized data here but RSAEncryptionPadding does not at this point provide support for this. pbLabel = IntPtr.Zero, cbLabel = 0, }; return EncryptOrDecrypt(keyHandle, data, AsymmetricPaddingMode.NCRYPT_PAD_OAEP_FLAG, &paddingInfo, encryptOrDecrypt); } } default: throw new CryptographicException(SR.Cryptography_UnsupportedPaddingMode); } } } }
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) throw new ArgumentNullException("data"); if (padding == null) throw new ArgumentNullException("padding"); Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding); SafeRsaHandle key = _key.Value; CheckInvalidKey(key); byte[] buf = new byte[Interop.Crypto.RsaSize(key)]; int returnValue = Interop.Crypto.RsaPrivateDecrypt( data.Length, data, buf, key, rsaPadding); CheckReturn(returnValue); // If the padding mode is RSA_NO_PADDING then the size of the decrypted block // will be RSA_size, so let's just return buf. // // If any padding was used, then some amount (determined by the padding algorithm) // will have been reduced, and only returnValue bytes were part of the decrypted // body, so copy the decrypted bytes to an appropriately sized array before // returning it. if (returnValue == buf.Length) { return buf; } byte[] plainBytes = new byte[returnValue]; Array.Copy(buf, 0, plainBytes, 0, returnValue); return plainBytes; }
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) throw new ArgumentNullException("data"); if (padding == null) throw new ArgumentNullException("padding"); Interop.libcrypto.OpenSslRsaPadding openSslPadding; if (padding == RSAEncryptionPadding.Pkcs1) { openSslPadding = Interop.libcrypto.OpenSslRsaPadding.RSA_PKCS1_PADDING; } else if (padding == RSAEncryptionPadding.OaepSHA1) { openSslPadding = Interop.libcrypto.OpenSslRsaPadding.RSA_PKCS1_OAEP_PADDING; } else { throw PaddingModeNotSupported(); } return Decrypt(data, openSslPadding); }
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) { throw new NotImplementedException(SR.WorkInProgress); }
public virtual bool TryEncrypt(System.ReadOnlySpan <byte> data, System.Span <byte> destination, RSAEncryptionPadding padding, out int bytesWritten) { throw null; }
protected override byte[] Encrypt(RSA rsa, byte[] data, RSAEncryptionPadding padding) => TryWithOutputArray(dest => rsa.TryEncrypt(data, dest, padding, out int bytesWritten) ? (true, bytesWritten) : (false, 0));
/// <summary> /// RSA private key is decrypted /// </summary> /// <param name="data">Need to decrypt the data</param> /// <param name="padding">Padding algorithm</param> /// <returns></returns> public string DecryptByPrivateKey(string data, RSAEncryptionPadding padding) { return(DecryptByPrivateKey(Convert.FromBase64String(data), padding)); }
static byte[] DecryptData(X509Certificate2 cert, byte[] data, RSAEncryptionPadding padding) { using (RSA rsa = cert.GetRSAPrivateKey()) return(rsa.Decrypt(data, padding)); }
private static Interop.Crypto.RsaPadding GetInteropPadding(RSAEncryptionPadding padding) { if (padding == RSAEncryptionPadding.Pkcs1) { return Interop.Crypto.RsaPadding.Pkcs1; } else if (padding == RSAEncryptionPadding.OaepSHA1) { return Interop.Crypto.RsaPadding.OaepSHA1; } else { throw PaddingModeNotSupported(); } }
/// <summary> /// 将Base64字符串进行RSA解密,返回解密后的字符串,默认为【Xml格式】的私钥,默认【不分块】 /// </summary> /// <param name="data">要解密的【Base64字符串】</param> /// <param name="privateKey">私钥字符串</param> /// <param name="padding">填充方式枚举值</param> /// <param name="isXmlKey">是否为【Xml格式】私钥</param> /// <param name="autoBlock">是否自动分块</param> /// <returns></returns> public string Decrypt(string data, string privateKey, RSAEncryptionPadding padding, bool isXmlKey = true, bool autoBlock = false) => Decrypt(data.Base64ToBytes(), privateKey, padding, isXmlKey, autoBlock);
public static ICryptoValue DecryptByPrivateKey(byte[] cipherData, string privateKey, RsaKeyFormat format, RSAEncryptionPadding padding) { var key = RsaKeyGenerator.GeneratePrivateKey(privateKey, format); var function = Factory.Create(key); return(function.DecryptByPrivateKey(cipherData, padding)); }
public static ICryptoValue DecryptByPrivateKey(string cipherText, string privateKey, RsaKeyFormat format, RSAEncryptionPadding padding, Encoding encoding = null) { var key = RsaKeyGenerator.GeneratePrivateKey(privateKey, format); var function = Factory.Create(key); return(function.DecryptByPrivateKey(cipherText, padding, encoding)); }
public static ICryptoValue EncryptByPublicKey(byte[] originalData, string publicKey, RsaKeyFormat format, RSAEncryptionPadding padding) { var key = RsaKeyGenerator.GeneratePublicKey(publicKey, format); var function = Factory.Create(key); return(function.EncryptByPublicKey(originalData, padding)); }
public static ICryptoValue EncryptByPublicKey(string originalText, string publicKey, RsaKeyFormat format, RSAEncryptionPadding padding, Encoding encoding = null) { var key = RsaKeyGenerator.GeneratePublicKey(publicKey, format); var function = Factory.Create(key); return(function.EncryptByPublicKey(originalText, padding, encoding)); }
/// <summary> /// RSA 私钥解密。 /// </summary> /// <param name="cipher">密文的 Base64 编码结果。</param> /// <param name="privateKey">私钥(PEM 格式)。</param> /// <param name="encryptionPadding">对齐方式(默认 <see cref="RSAEncryptionPadding.Pkcs1" />)。</param> /// <returns>明文。</returns> public static string Decrypt(string cipher, string privateKey, RSAEncryptionPadding encryptionPadding) { return(Decrypt(cipher, privateKey, Encoding.UTF8, encryptionPadding)); }
/// <summary> /// RSA 私钥解密。 /// </summary> /// <param name="cipher">密文的 Base64 编码结果。</param> /// <param name="privateKey">私钥(PEM 格式)。</param> /// <param name="encoding">字符集(默认 <see cref="Encoding.UTF8" />)。</param> /// <param name="encryptionPadding">对齐方式(默认 <see cref="RSAEncryptionPadding.Pkcs1" />)。</param> /// <returns>明文。</returns> public static string Decrypt(string cipher, string privateKey, Encoding encoding, RSAEncryptionPadding encryptionPadding) { Guard.CheckArgumentNotNull(encoding, nameof(encoding)); privateKey = FormatPublicOrPrivateKey(privateKey); byte[] bytes = Decrypt(Convert.FromBase64String(cipher), Convert.FromBase64String(privateKey), encryptionPadding); return(encoding.GetString(bytes)); }
/// <summary> /// 使用公钥 RSA 加密。 /// </summary> /// <param name="plain">明文。</param> /// <param name="publicKey">公钥(PEM 格式)。</param> /// <param name="encryptionPadding">对齐方式(默认 <see cref="RSAEncryptionPadding.Pkcs1" />)。</param> /// <returns>密文的 Base64 编码结果。</returns> public static string Encrypt(string plain, string publicKey, RSAEncryptionPadding encryptionPadding) { return(Encrypt(plain, publicKey, Encoding.UTF8, encryptionPadding)); }
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) { throw new ArgumentNullException("data"); } if (padding == null) { throw new ArgumentNullException("padding"); } if (padding == RSAEncryptionPadding.Pkcs1) { return NCryptNative.EncryptDataPkcs1(KeyHandle, data); } else if (padding.Mode == RSAEncryptionPaddingMode.Oaep) { return NCryptNative.EncryptDataOaep(KeyHandle, data, padding.OaepHashAlgorithm.Name); } else { // no other padding possibilities at present, but we might version independently from more being added. throw new CryptographicException(SR.GetString(SR.Cryptography_UnsupportedPaddingMode)); }; }
public EncryptedConsulKeyAclProvider(string encryptedKeyName, X509Certificate2 encryptionCertifcate, RSAEncryptionPadding padding) { if (!encryptionCertifcate.HasPrivateKey) { throw new ArgumentException("Certificate needs to have the private key to decrypt"); } if (encryptedKeyName.StartsWith("/")) { encryptedKeyName = encryptedKeyName.Substring(1); } using (var httpClient = HttpUtils.CreateClient(null)) { var keyValues = httpClient.GetStringAsync($"/v1/kv/{encryptedKeyName}").Result; var keys = JsonConvert.DeserializeObject <KeyValue[]>(keyValues); if (keys.Length != 1) { throw new ArgumentException($"Should only be a single key returned from query but had {keys.Length}"); } var keyValue = Encoding.UTF8.GetString(Convert.FromBase64String(keys[0].Value)); var decryptedValue = encryptionCertifcate.GetRSAPrivateKey().Decrypt(Convert.FromBase64String(keyValue), padding); _aclToken = Encoding.UTF8.GetString(decryptedValue); } }
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding);
public byte[] Decrypt(byte[] buffer, RSAEncryptionPadding padding) { return(Decrypt(buffer, 0, buffer.Length, padding)); }
/// <summary> /// 使用公钥 RSA 加密。 /// </summary> /// <param name="plain">明文。</param> /// <param name="publicKey">公钥(PEM 格式)。</param> /// <param name="encoding">字符集(默认 <see cref="Encoding.UTF8" />)。</param> /// <param name="encryptionPadding">对齐方式(默认 <see cref="RSAEncryptionPadding.Pkcs1" />)。</param> /// <returns>密文的 Base64 编码结果。</returns> public static string Encrypt(string plain, string publicKey, Encoding encoding, RSAEncryptionPadding encryptionPadding) { Guard.CheckArgumentNotNull(encoding, nameof(encoding)); publicKey = FormatPublicOrPrivateKey(publicKey); byte[] bytes = Encrypt(encoding.GetBytes(plain), Convert.FromBase64String(publicKey), encryptionPadding); return(Convert.ToBase64String(bytes)); }
protected override byte[] Decrypt(RSA rsa, byte[] data, RSAEncryptionPadding padding) => rsa.Decrypt(data, padding);
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) => DecryptDelegate(data, padding);
protected abstract byte[] Decrypt(RSA rsa, byte[] data, RSAEncryptionPadding padding);
/// <summary> /// RSA public key encryption /// </summary> /// <param name="data">Need to encrypt data</param> /// <param name="padding">Padding algorithm</param> /// <returns></returns> public string EncryptByPrivateKey(string data, RSAEncryptionPadding padding) { return(EncryptByPrivateKey(DataEncoding.GetBytes(data), padding)); }
private byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { using RSA rsa = KeyMaterial.ToRSA(true); return(rsa.Decrypt(data, padding)); }
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) { throw new NotImplementedException(); }
CmsRecipient(X509Certificate2 certificate, RSAEncryptionPadding rsaEncryptionPadding !!) : this(certificate)
protected override async Task OnOpenAsync(CancellationToken token) { await base.OnOpenAsync(token).ConfigureAwait(false); token.ThrowIfCancellationRequested(); this.sendBuffer = new byte[this.LocalSendBufferSize]; this.receiveBuffer = new byte[this.LocalReceiveBufferSize]; if (this.LocalCertificate != null) { this.localCertificateBlob = this.LocalCertificate.RawData; } this.remoteCertificateBlob = this.RemoteEndpoint.ServerCertificate; if (this.remoteCertificateBlob != null) { this.RemoteCertificate = new X509Certificate2(this.remoteCertificateBlob); } if (this.RemoteEndpoint.SecurityMode == MessageSecurityMode.SignAndEncrypt) { if (this.LocalCertificate == null) { throw new ServiceResultException(StatusCodes.BadSecurityChecksFailed, "LocalCertificate is null."); } if (this.RemoteCertificate == null) { throw new ServiceResultException(StatusCodes.BadSecurityChecksFailed, "RemoteCertificate is null."); } this.LocalPrivateKey = this.LocalCertificate.GetRSAPrivateKey(); this.RemotePublicKey = this.RemoteCertificate.GetRSAPublicKey(); switch (this.RemoteEndpoint.SecurityPolicyUri) { case SecurityPolicyUris.Basic128Rsa15: this.asymEncryptionPadding = RSAEncryptionPadding.Pkcs1; this.asymSignatureHashAlgorithmName = HashAlgorithmName.SHA1; this.symSigner = new HMACSHA1(); this.symVerifier = new HMACSHA1(); this.symEncryptionAlgorithm = Aes.Create(); this.symEncryptionAlgorithm.Mode = CipherMode.CBC; this.symEncryptionAlgorithm.Padding = PaddingMode.None; this.asymLocalKeySize = this.LocalPrivateKey.KeySize; this.asymRemoteKeySize = this.RemotePublicKey.KeySize; this.asymLocalPlainTextBlockSize = Math.Max((this.asymLocalKeySize / 8) - 11, 1); this.asymRemotePlainTextBlockSize = Math.Max((this.asymRemoteKeySize / 8) - 11, 1); this.symSignatureSize = 20; this.symSignatureKeySize = 16; this.symEncryptionBlockSize = 16; this.symEncryptionKeySize = 16; break; case SecurityPolicyUris.Basic256: this.asymEncryptionPadding = RSAEncryptionPadding.OaepSHA1; this.asymSignatureHashAlgorithmName = HashAlgorithmName.SHA1; this.symSigner = new HMACSHA1(); this.symVerifier = new HMACSHA1(); this.symEncryptionAlgorithm = Aes.Create(); this.symEncryptionAlgorithm.Mode = CipherMode.CBC; this.symEncryptionAlgorithm.Padding = PaddingMode.None; this.asymLocalKeySize = this.LocalPrivateKey.KeySize; this.asymRemoteKeySize = this.RemotePublicKey.KeySize; this.asymLocalPlainTextBlockSize = Math.Max((this.asymLocalKeySize / 8) - 42, 1); this.asymRemotePlainTextBlockSize = Math.Max((this.asymRemoteKeySize / 8) - 42, 1); this.symSignatureSize = 20; this.symSignatureKeySize = 24; this.symEncryptionBlockSize = 16; this.symEncryptionKeySize = 32; break; case SecurityPolicyUris.Basic256Sha256: this.asymEncryptionPadding = RSAEncryptionPadding.OaepSHA1; this.asymSignatureHashAlgorithmName = HashAlgorithmName.SHA256; this.symSigner = new HMACSHA256(); this.symVerifier = new HMACSHA256(); this.symEncryptionAlgorithm = Aes.Create(); this.symEncryptionAlgorithm.Mode = CipherMode.CBC; this.symEncryptionAlgorithm.Padding = PaddingMode.None; this.asymLocalKeySize = this.LocalPrivateKey.KeySize; this.asymRemoteKeySize = this.RemotePublicKey.KeySize; this.asymLocalPlainTextBlockSize = Math.Max((this.asymLocalKeySize / 8) - 42, 1); this.asymRemotePlainTextBlockSize = Math.Max((this.asymRemoteKeySize / 8) - 42, 1); this.symSignatureSize = 32; this.symSignatureKeySize = 32; this.symEncryptionBlockSize = 16; this.symEncryptionKeySize = 32; break; default: throw new ServiceResultException(StatusCodes.BadSecurityPolicyRejected); } this.asymIsSigned = this.asymIsEncrypted = true; this.symIsSigned = true; this.symIsEncrypted = true; this.asymLocalSignatureSize = this.asymLocalKeySize / 8; this.asymLocalCipherTextBlockSize = Math.Max(this.asymLocalKeySize / 8, 1); this.asymRemoteSignatureSize = this.asymRemoteKeySize / 8; this.asymRemoteCipherTextBlockSize = Math.Max(this.asymRemoteKeySize / 8, 1); this.clientSigningKey = new byte[this.symSignatureKeySize]; this.clientEncryptingKey = new byte[this.symEncryptionKeySize]; this.clientInitializationVector = new byte[this.symEncryptionBlockSize]; this.serverSigningKey = new byte[this.symSignatureKeySize]; this.serverEncryptingKey = new byte[this.symEncryptionKeySize]; this.serverInitializationVector = new byte[this.symEncryptionBlockSize]; this.encryptionBuffer = new byte[this.LocalSendBufferSize]; } else if (this.RemoteEndpoint.SecurityMode == MessageSecurityMode.Sign) { if (this.LocalCertificate == null) { throw new ServiceResultException(StatusCodes.BadSecurityChecksFailed, "LocalCertificate is null."); } if (this.RemoteCertificate == null) { throw new ServiceResultException(StatusCodes.BadSecurityChecksFailed, "RemoteCertificate is null."); } this.LocalPrivateKey = this.LocalCertificate.GetRSAPrivateKey(); this.RemotePublicKey = this.RemoteCertificate.GetRSAPublicKey(); switch (this.RemoteEndpoint.SecurityPolicyUri) { case SecurityPolicyUris.Basic128Rsa15: this.asymEncryptionPadding = RSAEncryptionPadding.Pkcs1; this.asymSignatureHashAlgorithmName = HashAlgorithmName.SHA1; this.symSigner = new HMACSHA1(); this.symVerifier = new HMACSHA1(); this.asymLocalKeySize = this.LocalPrivateKey.KeySize; this.asymRemoteKeySize = this.RemotePublicKey.KeySize; this.asymLocalPlainTextBlockSize = Math.Max((this.asymLocalKeySize / 8) - 11, 1); this.asymRemotePlainTextBlockSize = Math.Max((this.asymRemoteKeySize / 8) - 11, 1); this.symSignatureSize = 20; this.symSignatureKeySize = 16; this.symEncryptionBlockSize = 16; this.symEncryptionKeySize = 16; break; case SecurityPolicyUris.Basic256: this.asymEncryptionPadding = RSAEncryptionPadding.OaepSHA1; this.asymSignatureHashAlgorithmName = HashAlgorithmName.SHA1; this.symSigner = new HMACSHA1(); this.symVerifier = new HMACSHA1(); this.asymLocalKeySize = this.LocalPrivateKey.KeySize; this.asymRemoteKeySize = this.RemotePublicKey.KeySize; this.asymLocalPlainTextBlockSize = Math.Max((this.asymLocalKeySize / 8) - 42, 1); this.asymRemotePlainTextBlockSize = Math.Max((this.asymRemoteKeySize / 8) - 42, 1); this.symSignatureSize = 20; this.symSignatureKeySize = 24; this.symEncryptionBlockSize = 16; this.symEncryptionKeySize = 32; break; case SecurityPolicyUris.Basic256Sha256: this.asymEncryptionPadding = RSAEncryptionPadding.OaepSHA1; this.asymSignatureHashAlgorithmName = HashAlgorithmName.SHA256; this.symSigner = new HMACSHA256(); this.symVerifier = new HMACSHA256(); this.asymLocalKeySize = this.LocalPrivateKey.KeySize; this.asymRemoteKeySize = this.RemotePublicKey.KeySize; this.asymLocalPlainTextBlockSize = Math.Max((this.asymLocalKeySize / 8) - 42, 1); this.asymRemotePlainTextBlockSize = Math.Max((this.asymRemoteKeySize / 8) - 42, 1); this.symSignatureSize = 32; this.symSignatureKeySize = 32; this.symEncryptionBlockSize = 16; this.symEncryptionKeySize = 32; break; default: throw new ServiceResultException(StatusCodes.BadSecurityPolicyRejected); } this.asymIsSigned = this.asymIsEncrypted = true; this.symIsSigned = true; this.symIsEncrypted = false; this.asymLocalSignatureSize = this.asymLocalKeySize / 8; this.asymLocalCipherTextBlockSize = Math.Max(this.asymLocalKeySize / 8, 1); this.asymRemoteSignatureSize = this.asymRemoteKeySize / 8; this.asymRemoteCipherTextBlockSize = Math.Max(this.asymRemoteKeySize / 8, 1); this.clientSigningKey = new byte[this.symSignatureKeySize]; this.clientEncryptingKey = new byte[this.symEncryptionKeySize]; this.clientInitializationVector = new byte[this.symEncryptionBlockSize]; this.serverSigningKey = new byte[this.symSignatureKeySize]; this.serverEncryptingKey = new byte[this.symEncryptionKeySize]; this.serverInitializationVector = new byte[this.symEncryptionBlockSize]; this.encryptionBuffer = new byte[this.LocalSendBufferSize]; } else if (this.RemoteEndpoint.SecurityMode == MessageSecurityMode.None) { this.asymIsSigned = this.asymIsEncrypted = false; this.symIsSigned = this.symIsEncrypted = false; this.asymLocalKeySize = 0; this.asymRemoteKeySize = 0; this.asymLocalSignatureSize = 0; this.asymLocalCipherTextBlockSize = 1; this.asymRemoteSignatureSize = 0; this.asymRemoteCipherTextBlockSize = 1; this.asymLocalPlainTextBlockSize = 1; this.asymRemotePlainTextBlockSize = 1; this.symSignatureSize = 0; this.symSignatureKeySize = 0; this.symEncryptionBlockSize = 1; this.symEncryptionKeySize = 0; this.encryptionBuffer = null; } else { throw new ServiceResultException(StatusCodes.BadSecurityModeRejected); } this.sendRequestsTask = Task.Run(() => this.SendRequestsAsync(this.channelCts.Token)); this.receiveResponsesTask = Task.Run(() => this.ReceiveResponsesAsync(this.channelCts.Token)); var openSecureChannelRequest = new OpenSecureChannelRequest { ClientProtocolVersion = ProtocolVersion, RequestType = SecurityTokenRequestType.Issue, SecurityMode = this.RemoteEndpoint.SecurityMode, ClientNonce = this.symIsSigned ? this.GetNextNonce() : null, RequestedLifetime = TokenRequestedLifetime }; var openSecureChannelResponse = (OpenSecureChannelResponse)await this.RequestAsync(openSecureChannelRequest).ConfigureAwait(false); if (openSecureChannelResponse.ServerProtocolVersion < ProtocolVersion) { throw new ServiceResultException(StatusCodes.BadProtocolVersionUnsupported); } await this.sendingSemaphore.WaitAsync(token).ConfigureAwait(false); try { this.ChannelId = openSecureChannelResponse.SecurityToken.ChannelId; this.TokenId = openSecureChannelResponse.SecurityToken.TokenId; this.tokenRenewalTime = DateTime.UtcNow.AddMilliseconds(0.75 * openSecureChannelResponse.SecurityToken.RevisedLifetime); if (this.symIsSigned) { var clientNonce = openSecureChannelRequest.ClientNonce; var serverNonce = openSecureChannelResponse.ServerNonce; // (re)create client security keys for encrypting the next message sent var clientSecurityKey = CalculatePSHA(serverNonce, clientNonce, this.symSignatureKeySize + this.symEncryptionKeySize + this.symEncryptionBlockSize, this.asymSignatureHashAlgorithmName); Buffer.BlockCopy(clientSecurityKey, 0, this.clientSigningKey, 0, this.symSignatureKeySize); Buffer.BlockCopy(clientSecurityKey, this.symSignatureKeySize, this.clientEncryptingKey, 0, this.symEncryptionKeySize); Buffer.BlockCopy(clientSecurityKey, this.symSignatureKeySize + this.symEncryptionKeySize, this.clientInitializationVector, 0, this.symEncryptionBlockSize); // (re)create server security keys for decrypting the next message received that has a new TokenId var serverSecurityKey = CalculatePSHA(clientNonce, serverNonce, this.symSignatureKeySize + this.symEncryptionKeySize + this.symEncryptionBlockSize, this.asymSignatureHashAlgorithmName); Buffer.BlockCopy(serverSecurityKey, 0, this.serverSigningKey, 0, this.symSignatureKeySize); Buffer.BlockCopy(serverSecurityKey, this.symSignatureKeySize, this.serverEncryptingKey, 0, this.symEncryptionKeySize); Buffer.BlockCopy(serverSecurityKey, this.symSignatureKeySize + this.symEncryptionKeySize, this.serverInitializationVector, 0, this.symEncryptionBlockSize); } } finally { this.sendingSemaphore.Release(); } }
public Task <byte[]> AsymetricDecrypt(string certificateThumbprint, byte[] data, RSAEncryptionPadding padding) { if (certificateThumbprint == null) { throw new ArgumentNullException(nameof(certificateThumbprint)); } if (data == null) { throw new ArgumentNullException(nameof(data)); } if (!string.Equals(certificateThumbprint, this.p12Certificate.Thumbprint, StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException($"This instance does not contain certificate with thumbprint {certificateThumbprint}."); } byte[] decrypted = this.p12Certificate.GetRSAPrivateKey().Decrypt(data, padding); return(Task.FromResult(decrypted)); }
public virtual byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { throw DerivedClassMustOverride(); }
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (padding == null) throw new ArgumentNullException(nameof(padding)); if (padding == RSAEncryptionPadding.Pkcs1) { return Decrypt(data, fOAEP: false); } else if (padding == RSAEncryptionPadding.OaepSHA1) { return Decrypt(data, fOAEP: true); } else { throw PaddingModeNotSupported(); } }
public abstract byte[] Decrypt(byte[] data, RSAEncryptionPadding padding);
/// <summary> /// 分块解密 /// </summary> /// <param name="value">已加密的值</param> /// <param name="key">私钥</param> /// <param name="encoding">编码</param> /// <param name="padding">填充方式</param> /// <returns></returns> public static string DecryptBlock(string value, string key, Encoding encoding, RSAEncryptionPadding padding) { byte[] data = Convert.FromBase64String(value); var provider = CreateRsaProviderFromPrivateKey(key); int bufferSize = provider.KeySize / 8;//单块最大长度 var buffer = new byte[bufferSize]; using (MemoryStream inputStream = new MemoryStream(data), outputStream = new MemoryStream()) { while (true) { int readSize = inputStream.Read(buffer, 0, bufferSize); if (readSize <= 0) { break; } var temp = new byte[readSize]; Array.Copy(buffer, 0, temp, 0, readSize); var rawBytes = provider.Decrypt(temp, padding); outputStream.Write(rawBytes, 0, rawBytes.Length); } provider.Dispose(); return(encoding.GetString(outputStream.ToArray())); } }
public RsaCryptoProvider(RSA cng, RSAEncryptionPadding padding) { _cng = cng; _padding = padding; }
/// <summary> /// 将字符串进行RSA加密,返回加密后的Base64字符串,默认为【Xml格式】的密钥,默认【不分块】 /// </summary> /// <param name="data">要加密的字符串</param> /// <param name="key">公钥或私钥字符串</param> /// <param name="padding">填充方式枚举值</param> /// <param name="isXmlKey">是否为【Xml格式】私钥</param> /// <param name="autoBlock">是否自动分块</param> /// <returns>【Base64字符串】</returns> public string Encrypt(string data, string key, RSAEncryptionPadding padding, bool isXmlKey = true, bool autoBlock = false) => Encrypt(data.ToBytes(), key, padding, isXmlKey, autoBlock);
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) { if (data == null) throw new ArgumentNullException("data"); if (padding == null) throw new ArgumentNullException("padding"); Interop.Crypto.RsaPadding rsaPadding = GetInteropPadding(padding); SafeRsaHandle key = _key.Value; CheckInvalidKey(key); byte[] buf = new byte[Interop.Crypto.RsaSize(key)]; int returnValue = Interop.Crypto.RsaPublicEncrypt( data.Length, data, buf, key, rsaPadding); CheckReturn(returnValue); return buf; }
/// <summary> /// 将字节数组进行RSA解密,返回解密后的字符串,默认为【Xml格式】的私钥,默认【不分块】 /// </summary> /// <param name="data">要解密的字节数组</param> /// <param name="privateKey">私钥字符串</param> /// <param name="padding">填充方式枚举值</param> /// <param name="isXmlKey">是否为【Xml格式】私钥</param> /// <param name="autoBlock">是否自动分块</param> /// <returns></returns> public string Decrypt(byte[] data, string privateKey, RSAEncryptionPadding padding, bool isXmlKey = true, bool autoBlock = false) => DecryptBytes(data, privateKey, padding, isXmlKey, autoBlock)?.BytesToString();
public static bool TryGetRsaOaepEncryptionPadding( ReadOnlyMemory <byte>?parameters, out RSAEncryptionPadding rsaEncryptionPadding, out Exception exception) { exception = null; rsaEncryptionPadding = null; if (parameters == null || parameters.Value.IsEmpty) { exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); return(false); } try { OaepParamsAsn oaepParameters = OaepParamsAsn.Decode(parameters.Value, AsnEncodingRules.DER); if (oaepParameters.MaskGenFunc.Algorithm.Value != Oids.Mgf1 || oaepParameters.MaskGenFunc.Parameters == null || oaepParameters.PSourceFunc.Algorithm.Value != Oids.PSpecified ) { exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); return(false); } AlgorithmIdentifierAsn mgf1AlgorithmIdentifier = AlgorithmIdentifierAsn.Decode(oaepParameters.MaskGenFunc.Parameters.Value, AsnEncodingRules.DER); if (mgf1AlgorithmIdentifier.Algorithm.Value != oaepParameters.HashFunc.Algorithm.Value) { exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); return(false); } if (oaepParameters.PSourceFunc.Parameters != null && !oaepParameters.PSourceFunc.Parameters.Value.Span.SequenceEqual(s_pSpecifiedDefaultParameters)) { exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); return(false); } switch (oaepParameters.HashFunc.Algorithm.Value) { case Oids.Sha1: rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA1; return(true); case Oids.Sha256: rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA256; return(true); case Oids.Sha384: rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA384; return(true); case Oids.Sha512: rsaEncryptionPadding = RSAEncryptionPadding.OaepSHA512; return(true); default: exception = new CryptographicException( SR.Cryptography_Cms_UnknownAlgorithm, oaepParameters.HashFunc.Algorithm.Value); return(false); } } catch (CryptographicException e) { exception = e; return(false); } }
/// <summary> /// RSA解密 /// </summary> /// <param name="keyType"></param> /// <param name="privateKey"></param> /// <param name="data"></param> /// <param name="padding"></param> /// <param name="encoding"></param> /// <returns></returns> public static string Decrypt(RsaKeyType keyType, string privateKey, string data, RSAEncryptionPadding padding, Encoding encoding = null) { return(Rsa.Decrypt(keyType, privateKey, data, padding, encoding)); }
/// <summary> /// 将字节数组进行RSA加密,返回加密后的Base64字符串,默认为【Xml格式】的密钥,默认【不分块】 /// </summary> /// <param name="data">要加密的字节数组</param> /// <param name="key">公钥或私钥字符串</param> /// <param name="padding">填充方式枚举值</param> /// <param name="isXmlKey">是否为【Xml格式】私钥</param> /// <param name="autoBlock">是否自动分块</param> /// <returns>【Base64字符串】</returns> public string Encrypt(byte[] data, string key, RSAEncryptionPadding padding, bool isXmlKey = true, bool autoBlock = false) => EncryptBytes(data, key, padding, isXmlKey, autoBlock)?.ToBase64();
/// <summary> /// 分块加密 /// </summary> /// <param name="value">待加密的值</param> /// <param name="key">公钥</param> /// <param name="encoding">编码</param> /// <param name="padding">填充方式</param> /// <returns></returns> public static string EncryptBlock(string value, string key, Encoding encoding, RSAEncryptionPadding padding) { byte[] data = encoding.GetBytes(value); var provider = CreateRsaProviderFromPublicKey(key); int bufferSize = (provider.KeySize / 8) - 11;//单块最大长度 var buffer = new byte[bufferSize]; using (MemoryStream inputStream = new MemoryStream(data), outStream = new MemoryStream()) { while (true) { // 分段加密 int readSize = inputStream.Read(buffer, 0, bufferSize); if (readSize <= 0) { break; } var temp = new byte[readSize]; Array.Copy(buffer, 0, temp, 0, readSize); RSACryptoServiceProvider a = new RSACryptoServiceProvider(); var encryptedBytes = provider.Encrypt(temp, padding); outStream.Write(encryptedBytes, 0, encryptedBytes.Length); } provider.Dispose(); return(Convert.ToBase64String(outStream.ToArray())); } }