예제 #1
0
        /// <summary>
        /// Creates a X509-formatted public key string from a given RSA key pair.
        /// </summary>
        public static string GetPublicKeyFormattedString(RSA keyPair)
        {
            if (keyPair == null)
            {
                return(string.Empty);
            }

            var publicKey      = keyPair.ExportParameters(false);
            var publicKeyBytes = RsaKeyUtils.PublicKeyToX509(publicKey);

            return(string.Format(FORMAT_PUBLIC_KEY, Convert.ToBase64String(publicKeyBytes)));
        }
예제 #2
0
        /// <summary>
        /// Creates a public-key-only RSA key pair from X509-formatted public key string.
        /// </summary>
        public static RSA CreatePublicKeyFromPublicKeyFormattedString(string publicKeyString)
        {
            if (string.IsNullOrWhiteSpace(publicKeyString))
            {
                return(null);
            }

            var publicKeyStringTrimmed = publicKeyString
                                         .Replace(PUBLIC_KEY_START, string.Empty)
                                         .Replace(PUBLIC_KEY_END, string.Empty);

            return(RsaKeyUtils.DecodePublicKey(Convert.FromBase64String(publicKeyStringTrimmed)));
        }
예제 #3
0
        /// <summary>
        /// Creates an RSA key pair from PKCS8-formatted private key string.
        /// </summary>
        public static RSA CreateKeyPairFromPrivateKeyFormattedString(string privateKeyString)
        {
            if (string.IsNullOrWhiteSpace(privateKeyString))
            {
                return(null);
            }

            var privateKeyStringTrimmed = privateKeyString
                                          .Replace(PRIVATE_KEY_START, string.Empty)
                                          .Replace(PRIVATE_KEY_END, string.Empty);

            return(RsaKeyUtils.DecodePrivateKeyInfo(Convert.FromBase64String(privateKeyStringTrimmed)));
        }
예제 #4
0
        /// <summary>
        /// If possible, creates a PKCS8-formatted private key string from a given RSA key pair; else returns an empty
        /// string.
        /// </summary>
        public static string GetPrivateKeyFormattedString(RSA keyPair)
        {
            if (keyPair == null)
            {
                return(string.Empty);
            }

            try
            {
                var privateKey      = keyPair.ExportParameters(true);
                var privateKeyBytes = RsaKeyUtils.PrivateKeyToPkcs8(privateKey);

                return(string.Format(FORMAT_PRIVATE_KEY, Convert.ToBase64String(privateKeyBytes)));
            }
            catch (SecurityException)
            {
                return(string.Empty);
            }
        }