示例#1
0
        public static string Encrypt(RsaKeyFormat rsaKeyFormat, string publicKey, string data)
        {
            KeyWorker _keyWorker;

            switch (rsaKeyFormat)
            {
                case RsaKeyFormat.XML:
                    _keyWorker = new KeyWorker(publicKey, KeyFormat.XML);
                    break;
                case RsaKeyFormat.ASN:
                    _keyWorker = new KeyWorker(publicKey, KeyFormat.ASN);
                    break;
                case RsaKeyFormat.PEM:
                    _keyWorker = new KeyWorker(publicKey, KeyFormat.PEM);
                    break;
                default:
                    throw new Exception(string.Format("the rsa key format: {0} is not supported.", rsaKeyFormat));
            }

            return _keyWorker.Encrypt(data);
        }
示例#2
0
        private static void Test(int keySize = 2048)
        {
            //const int keySize = 2048;
            Console.WriteLine("=========================== 密钥长度{0} ===========================", keySize);

            //生成公私钥对
            KeyPair keyPair = KeyGenerator.GenerateKeyPair(KeyFormat.XML, keySize);

            //转换成不同的格式
            KeyPair asnKeyPair = keyPair.ToASNKeyPair();
            KeyPair xmlKeyPair = asnKeyPair.ToXMLKeyPair();
            KeyPair pemKeyPair = xmlKeyPair.ToPEMKeyPair();

            //获取公私钥
            string privateKey = xmlKeyPair.PrivateKey;
            string publicKey = xmlKeyPair.PublicKey;

            //加解密
            KeyWorker privateWorker = new KeyWorker(privateKey, KeyFormat.XML);
            KeyWorker publicWorker = new KeyWorker(publicKey, KeyFormat.XML);

            //XML
            Console.WriteLine(privateWorker.Decrypt(publicWorker.Encrypt("你好!世界")));
            Console.WriteLine(publicWorker.Decrypt(privateWorker.Encrypt("你好!中国")));

            //ASN
            privateWorker = new KeyWorker(asnKeyPair.PrivateKey, KeyFormat.ASN);
            publicWorker = new KeyWorker(asnKeyPair.PublicKey, KeyFormat.ASN);
            Console.WriteLine(privateWorker.Decrypt(publicWorker.Encrypt("你好!世界")));
            Console.WriteLine(publicWorker.Decrypt(privateWorker.Encrypt("你好!中国")));

            //PEM
            privateWorker = new KeyWorker(pemKeyPair.PrivateKey, KeyFormat.PEM);
            publicWorker = new KeyWorker(pemKeyPair.PublicKey, KeyFormat.PEM);
            Console.WriteLine(privateWorker.Decrypt(publicWorker.Encrypt("你好!世界")));
            Console.WriteLine(publicWorker.Decrypt(privateWorker.Encrypt("你好!中国")));
        }