private void LoadKeyFromXml(string path, RsaKeyType rsaKeyType) { if (!File.Exists(path)) throw new FileNotFoundException("File not exists: " + path); // Using the .NET RSA class to load a key from an Xml file, and populating the relevant members // of my class with it's RSAParameters try { _rsaCryptosystem.FromXmlString(File.ReadAllText(path)); RSAParameters rsaParams = _rsaCryptosystem.ExportParameters(rsaKeyType == RsaKeyType.Private); if (rsaKeyType == RsaKeyType.Private) { _d = new BigInteger(rsaParams.D); // This parameter is only for private key' _isPrivateKeyLoaded = true; } else { _isPublicKeyLoaded = true; } _modulus = new BigInteger(rsaParams.Modulus); _exponent = new BigInteger(rsaParams.Exponent); } // Examle for the proper use of try - catch blocks: Informing the main app where and why the Exception occurred catch (XmlSyntaxException ex) // Not an xml file { string excReason = "Exception occurred at LoadKeyFromXml(), Selected file is not a valid xml file."; Debug.WriteLine(excReason + " Exception Message: " + ex.Message); throw new Exception(excReason, ex); } catch (CryptographicException ex) // Not a Key file { string excReason = "Exception occurred at LoadKeyFromXml(), Selected xml file is not a public key file."; Debug.WriteLine(excReason + " Exception Message: " + ex.Message); throw new Exception(excReason, ex); } catch (Exception ex) // other exception, hope the ex.message will help { string excReason = "General Exception occurred at LoadKeyFromXml()."; Debug.WriteLine(excReason + " Exception Message: " + ex.Message); throw new Exception(excReason, ex); } }
/// <summary> /// 生成RSA密钥对 /// </summary> /// <param name="keyType"></param> /// <param name="keySize"></param> /// <returns></returns> public static RsaKeyPair GenerateKeyPair(RsaKeyType keyType, int keySize) { return(Rsa.GenerateKeyPair(keyType, keySize)); }
/// <summary> /// 生成rsa秘钥 /// </summary> /// <param name="rsaKeyType">密钥类型</param> /// <param name="length">密钥长度</param> /// <returns></returns> public RsaKey GenerateRsaKeys(RsaKeyType rsaKeyType = RsaKeyType.XML, int length = 1024) { return(RsaCrypt.GenerateRsaKeys(rsaKeyType, length)); }