1
這裏是我的WCF服務代碼:如何使用BouncyCastle生成可用於WCF驗證的X509Certificate2?
ServiceHost svh = new ServiceHost(typeof(MyClass));
var tcpbinding = new NetTcpBinding(SecurityMode.TransportWithMessageCredential, true);
//security
tcpbinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
svh.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new BWUserNamePasswordValidator();
svh.Credentials.UserNameAuthentication.UserNamePasswordValidationMode =UserNamePasswordValidationMode.Custom;
svh.Credentials.ServiceCertificate.Certificate = GenerateCertificate(myCert);
svh.AddServiceEndpoint(typeof(IMyClass), tcpbinding, location);
svh.Open();
而這裏的代碼,我使用生成證書,其中:
static X509Certificate2 GenerateCertificate(string certName)
{
var keypairgen = new RsaKeyPairGenerator();
keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));
var keypair = keypairgen.GenerateKeyPair();
var gen = new X509V3CertificateGenerator();
var CN = new X509Name("CN=" + certName);
var SN = BigInteger.ProbablePrime(120, new Random());
gen.SetSerialNumber(SN);
gen.SetSubjectDN(CN);
gen.SetIssuerDN(CN);
gen.SetNotAfter(DateTime.MaxValue);
gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
gen.SetSignatureAlgorithm("MD5WithRSA");
gen.SetPublicKey(keypair.Public);
gen.AddExtension(X509Extensions.SubjectKeyIdentifier, false,
new SubjectKeyIdentifierStructure(keypair.Public));
var newCert = gen.Generate(keypair.Private);
return new X509Certificate2(DotNetUtilities.ToX509Certificate((Org.BouncyCastle.X509.X509Certificate)newCert));
}
當我開始它與下面的異常崩潰的服務器:
ArgumentException: It is likely that certificate 'CN=MyCert' may not
have a private key that is capable of key exchange or the process may not have
access rights for the private key. Please see inner exception for detail.
內部異常爲空。
我做錯了什麼?
增加了參數。該服務仍然不會從它開始。 我正在試驗用makecert創建一個可用的證書,並且正確的命令序列是 makecert -n「CN = mfcertificate」-cy權限-a sha1 -sv「nick_ca.pvk」-r「nick_ca.cer」 makecert -pe -n「CN = my Dev」-a sha1 -sky exchange -eku 1.3.6.1.5.5.7.3.1 -ic「nick_ca.cer」-iv「nick_ca.pvk」-sp「Microsoft RSA SChannel Cryptographic提供者「-sy 12 -sv」nick_dev.pvk「」nick_dev.cer「 pvk2pfx -pvk」nick_dev.pvk「-spc」nick_dev.cer「-pfx」nick_dev.pfx「 我不知道如何在BouncyCastle中做到這一點雖然 – 2012-02-12 19:26:14
你得到的錯誤將使用makecert與「-sky exchange」參數解決,我只是不知道BouncyCastle API足夠知道如何做到這一點。抱歉。 – 2012-02-12 19:34:48
實際上,它沒有解決,我試過了)) – 2012-02-12 19:36:04