软件注册码随笔
用到的是: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客户拥有公密:publicKey1:客户端生成序列号2:客户把序列号告诉私密拥有者3:私密拥有者用私钥加密信息(时间,版本,或者什么的)4:加密后的信息给客户,客户在软件操作,验证1,2步骤不用说了,很简单直接3,4步骤私密加密按 Ctrl+C 复制代码
按 Ctrl+C 复制代码
公密解密http://common.cnblogs.com/images/copycode.gif
1byte[] 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);http://common.cnblogs.com/images/copycode.gif
帮助类http://common.cnblogs.com/images/copycode.gif
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; 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(); }http://common.cnblogs.com/images/copycode.gif
页:
[1]