大牛们,帮我译成C#吧!

屌丝女士111 2016-08-29 11:02:03
 /* 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);
...全文
1112 23 打赏 收藏 转发到动态 举报
写回复
用AI写文章
23 条回复
切换为时间正序
请发表友善的回复…
发表回复
沫含天下 2019-11-29
  • 打赏
  • 举报
回复
引用 26 楼 lijing3333 的回复:
java的代码直接全部拷贝到vs里面 让vs自己报错 然后一个个的改就行了。。。。
lijing3333 2019-11-28
  • 打赏
  • 举报
回复
java的代码直接全部拷贝到vs里面 让vs自己报错 然后一个个的改就行了。。。。
token不能为空 2018-06-14
  • 打赏
  • 举报
回复
引用 16 楼 zengjun1980 的回复:
你去研究下,C#的BouncyCastle.Crypto
这个玩意有api文档吗,官网没找到啊
CyberLogix 2018-06-13
  • 打赏
  • 举报
回复
吧相应的API换成.NET的就行了
  • 打赏
  • 举报
回复
.NET Framework 4.7.2 提供大量的加密增强功能、对 ZIP 存档更好的解压缩支持以及额外的集合 API。 RSA.Create 和 DSA.Create 的新重载 利用 DSA.Create(DSAParameters) 和 RSA.Create(RSAParameters) 方法,可在实例化新的 DSA 或 RSA 密钥时提供密钥参数。 它们允许你替换如下所示的代码:
// 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" />
屌丝女士111 2018-06-13
  • 打赏
  • 举报
回复
引用 16 楼 zengjun1980 的回复:
你去研究下,C#的BouncyCastle.Crypto
屌丝女士111 Bbs5 点醒我了,悔现在才来回贴 感谢
屌丝女士111 2018-06-13
  • 打赏
  • 举报
回复
点醒我了,悔现在才来回贴 感谢
zengjun1980 2016-11-03
  • 打赏
  • 举报
回复
你去研究下,C#的BouncyCastle.Crypto
屌丝女士111 2016-09-01
  • 打赏
  • 举报
回复
继续关注,大家看看难点尼
屌丝女士111 2016-08-30
  • 打赏
  • 举报
回复
引用 10 楼 twotuli_software 的回复:
5块钱一行,敢不敢?
能翻出来,而且能用 有什么不敢的
屌丝女士111 2016-08-30
  • 打赏
  • 举报
回复
引用 11 楼 HW_1549924525 的回复:
引用
10#
全翻译出来算五块一行 ,不能就不算
先翻一下cer加密,看看水平再说 如果行,没问题啊
HW_1549924525 2016-08-30
  • 打赏
  • 举报
回复
引用
引用
啊啊啊啊
HW_1549924525 2016-08-30
  • 打赏
  • 举报
回复
引用
10#
全翻译出来算五块一行 ,不能就不算
维秀斯丢丢 2016-08-30
  • 打赏
  • 举报
回复
5块钱一行,敢不敢?
屌丝女士111 2016-08-29
  • 打赏
  • 举报
回复
大牛们,不会还是不屑于解决啊! 等.............
屌丝女士111 2016-08-29
  • 打赏
  • 举报
回复
引用 5 楼 shingoscar 的回复:
楼主要是愿意发工资的话,咱可以商量下
哎 意思是你有解决方案咯 说吧 多少钱
屌丝女士111 2016-08-29
  • 打赏
  • 举报
回复
引用 6 楼 BEYONDMA 的回复:
如果你的问题是哪句话不懂还好。
你好,我的问题出在,我在取pfx带有私钥和公钥的证书时提示: 网络密码不正确 因为怕会误导大家,所以才直接贴码直译 // 一个pfx文件地址,一个是导出私钥的密码 X509Certificate2 c3 = new X509Certificate2(pfxFileName, password); //string keyPublic3 = c3.PublicKey.Key.ToXmlString(false); // 公钥 //string keyPrivate3 = c3.PrivateKey.ToXmlString(true); // 私钥 //string cypher3 = OperCert.RSAEncrypt(keyPublic3, "邮件表体内容,哈哈哈哈哈哈哈"); // 加密 //对于java里面的代码是: 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());
屌丝女士111 2016-08-29
  • 打赏
  • 举报
回复
引用 2 楼 Forty2 的回复:
技术论坛是探讨技术的,不是代工的不是? 论坛朋友们又不能替你领工资。
肯定是常识过解决方案,才来询问的, 那你的意思是想有偿回答咯!
beyondma 2016-08-29
  • 打赏
  • 举报
回复
如果你的问题是哪句话不懂还好。
Poopaye 2016-08-29
  • 打赏
  • 举报
回复
楼主要是愿意发工资的话,咱可以商量下
加载更多回复(3)

110,571

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧