コード例 #1
0
ファイル: KeyHelper.cs プロジェクト: bhbk/fm3na7zy
        /*
         * openssh uses base64 and special formatting for public keys like with "authorized_keys"
         * https://man.openbsd.org/ssh-keygen
         */
        public static StringBuilder ExportPubKeyBase64(tbl_User user, ICollection <tbl_PublicKey> keys)
        {
            var callPath = $"{MethodBase.GetCurrentMethod().DeclaringType.Name}.{MethodBase.GetCurrentMethod().Name}";
            var sb       = new StringBuilder();

            foreach (var key in keys)
            {
                var pubBytes   = Encoding.ASCII.GetBytes(key.KeyValue);
                var pubKeyInfo = new PublicKeyInfo();
                pubKeyInfo.Load(new MemoryStream(pubBytes));

                var pubStream = new MemoryStream();
                var pubKey    = new SshPublicKey(pubKeyInfo);
                pubKey.SavePublicKey(pubStream, SshPublicKeyFormat.Pkcs8);

                var algo = string.Empty;

                switch (pubKey.KeyAlgorithm)
                {
                case SshHostKeyAlgorithm.DSS:
                    algo = "ssh-dsa";
                    break;

                case SshHostKeyAlgorithm.RSA:
                    algo = "ssh-rsa";
                    break;

                //case SshHostKeyAlgorithm.ECDsaNistP256:
                //	algo = "ecdsa-sha2-nistp256";
                //	break;

                //case SshHostKeyAlgorithm.ECDsaNistP384:
                //	algo = "ecdsa-sha2-nistp384";
                //	break;

                //case SshHostKeyAlgorithm.ECDsaNistP521:
                //	algo = "ecdsa-sha2-nistp521";
                //	break;

                //case SshHostKeyAlgorithm.ED25519:
                //	algo = "ssh-ed25519";
                //	break;

                default:
                {
                    Log.Warning($"'{callPath}' '{user.IdentityAlias}' algorithm {pubKey.KeyAlgorithm} not supported");
                    continue;
                }
                }

                sb.AppendLine($"{algo} {Convert.ToBase64String(pubKey.GetPublicKey())} {key.Comment}");
            }

            return(sb);
        }