/// <summary>获取指定Key,默认实现从SecurityKey解析</summary> /// <param name="name"></param> /// <returns></returns> public virtual String GetKey(String name) { var key = SecurityKey; if (key.IsNullOrEmpty()) { var file = "..\\Keys\\SsoSecurity.prvkey".GetFullPath(); if (File.Exists(file)) { key = File.ReadAllText(file); } if (key.IsNullOrEmpty()) { file.EnsureDirectory(true); var ks = RSAHelper.GenerateParameters(); File.WriteAllText(file, ks[0]); File.WriteAllText(file.TrimEnd(".prvkey") + ".pubkey", ks[1]); key = ks[0]; } } if (key.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(SecurityKey), $"无法找到名为[{name}]的密钥"); } var name2 = ""; var p = key.IndexOf('$'); if (p >= 0) { name2 = key.Substring(0, p); key = key.Substring(p + 1); } if (!name.IsNullOrEmpty() && !name2.IsNullOrEmpty() && !name.EqualIgnoreCase(name2)) { throw new ArgumentOutOfRangeException(nameof(SecurityKey), $"无法找到名为[{name}]的密钥"); } return(key); }
public void TestBase64Key() { //var rsa = new RSACryptoServiceProvider(2048); //var prvKey = RSAHelper.WriteParameters(rsa.ExportParameters(true)); //var pubKey = RSAHelper.WriteParameters(rsa.ExportParameters(false)); var ss = RSAHelper.GenerateParameters(1024); var prvKey = ss[0]; var pubKey = ss[1]; Assert.NotEmpty(prvKey); Assert.NotEmpty(pubKey); var str = "Stone@NewLife"; var txt = RSAHelper.Encrypt(str.GetBytes(), pubKey).ToBase64(); Assert.NotEmpty(txt); var rs = RSAHelper.Decrypt(txt.ToBase64(), prvKey).ToStr(); Assert.NotEmpty(rs); Assert.Equal(str, rs); }