本文整理汇总了C#中System.Security.Cryptography.X509Certificates.X509Certificate2.GetRSAPublicKey方法的典型用法代码示例。如果您正苦于以下问题:C# X509Certificate2.GetRSAPublicKey方法的具体用法?C# X509Certificate2.GetRSAPublicKey怎么用?C# X509Certificate2.GetRSAPublicKey使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.X509Certificates.X509Certificate2
的用法示例。
在下文中一共展示了X509Certificate2.GetRSAPublicKey方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetCipherTextBlockSize
/// <summary>
/// Return the ciphertext block size for RSA OAEP encryption.
/// </summary>
public static int GetCipherTextBlockSize(X509Certificate2 encryptingCertificate, bool useOaep)
{
using (RSA rsa = encryptingCertificate.GetRSAPublicKey())
{
if (rsa != null)
{
return rsa.KeySize / 8;
}
}
return -1;
}
示例2: RsaPkcs15_GetSignatureLength
/// <summary>
/// Returns the length of a RSA PKCS#1 v1.5 signature.
/// </summary>
private static int RsaPkcs15_GetSignatureLength(X509Certificate2 signingCertificate)
{
using (RSA rsa = signingCertificate.GetRSAPublicKey())
{
if (rsa == null)
{
throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "No public key for certificate.");
}
return rsa.KeySize / 8;
}
}
示例3: GetPlainTextBlockSize
/// <summary>
/// Return the plaintext block size for RSA OAEP encryption.
/// </summary>
public static int GetPlainTextBlockSize(X509Certificate2 encryptingCertificate, bool useOaep)
{
using (RSA rsa = encryptingCertificate.GetRSAPublicKey())
{
if (rsa != null)
{
if (useOaep)
{
return rsa.KeySize / 8 - 42;
}
else
{
return rsa.KeySize / 8 - 11;
}
}
}
return -1;
}
示例4: Encrypt
/// <summary>
/// Encrypts the data using RSA PKCS#1 v1.5 or OAEP encryption.
/// </summary>
public static ArraySegment<byte> Encrypt(
ArraySegment<byte> dataToEncrypt,
X509Certificate2 encryptingCertificate,
bool useOaep,
ArraySegment<byte> outputBuffer)
{
// get the encrypting key.
using (RSA rsa = encryptingCertificate.GetRSAPublicKey())
{
if (rsa == null)
{
throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "No public key for certificate.");
}
int inputBlockSize = GetPlainTextBlockSize(encryptingCertificate, useOaep);
int outputBlockSize = rsa.KeySize / 8;
// verify the input data is the correct block size.
if (dataToEncrypt.Count % inputBlockSize != 0)
{
Utils.Trace("Message is not an integral multiple of the block size. Length = {0}, BlockSize = {1}.", dataToEncrypt.Count, inputBlockSize);
}
byte[] encryptedBuffer = outputBuffer.Array;
using (MemoryStream ostrm = new MemoryStream(
encryptedBuffer,
outputBuffer.Offset,
outputBuffer.Count))
{
// encrypt body.
byte[] input = new byte[inputBlockSize];
for (int ii = dataToEncrypt.Offset; ii < dataToEncrypt.Offset + dataToEncrypt.Count; ii += inputBlockSize)
{
Array.Copy(dataToEncrypt.Array, ii, input, 0, input.Length);
if (useOaep == true)
{
byte[] cipherText = rsa.Encrypt(input, RSAEncryptionPadding.OaepSHA1);
ostrm.Write(cipherText, 0, cipherText.Length);
}
else
{
byte[] cipherText = rsa.Encrypt(input, RSAEncryptionPadding.Pkcs1);
ostrm.Write(cipherText, 0, cipherText.Length);
}
}
}
// return buffer
return new ArraySegment<byte>(
encryptedBuffer,
outputBuffer.Offset,
(dataToEncrypt.Count / inputBlockSize) * outputBlockSize);
}
}
示例5: RsaPkcs15Sha1_Verify
/// <summary>
/// Verifies an RSA/SHA1 PKCS#1 v1.5 signature.
/// </summary>
public static bool RsaPkcs15Sha1_Verify(
ArraySegment<byte> dataToVerify,
byte[] signature,
X509Certificate2 signingCertificate)
{
// extract the private key.
using (RSA rsa = signingCertificate.GetRSAPublicKey())
{
if (rsa == null)
{
throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "No public key for certificate.");
}
// verify signature.
return rsa.VerifyData(dataToVerify.Array, dataToVerify.Offset, dataToVerify.Count, signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
}
}
示例6: RsaPkcs15_Verify
/// <summary>
/// Verifies an RSA PKCS#1 v1.5 signature of a hash algorithm for the stream.
/// </summary>
private static bool RsaPkcs15_Verify(
ArraySegment<byte> dataToVerify,
byte[] signature,
X509Certificate2 signingCertificate,
HashAlgorithmName algorithm)
{
// extract the public key.
using (RSA rsa = signingCertificate.GetRSAPublicKey())
{
if (rsa == null)
{
throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "No public key for certificate.");
}
// verify signature.
if (!rsa.VerifyData(dataToVerify.Array, dataToVerify.Offset, dataToVerify.Count, signature, algorithm, RSASignaturePadding.Pkcs1))
{
string messageType = new UTF8Encoding().GetString(dataToVerify.Array, dataToVerify.Offset, 4);
int messageLength = BitConverter.ToInt32(dataToVerify.Array, dataToVerify.Offset + 4);
string actualSignature = Utils.ToHexString(signature);
Utils.Trace(
"Could not validate signature.\r\nCertificate={0}, MessageType={1}, Length={2}\r\nActualSignature={3}",
signingCertificate.Subject,
messageType,
messageLength,
actualSignature);
return false;
}
}
return true;
}
示例7: EncryptPkcsPadding
public static byte[] EncryptPkcsPadding(X509Certificate2 cert, byte[] rgb)
{
#if NET45 || NET451
return ((RSACryptoServiceProvider)cert.PublicKey.Key).Encrypt(rgb, false);
#else
using (var rsa = cert.GetRSAPublicKey())
{
return rsa.Encrypt(rgb, RSAEncryptionPadding.Pkcs1);
}
#endif
}
示例8: CheckApplicationInstanceCertificate
/// <summary>
/// Creates an application instance certificate if one does not already exist.
/// </summary>
private static async Task<bool> CheckApplicationInstanceCertificate(
ApplicationConfiguration configuration,
X509Certificate2 certificate,
bool silent,
ushort minimumKeySize)
{
if (certificate == null)
{
return false;
}
Utils.Trace(Utils.TraceMasks.Information, "Checking application instance certificate. {0}", certificate.Subject);
// validate certificate.
configuration.CertificateValidator.Validate(certificate);
// check key size.
if (minimumKeySize > certificate.GetRSAPublicKey().KeySize)
{
string message = Utils.Format(
"The key size ({0}) in the certificate is less than the minimum provided ({1}). Use certificate anyway?",
certificate.GetRSAPublicKey().KeySize,
minimumKeySize);
if (!silent && MessageDlg!=null)
{
MessageDlg.Message(message, true);
if (!await MessageDlg.ShowAsync())
{
return false;
}
}
else
{
Utils.Trace(message);
return false;
}
}
// check domains.
if (configuration.ApplicationType != ApplicationType.Client)
{
if (!await CheckDomainsInCertificate(configuration, certificate, silent))
{
return false;
}
}
// check uri.
string applicationUri = Utils.GetApplicationUriFromCertificate(certificate);
if (String.IsNullOrEmpty(applicationUri))
{
string message = "The Application URI could not be read from the certificate. Use certificate anyway?";
if (!silent && MessageDlg != null)
{
MessageDlg.Message(message, true);
if (!await MessageDlg.ShowAsync())
{
return false;
}
}
else
{
Utils.Trace(message);
return false;
}
}
else
{
configuration.ApplicationUri = applicationUri;
}
// update configuration.
configuration.SecurityConfiguration.ApplicationCertificate.Certificate = certificate;
return true;
}
示例9: ReadAsymmetricMessage
//.........这里部分代码省略.........
{
if (securityPolicyUri != SecurityPolicies.None)
{
throw ServiceResultException.Create(StatusCodes.BadSecurityPolicyRejected, "The security policy is not supported.");
}
m_securityMode = MessageSecurityMode.None;
m_securityPolicyUri = SecurityPolicies.None;
m_discoveryOnly = true;
m_uninitialized = false;
m_selectedEndpoint = null;
}
}
int headerSize = decoder.Position;
// decrypt the body.
ArraySegment<byte> plainText = Decrypt(
new ArraySegment<byte>(buffer.Array, buffer.Offset + headerSize, buffer.Count - headerSize),
new ArraySegment<byte>(buffer.Array, buffer.Offset, headerSize),
receiverCertificate);
// extract signature.
int signatureSize = GetAsymmetricSignatureSize(senderCertificate);
byte[] signature = new byte[signatureSize];
for (int ii = 0; ii < signatureSize; ii++)
{
signature[ii] = plainText.Array[plainText.Offset+plainText.Count-signatureSize+ii];
}
// verify the signature.
ArraySegment<byte> dataToVerify = new ArraySegment<byte>(plainText.Array, plainText.Offset, plainText.Count-signatureSize);
if (!Verify(dataToVerify, signature, senderCertificate))
{
Utils.Trace("Could not verify signature on message.");
throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "Could not verify the signature on the message.");
}
// verify padding.
int paddingCount = 0;
if (SecurityMode != MessageSecurityMode.None)
{
int paddingEnd = -1;
if (receiverCertificate.GetRSAPublicKey().KeySize > TcpMessageLimits.KeySizeExtraPadding)
{
paddingEnd = plainText.Offset + plainText.Count - signatureSize - 1;
paddingCount = plainText.Array[paddingEnd - 1] + plainText.Array[paddingEnd] * 256;
//parse until paddingStart-1; the last one is actually the extrapaddingsize
for (int ii = paddingEnd - paddingCount; ii < paddingEnd; ii++)
{
if (plainText.Array[ii] != plainText.Array[paddingEnd - 1])
{
throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "Could not verify the padding in the message.");
}
}
}
else
{
paddingEnd = plainText.Offset + plainText.Count - signatureSize - 1;
paddingCount = plainText.Array[paddingEnd];
for (int ii = paddingEnd - paddingCount; ii < paddingEnd; ii++)
{
if (plainText.Array[ii] != plainText.Array[paddingEnd])
{
throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "Could not verify the padding in the message.");
}
}
}
paddingCount++;
}
// decode message.
decoder = new BinaryDecoder(
plainText.Array,
plainText.Offset + headerSize,
plainText.Count - headerSize,
Quotas.MessageContext);
sequenceNumber = decoder.ReadUInt32(null);
requestId = decoder.ReadUInt32(null);
headerSize += decoder.Position;
decoder.Close();
Utils.Trace("Security Policy: {0}", SecurityPolicyUri);
Utils.Trace("Sender Certificate: {0}", (senderCertificate != null)?senderCertificate.Subject:"(none)");
// return the body.
return new ArraySegment<byte>(
plainText.Array,
plainText.Offset + headerSize,
plainText.Count - headerSize - signatureSize - paddingCount);
}
示例10: WriteAsymmetricMessage
/// <summary>
/// Sends a OpenSecureChannel response.
/// </summary>
protected BufferCollection WriteAsymmetricMessage(
uint messageType,
uint requestId,
X509Certificate2 senderCertificate,
X509Certificate2 receiverCertificate,
ArraySegment<byte> messageBody)
{
bool success = false;
BufferCollection chunksToSend = new BufferCollection();
byte[] buffer = BufferManager.TakeBuffer(SendBufferSize, "WriteAsymmetricMessage");
try
{
int headerSize = GetAsymmetricHeaderSize(SecurityPolicyUri, senderCertificate);
int signatureSize = GetAsymmetricSignatureSize(senderCertificate);
BinaryEncoder encoder = new BinaryEncoder(buffer, 0, SendBufferSize, Quotas.MessageContext);
WriteAsymmetricMessageHeader(
encoder,
messageType | TcpMessageType.Intermediate,
ChannelId,
SecurityPolicyUri,
senderCertificate,
receiverCertificate);
// save the header.
ArraySegment<byte> header = new ArraySegment<byte>(buffer, 0, headerSize);
// calculate the space available.
int plainTextBlockSize = GetPlainTextBlockSize(receiverCertificate);
int cipherTextBlockSize = GetCipherTextBlockSize(receiverCertificate);
int maxCipherTextSize = SendBufferSize - headerSize;
int maxCipherBlocks = maxCipherTextSize/cipherTextBlockSize;
int maxPlainTextSize = maxCipherBlocks*plainTextBlockSize;
int maxPayloadSize = maxPlainTextSize - signatureSize - 1 - TcpMessageLimits.SequenceHeaderSize;
int bytesToWrite = messageBody.Count;
int startOfBytes = messageBody.Offset;
while (bytesToWrite > 0)
{
encoder.WriteUInt32(null, GetNewSequenceNumber());
encoder.WriteUInt32(null, requestId);
int payloadSize = bytesToWrite;
if (payloadSize > maxPayloadSize)
{
payloadSize = maxPayloadSize;
}
else
{
UpdateMessageType(buffer, 0, messageType | TcpMessageType.Final);
}
// write the message body.
encoder.WriteRawBytes(messageBody.Array, messageBody.Offset+startOfBytes, payloadSize);
// calculate the amount of plain text to encrypt.
int plainTextSize = encoder.Position - headerSize + signatureSize;
// calculate the padding.
int padding = 0;
if (SecurityMode != MessageSecurityMode.None)
{
if (receiverCertificate.GetRSAPublicKey().KeySize <= TcpMessageLimits.KeySizeExtraPadding)
{
// need to reserve one byte for the padding.
plainTextSize++;
if (plainTextSize % plainTextBlockSize != 0)
{
padding = plainTextBlockSize - (plainTextSize % plainTextBlockSize);
}
encoder.WriteByte(null, (byte)padding);
for (int ii = 0; ii < padding; ii++)
{
encoder.WriteByte(null, (byte)padding);
}
}
else
{
// need to reserve one byte for the padding.
plainTextSize++;
// need to reserve one byte for the extrapadding.
plainTextSize++;
if (plainTextSize % plainTextBlockSize != 0)
{
padding = plainTextBlockSize - (plainTextSize % plainTextBlockSize);
}
byte paddingSize = (byte)(padding & 0xff);
//.........这里部分代码省略.........