用到的是:BouncyCastle.Crypto.dll类库
官网:http://www.bouncycastle.org/csharp/RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator(); //密钥构造器 RsaKeyGenerationParameters p = new RsaKeyGenerationParameters(BigInteger.ValueOf(3), new SecureRandom(), 1024, 25); //初始化密钥构造器 keyGenerator.Init(p); //密钥对 AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair(); //公钥和私钥 AsymmetricKeyParameter publicKey = keyPair.Public; AsymmetricKeyParameter privateKey = keyPair.Private;保存密钥对到文件(我这里用*.key形式保存的,当然也可以用其它的)private static void SavePublicKey(AsymmetricKeyParameter publicKey) { SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); Asn1Object ao = publicKeyInfo.ToAsn1Object(); byte[] publicKeyByte = ao.GetEncoded(); FileStream fs = new FileStream(@"D:\public.key", FileMode.Create, FileAccess.Write); fs.Write(publicKeyByte, 0, publicKeyByte.Length); fs.Close(); }private static void SavePrivateKey(AsymmetricKeyParameter privateKey) { PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey); Asn1Object ao = privateKeyInfo.ToAsn1Object(); byte[] privateKeyByte = ao.GetEncoded(); FileStream fs = new FileStream(@"D:\private.key", FileMode.Create, FileAccess.Write); fs.Write(privateKeyByte, 0, privateKeyByte.Length); fs.Close(); }
软件注册基本结构: 自己拥有私密:privatekey 客户拥有公密:publicKey 1:客户端生成序列号 2:客户把序列号告诉私密拥有者 3:私密拥有者用私钥加密信息(时间,版本,或者什么的) 4:加密后的信息给客户,客户在软件操作,验证 1,2步骤不用说了,很简单 直接3,4步骤 私密加密 按 Ctrl+C 复制代码
按 Ctrl+C 复制代码
公密解密 [url=][/url]
1 byte[] data = ConvertHexStringToBytes(tempEnString);2 IAsymmetricBlockCipher engine = new RsaEngine();3 Asn1Object aobject = Asn1Object.FromStream(new FileStream(@"D:\public.key", FileMode.Open, FileAccess.Read)); //a.puk??4 SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.GetInstance(aobject);5 AsymmetricKeyParameter publicKey = (RsaKeyParameters)PublicKeyFactory.CreateKey(pubInfo);6 engine.Init(false, publicKey);7 engine.GetInputBlockSize();8 byte[] deData = engine.ProcessBlock(data, 0, data.Length);9 string tempString = byteToHexStr(deData);[url=][/url]
帮助类 [url=][/url]
private string byteToHexStr(byte[] bytes) { string returnStr = ""; if (bytes != null) { for (int i = 0; i < bytes.Length; i++) { returnStr += bytes.ToString("X2"); } } return returnStr; } public byte[] ConvertHexStringToBytes(string hexString) { int len = hexString.Length / 2; byte[] bytes = new byte[len]; for (int i = 0; i < len; i++) { bytes = Convert.ToByte(hexString.Substring(i * 2, 2), 16); } return bytes; } public string ConvertBytesToHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(); foreach (byte b in bytes) { sb.Append(string.Format("{0:X2}", b).PadLeft(2, '0')); } return sb.ToString(); }[url=][/url]
|