本文整理汇总了C#中System.Security.Cryptography.Pkcs.EnvelopedCms.Encode方法的典型用法代码示例。如果您正苦于以下问题:C# EnvelopedCms.Encode方法的具体用法?C# EnvelopedCms.Encode怎么用?C# EnvelopedCms.Encode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.Pkcs.EnvelopedCms
的用法示例。
在下文中一共展示了EnvelopedCms.Encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Rc4AndCngWrappersDontMixTest
public static void Rc4AndCngWrappersDontMixTest()
{
//
// Combination of RC4 over a CAPI certificate.
//
// This works as long as the PKCS implementation opens the cert using CAPI. If he creates a CNG wrapper handle (by passing CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG),
// the test fails with a NOTSUPPORTED crypto exception inside Decrypt(). The same happens if the key is genuinely CNG.
//
byte[] content = { 6, 3, 128, 33, 44 };
AlgorithmIdentifier rc4 = new AlgorithmIdentifier(new Oid(Oids.Rc4));
EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(content), rc4);
CmsRecipientCollection recipients = new CmsRecipientCollection(new CmsRecipient(Certificates.RSAKeyTransferCapi1.GetCertificate()));
ecms.Encrypt(recipients);
byte[] encodedMessage = ecms.Encode();
ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
if (cert == null)
return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can.
X509Certificate2Collection extraStore = new X509Certificate2Collection();
extraStore.Add(cert);
ecms.Decrypt(extraStore);
}
ContentInfo contentInfo = ecms.ContentInfo;
Assert.Equal<byte>(content, contentInfo.Content);
}
示例2: EncryptedBytes
private byte[] EncryptedBytes(byte[] bytes)
{
var contentInfo = new ContentInfo(bytes);
var encryptAlgoOid = new Oid("2.16.840.1.101.3.4.1.42"); // AES-256-CBC
var envelopedCms = new EnvelopedCms(contentInfo, new AlgorithmIdentifier(encryptAlgoOid));
var recipient = new CmsRecipient(CryptographicCertificate);
envelopedCms.Encrypt(recipient);
return envelopedCms.Encode();
}
示例3: Encrypt
/// <summary>
/// Encrypts the specified string.
/// </summary>
/// <param name="plaintext">The plaintext to be encrypted.</param>
/// <param name="certificate">The certificate to be used for encryption.</param>
/// <returns>The encrypted text.</returns>
public static string Encrypt(this string plaintext, X509Certificate2 certificate)
{
var contentInfo = new ContentInfo(Encoding.UTF8.GetBytes(plaintext));
var envelopedCms = new EnvelopedCms(contentInfo);
var cmsRecipient = new CmsRecipient(certificate);
envelopedCms.Encrypt(cmsRecipient);
return Convert.ToBase64String(envelopedCms.Encode());
}
示例4: DecodeCertificates0_RoundTrip
public static void DecodeCertificates0_RoundTrip()
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(contentInfo);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
CmsRecipient cmsRecipient = new CmsRecipient(cert);
ecms.Encrypt(cmsRecipient);
}
byte[] encodedMessage = ecms.Encode();
VerifyCertificates0(encodedMessage);
}
示例5: DecodeAlgorithmDes_RoundTrip
public static void DecodeAlgorithmDes_RoundTrip()
{
AlgorithmIdentifier algorithm = new AlgorithmIdentifier(new Oid(Oids.Des));
ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(contentInfo, algorithm);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
CmsRecipient cmsRecipient = new CmsRecipient(cert);
ecms.Encrypt(cmsRecipient);
}
byte[] encodedMessage = ecms.Encode();
VerifyAlgorithmDes(encodedMessage);
}
示例6: DecodeRecipients3_RoundTrip
public static void DecodeRecipients3_RoundTrip()
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(contentInfo);
CmsRecipientCollection recipients = new CmsRecipientCollection();
foreach (X509Certificate2 cert in s_certs)
{
recipients.Add(new CmsRecipient(cert));
}
ecms.Encrypt(recipients);
byte[] encodedMessage = ecms.Encode();
VerifyRecipients3(encodedMessage);
}
示例7: GetEnvelopedMime
/// <summary>
/// Decrypts enveloped mime content.
/// </summary>
/// <param name="cert">Decrypting certificate.</param>
/// <returns>Returns decrypted enveloped mime content.</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>cert</b> is null reference.</exception>
/// <exception cref="InvalidOperationException">Is raised when <b>smime-type != enveloped-data</b>.</exception>
public MIME_Message GetEnvelopedMime(X509Certificate2 cert)
{
if(cert == null){
throw new ArgumentNullException("cert");
}
if(!string.Equals(this.Entity.ContentType.Parameters["smime-type"],"enveloped-data",StringComparison.InvariantCultureIgnoreCase)){
throw new InvalidOperationException("The VerifySignature method is only valid if Content-Type parameter smime-type=enveloped-data.");
}
EnvelopedCms envelopedCms = new EnvelopedCms();
envelopedCms.Decode(this.Data);
X509Certificate2Collection certificates = new X509Certificate2Collection(cert);
envelopedCms.Decrypt(certificates);
return MIME_Message.ParseFromStream(new MemoryStream(envelopedCms.Encode()));
}
示例8: ZeroLengthContent_RoundTrip
public static void ZeroLengthContent_RoundTrip()
{
ContentInfo contentInfo = new ContentInfo(Array.Empty<byte>());
EnvelopedCms ecms = new EnvelopedCms(contentInfo);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
CmsRecipient cmsRecipient = new CmsRecipient(cert);
try
{
ecms.Encrypt(cmsRecipient);
}
catch (CryptographicException e)
{
throw new Exception("ecms.Encrypt() threw " + e.Message + ".\nIf you're running on the desktop CLR, this is actually an expected result.");
}
}
byte[] encodedMessage = ecms.Encode();
ValidateZeroLengthContent(encodedMessage);
}
示例9: PostDecrypt_Encode
public static void PostDecrypt_Encode()
{
byte[] expectedContent = { 6, 3, 128, 33, 44 };
EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(expectedContent));
ecms.Encrypt(new CmsRecipient(Certificates.RSAKeyTransfer1.GetCertificate()));
byte[] encodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818067"
+ "6bada56dcaf2e65226941242db73b5a5420a6212cd6af662db52fdc0ca63875cb69066f7074da0fc009ce724e2d73fb19380"
+ "2deea8d92b069486a41c7c4fc3cd0174a918a559f79319039b40ae797bcacc909c361275ee2a5b1f0ff09fb5c19508e3f5ac"
+ "051ac0f03603c27fb8993d49ac428f8bcfc23a90ef9b0fac0f423a302b06092a864886f70d010701301406082a864886f70d"
+ "0307040828dc4d72ca3132e48008546cc90f2c5d4b79").HexToByteArray();
ecms.Decode(encodedMessage);
using (X509Certificate2 cer = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey())
{
if (cer == null)
return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can.
X509Certificate2Collection extraStore = new X509Certificate2Collection(cer);
RecipientInfoCollection r = ecms.RecipientInfos;
ecms.Decrypt(r[0], extraStore);
// Desktop compat: Calling Encode() at this point should have thrown an InvalidOperationException. Instead, it returns
// the decrypted inner content (same as ecms.ContentInfo.Content). This is easy for someone to take a reliance on
// so for compat sake, we'd better keep it.
byte[] encoded = ecms.Encode();
Assert.Equal<byte>(expectedContent, encoded);
}
}
示例10: EncryptAsBase64String
/// <summary>
/// Encrypt payload string into a base 64-encoded string using the certificate.
/// This is suitable for encrypting storage account keys for later use as a job argument.
/// </summary>
/// <param name="cert">
/// Certificate used to encrypt the payload.
/// </param>
/// <param name="payload">
/// Value to encrypt.
/// </param>
/// <returns>
/// Encrypted payload.
/// </returns>
public static string EncryptAsBase64String(X509Certificate2 cert, string payload)
{
var ci = new ContentInfo(Encoding.UTF8.GetBytes(payload));
var env = new EnvelopedCms(ci);
env.Encrypt(new CmsRecipient(cert));
return Convert.ToBase64String(env.Encode());
}
示例11: Encrypt
private string Encrypt(string password, X509Certificate2 cert)
{
byte[] bytes = Encoding.UTF8.GetBytes(password);
EnvelopedCms envelopedCms = new EnvelopedCms(new ContentInfo(bytes));
envelopedCms.Encrypt(new CmsRecipient(cert));
return Convert.ToBase64String(envelopedCms.Encode());
}
示例12: EncodeKeyTransl
private static KeyTransRecipientInfo EncodeKeyTransl(SubjectIdentifierType type = SubjectIdentifierType.IssuerAndSerialNumber)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(contentInfo);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
CmsRecipient cmsRecipient = new CmsRecipient(type, cert);
ecms.Encrypt(cmsRecipient);
}
byte[] encodedMessage = ecms.Encode();
EnvelopedCms ecms2 = new EnvelopedCms();
ecms2.Decode(encodedMessage);
RecipientInfoCollection recipients = ecms2.RecipientInfos;
Assert.Equal(1, recipients.Count);
RecipientInfo recipientInfo = recipients[0];
Assert.True(recipientInfo is KeyTransRecipientInfo);
return (KeyTransRecipientInfo)recipientInfo;
}
示例13: KrypterteBytes
private byte[] KrypterteBytes(byte[] bytes)
{
Logging.Log(TraceEventType.Information, Manifest.Forsendelse.KonversasjonsId, string.Format("Krypterer dokumentpakke med sertifikat {0}.", _krypteringssertifikat.Thumbprint));
var contentInfo = new ContentInfo(bytes);
var encryptAlgoOid = new Oid("2.16.840.1.101.3.4.1.42"); // AES-256-CBC
var envelopedCms = new EnvelopedCms(contentInfo, new AlgorithmIdentifier(encryptAlgoOid));
var recipient = new CmsRecipient(_krypteringssertifikat);
envelopedCms.Encrypt(recipient);
return envelopedCms.Encode();
}
示例14: HandleCertificateOperations
private static void HandleCertificateOperations(Options options, AuthenticationContext authContext, AuthenticationResult token)
{
using (var client = new KeyVaultManagementClient(new TokenCloudCredentials(options.SubscriptionId, token.AccessToken)))
{
if (!string.IsNullOrEmpty(options.ResourceGroup))
{
if (!string.IsNullOrEmpty(options.Vault))
{
var vaultInfo = client.Vaults.Get(options.ResourceGroup, options.Vault);
var vaultToken = authContext.AcquireToken("https://vault.azure.net", "1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob"));
var keyvaultClient = new KeyVaultClient((_, b, c) => Task.FromResult(vaultToken.AccessToken));
if (!string.IsNullOrEmpty(options.ExportCert))
{
var secret = keyvaultClient.GetSecretAsync(vaultInfo.Vault.Properties.VaultUri, options.ExportCert).GetAwaiter().GetResult();
var cert = new X509Certificate2(Convert.FromBase64String(secret.Value), new SecureString(), X509KeyStorageFlags.Exportable);
File.WriteAllBytes(options.Out, cert.Export(X509ContentType.Pfx));
}
if (!string.IsNullOrEmpty(options.Encrypt))
{
var secret = keyvaultClient.GetSecretAsync(vaultInfo.Vault.Properties.VaultUri, options.CertificateName).GetAwaiter().GetResult();
var cert = new X509Certificate2(Convert.FromBase64String(secret.Value));
byte[] encoded = System.Text.UTF8Encoding.UTF8.GetBytes(options.Encrypt);
var content = new ContentInfo(encoded);
var env = new EnvelopedCms(content);
env.Encrypt(new CmsRecipient(cert));
string encrypted64 = Convert.ToBase64String(env.Encode());
Console.WriteLine("Encrypting: {0}", options.Encrypt);
Console.WriteLine("Encrypted Base64 String: {0}", encrypted64);
}
if (!string.IsNullOrEmpty(options.Decrypt))
{
var secret = keyvaultClient.GetSecretAsync(vaultInfo.Vault.Properties.VaultUri, options.CertificateName).GetAwaiter().GetResult();
var cert = new X509Certificate2(Convert.FromBase64String(secret.Value));
var encryptedBytes = Convert.FromBase64String(options.Decrypt);
var envelope = new EnvelopedCms();
envelope.Decode(encryptedBytes);
envelope.Decrypt(new X509Certificate2Collection(cert));
Console.WriteLine("Decrypting: {0}", options.Decrypt);
Console.WriteLine("Decrypted String: {0}", Encoding.UTF8.GetString(envelope.ContentInfo.Content));
}
if (options.MakeCert)
{
var cert = Convert.ToBase64String(Certificate.CreateSelfSignCertificatePfx(string.Format("CN={0}", options.CertificateName), DateTime.UtcNow, DateTime.UtcNow.AddYears(2)));
var cert1 = new X509Certificate2(Convert.FromBase64String(cert));
var secrets = keyvaultClient.GetSecretsAsync(vaultInfo.Vault.Properties.VaultUri).GetAwaiter().GetResult();
if (secrets.Value == null || !secrets.Value.Any(s => s.Id == vaultInfo.Vault.Properties.VaultUri + "secrets/" + options.CertificateName))
{
Console.WriteLine(
JsonConvert.SerializeObject(keyvaultClient.SetSecretAsync(vaultInfo.Vault.Properties.VaultUri, options.CertificateName, cert, null, "application/pkcs12").GetAwaiter().GetResult()
, Formatting.Indented));
}
}
}
}
}
}
示例15: EncryptCmsRecipientUnknown
public void EncryptCmsRecipientUnknown ()
{
ContentInfo ci = new ContentInfo (asnNull);
EnvelopedCms ep = new EnvelopedCms (SubjectIdentifierType.IssuerAndSerialNumber, ci);
X509Certificate2 x509 = GetCertificate (false);
CmsRecipient p7r = new CmsRecipient (SubjectIdentifierType.Unknown, x509);
ep.Encrypt (p7r);
byte[] encoded = ep.Encode ();
#if DEBUG
FileStream fs = File.OpenWrite ("EncryptCmsRecipientUnknown.der");
fs.Write (encoded, 0, encoded.Length);
fs.Close ();
#endif
RoundTrip (encoded);
}