public static string GetComment(IEnumerable<string> publicKeyFileLines, string defaultValue = null)
{
const string rfc4716BeginMarker = "---- BEGIN SSH2 PUBLIC KEY ----";
const string rfc4716CommentHeader = "Comment: ";
const string openSshPublicKeyStart = "ssh-";
string comment = null;
if (publicKeyFileLines == null)
throw new ArgumentNullException("publicKeyFileLines");
var firstLine = publicKeyFileLines.FirstOrDefault();
if (firstLine != null) {
if (firstLine == rfc4716BeginMarker) {
var commentFound = false;
foreach (var line in publicKeyFileLines) {
if (commentFound) {
comment += line;
} else if (line.StartsWith(rfc4716CommentHeader)) {
commentFound = true;
comment = line.Substring(rfc4716CommentHeader.Length);
}
if (!commentFound)
continue;
if (comment.EndsWith("\\")) {
comment = comment.Substring(0, comment.Length - 1);
continue;
}
}
if (comment == null)
return defaultValue;
if (comment.StartsWith("\"") && comment.EndsWith("\"")) {
comment = comment.Substring(1, comment.Length - 2);
}
return comment;
} else if (firstLine.StartsWith(openSshPublicKeyStart)) {
var item = firstLine.Split(new char[] { ' ' }, 3);
if (item.Length == 3)
return item[2];
}
}
return defaultValue;
}