110,571
社区成员
发帖
与我相关
我的任务
分享
/* Add BC */
Security.addProvider(new BouncyCastleProvider());
String pkcs12Path = "xxx.pfx";
String keyalias = "xxxx";
String keyPwd = "******";
String smtpServer = xxx.xxx.com";
String emailAddress = "xxx.xxx.com";
String emailPwd = "xxxxx";
ArrayList<AddressInfo> toAdd = new ArrayList<>();
String path = "xxxx@djkeji.cer";
FileInputStream fi = new FileInputStream(path);
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
X509Certificate cert = (X509Certificate) cf.generateCertificate(fi);
toAdd.add(new AddressInfo("xxxxx@xxxxxxx.com", cert));
try {
MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mailcap.addMailcap("application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature");
mailcap.addMailcap("application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime");
mailcap.addMailcap("application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature");
mailcap.addMailcap("application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime");
mailcap.addMailcap("multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed");
CommandMap.setDefaultCommandMap(mailcap);
/* Open the keystore */
KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
keystore.load(new FileInputStream(pkcs12Path), "".toCharArray());
Certificate[] chain = keystore.getCertificateChain(keyalias);
/* Get the private key to sign the message with */
PrivateKey privateKey = (PrivateKey) keystore.getKey(keyalias, keyPwd.toCharArray());
if (privateKey == null) {
throw new Exception("cannot find private key for alias: " + keyalias);
}
/* Create the message to sign and encrypt */
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpServer);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, new MyAuthenticator(emailAddress, emailPwd));
MimeMessage body = new MimeMessage(session);
body.setFrom(new InternetAddress(emailAddress));
if (toAdd != null) {
body.addRecipients(Message.RecipientType.TO, parseEmailAdd(toAdd));
}
if (ccAdd != null) {
body.addRecipients(Message.RecipientType.CC, parseEmailAdd(ccAdd));
}
if (bccAdd != null) {
body.addRecipients(Message.RecipientType.BCC, parseEmailAdd(bccAdd));
}
body.setSubject(subject);
body.setContent(textContent, "text/plain");
body.saveChanges();
/* Create the SMIMESignedGenerator */
SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
capabilities.addCapability(SMIMECapability.dES_CBC);
ASN1EncodableVector attributes = new ASN1EncodableVector();
attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(new IssuerAndSerialNumber(new X500Name(((X509Certificate) chain[0]).getIssuerDN().getName()),
((X509Certificate) chain[0]).getSerialNumber())));
attributes.add(new SMIMECapabilitiesAttribute(capabilities));
SMIMESignedGenerator signer = new SMIMESignedGenerator();
signer.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC").setSignedAttributeGenerator(new AttributeTable(attributes))
.build("DSA".equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withRSA", privateKey, (X509Certificate) chain[0]));
/* Add the list of certs to the generator */
List certList = new ArrayList();
certList.add(chain[0]);
Store certs = new JcaCertStore(certList);
signer.addCertificates(certs);
/* Sign the message */
MimeMultipart mm = signer.generate(body);
MimeMessage signedMessage = new MimeMessage(session);
/* Set all original MIME headers in the signed message */
Enumeration headers = body.getAllHeaderLines();
while (headers.hasMoreElements()) {
signedMessage.addHeaderLine((String) headers.nextElement());
}
/* Set the content of the signed message */
signedMessage.setContent(mm);
signedMessage.saveChanges();
/* Create the encrypter */
SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator();
addRecipientInfoGenerator(encrypter, toAdd);//
addRecipientInfoGenerator(encrypter, ccAdd);
addRecipientInfoGenerator(encrypter, bccAdd);
/* Encrypt the message */
MimeBodyPart encryptedPart = encrypter.generate(signedMessage, new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC).setProvider("BC").build());
/*
* Create a new MimeMessage that contains the encrypted and signed
* content
*/
ByteArrayOutputStream out = new ByteArrayOutputStream();
encryptedPart.writeTo(out);
MimeMessage encryptedMessage = new MimeMessage(session, new ByteArrayInputStream(out.toByteArray()));
/* Set all original MIME headers in the encrypted message */
headers = body.getAllHeaderLines();
while (headers.hasMoreElements()) {
String headerLine = (String) headers.nextElement();
/*
* Make sure not to override any content-* headers from the
* original message
*/
if (!Strings.toLowerCase(headerLine).startsWith("content-")) {
encryptedMessage.addHeaderLine(headerLine);
}
}
Transport.send(encryptedMessage);
} catch (SMIMEException ex) {
ex.getUnderlyingException().printStackTrace(System.err);
ex.printStackTrace(System.err);
} catch (Exception ex) {
ex.printStackTrace(System.err);
// Before .NET Framework 4.7.2
using (RSA rsa = RSA.Create())
{
rsa.ImportParameters(rsaParameters);
// Other code to execute using the RSA instance.
}
采用类似如下所示的代码:
// Starting with .NET Framework 4.7.2
using (RSA rsa = RSA.Create(rsaParameters))
{
// Other code to execute using the rsa instance.
}
DSA.Create(Int32) 和 RSA.Create(Int32) 方法允许生成具有特定密钥大小的 DSA 或 RSA 密钥。 例如:
using (DSA dsa = DSA.Create(2048))
{
// Other code to execute using the dsa instance.
}
Rfc2898DeriveBytes 构造函数接受哈希算法名称
Rfc2898DeriveBytes 类具有三个带 HashAlgorithmName 参数的构造函数,该参数标识在派生密钥时使用的 HMAC 算法。 与 SHA-1 相比,开发人员应使用基于 SHA-2 的 HMAC,例如 SHA-256,如下面的示例所示:
private static byte[] DeriveKey(string password, out int iterations, out byte[] salt,
out HashAlgorithmName algorithm)
{
iterations = 100000;
algorithm = HashAlgorithmName.SHA256;
const int SaltSize = 32;
const int DerivedValueSize = 32;
using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, SaltSize,
iterations, algorithm))
{
salt = pbkdf2.Salt;
return pbkdf2.GetBytes(DerivedValueSize);
}
}
临时密钥支持
PFX 导入可以选择绕过硬盘直接从内存加载私钥。 如果在 X509Certificate2 构造函数或 X509Certificate2.Import 方法的其中一个重载中指定了新的 X509KeyStorageFlags.EphemeralKeySet 标记,则私钥将加载为临时密钥。 这能防止密钥在磁盘上可见。 但是:
由于密钥不会保留到磁盘,最好不要将通过此标记加载的证书添加到 X509Store。
以这种方式加载的密钥大多都是通过 Windows CNG 加载的。 因此,调用方必须通过调用扩展方法访问私钥,例如 cert.GetRSAPrivateKey()。 X509Certificate2.PrivateKey 属性不起作用。
由于旧的 X509Certificate2.PrivateKey 属性对证书不起作用,开发人员应在切换至临时密钥之前执行严密的测试。
PKCS#10 证书签名请求和 X.509 公钥证书的编程式创建
从 .NET Framework 4.7.2 开始,工作负载可以生成证书签名请求 (CSR),这允许将证书请求生成分阶到现有工具中。 这在测试方案中常常很有用。
有关详细信息和代码示例,请参阅 .NET 博客中的“PKCS#10 证书签名请求和 X.509 公钥证书的编程式创建”。
新的 SignerInfo 成员
从 .NET Framework 4.7.2 开始,SignerInfo 类将公开更多有关签名的信息。 你可以检索 System.Security.Cryptography.Pkcs.SignerInfo.SignatureAlgorithm 属性的值,以确定签名者采用的签名算法。 可以调用 SignerInfo.GetSignature 来获取此签名者的加密签名副本。
在 CryptoStream 释放后保持包装流打开
从 .NET Framework 4.7.2 开始,CryptoStream 类有了一个额外的构造函数可允许 Dispose 不关闭包装流。 若要在释放 CryptoStream 实例后保持包装流的打开状态,请调用新的 CryptoStream 构造函数,如下所示:
var cStream = new CryptoStream(stream, transform, mode, leaveOpen: true);
DeflateStream 中的解压缩更改
从 .NET Framework 4.7.2 开始,DeflateStream 类中的解压缩操作的实现变为默认使用本机 Windows API。 这样通常能大大地提高性能。
对于面向 .NET Framework 4.7.2 的应用程序,默认启用通过使用 Windows API 进行解压缩的支持。 对于面向旧版 .NET Framework 但在 .NET Framework 4.7.2 下运行的应用程序,可以将以下 AppContext 开关添加到应用程序配置文件,从而选择启用此行为:
<AppContextSwitchOverrides value="Switch.System.IO.Compression.DoNotUseNativeZipLibraryForDecompression=false" /> 10#
楼主要是愿意发工资的话,咱可以商量下
如果你的问题是哪句话不懂还好。
技术论坛是探讨技术的,不是代工的不是? 论坛朋友们又不能替你领工资。