一個完整的類用來生成RSACryptoServiceProvider單例類(.NET)

FrankYou發表於2015-07-21
 1 internal class CcbRsaCryptProvider
 2 {
 3         private static RSACryptoServiceProvider _providerForSign;
 4         private static RSACryptoServiceProvider _providerForVerifySign;
 5         private static readonly object SignObj = new object();
 6         private static readonly object VerifySignObj = new object();
 7 
 8         internal static RSACryptoServiceProvider GetInstanceForSign(string privateKeyFile)
 9         {
10             if (null != _providerForSign) return _providerForSign;
11             lock (SignObj)
12             {
13                 if (null != _providerForSign) return _providerForSign;
14                 var provider = new RSACryptoServiceProvider();
15                 provider.FromXmlString(GetXmlContent(privateKeyFile));
16                 _providerForSign = provider;
17             }
18             return _providerForSign;
19         }
20 
21         internal static RSACryptoServiceProvider GetInstanceForVerifySign(string publicKeyFile)
22         {
23             if (null != _providerForVerifySign) return _providerForVerifySign;
24             lock (VerifySignObj)
25             {
26                 if (null != _providerForVerifySign) return _providerForVerifySign;
27                 var provider = new RSACryptoServiceProvider();
28                 provider.FromXmlString(GetXmlContent(publicKeyFile));
29                 _providerForVerifySign = provider;
30             }
31             return _providerForVerifySign;
32         }
33 
34         private static string GetXmlContent(string filePath)
35         {
36             return File.ReadAllText(filePath);
37         }
38 
39         private CcbRsaCryptProvider()
40         {
41         }
42     }

 

相關文章