Faced with this question, Microsoft answered the way they are accustomed to: with a Microsoft-specific extension. They defined the User Principal Name, which is actually an
OtherName element, the UPN being identified by a Microsoft OID (18.104.22.168.4.1.322.214.171.124) and encoded as an
UTF8String (as succinctly specified there). The format of the string mimics that of an email address, in that it consists in an account name and a domain name, joined together with an '@' character.
It is noteworthy that though the UPN looks like an email address, it is not meant to be used for sending emails; and, correspondingly, Microsoft did not use a
rfc822name element, because such a name conveys email-based semantics (in particular when the certificate is used with S/MIME) that UPN are not supposed to embody.
The "X.509 way" to encode a name in a certificate, whose format does not match the predefined categories, is to do it along the same lines Microsoft did: use
otherName, with an OID of your own, and define your own syntax. Of course, such a name will be usable only by your own software... Although you may decide to reuse the Microsoft UPN format, and thus (possibly) gain some compatibility with Microsoft software (the UPN's goal is to map a certificate onto an Active Directory account).
The really important thing is to determine which software systems will have to deal with your "username". It is useless to encode a username in a certificate if the systems which must decode that username don't know how to do it. For instance, suppose that the username must be used by an Apache-powered Web site, the client certificate being presented at the SSL level. The documentation, in particular the
SSLUserName configuration directive, shows us that Apache may be set to use some specific certificate fields as "username", among the exhaustive list of environment variables maintained by the SSL module. If you are in that situation, then you will have to put your "username" in one of these fields, not in some
otherName with a syntax of your own.
From looking at these fields, I'd say that your best bet would be "UID". That's one of the components of a Distinguished Name, specified in RFC 4519 under OID 0.9.2342.19200300.100.1.1. It is basically a free-form string, and Apache's
mod_ssl knows how to extract it and turn it into a username with:
As a part of a DN, this would go in the
subjectDN field directly, not into a Subject Alt Name extension. (This raises the question of why Microsoft did not use that "UID" field for their UPN; my guess is that they wanted at some point to use the complete
subjectDN as a path in some LDAP directory, and thus could not add extra fields at will in the DN.)