privateKeyDecode function
PrivateKey
privateKeyDecode(})
Decodes the first private key from text.
Whitespace before the private key is ignored. By default, any non-whitespace
preamble before the key is not allowed. To ignore non-whitespace preamble,
set allowPreamble
to true. Note: not all formats allow preamble.
Result
Returns first private key in str
, starting at offset
(or the
beginning of the string if no offset is provided).
The text before and after the private key can be identified by examining the source member in the result (after casting it into its actual type).
Exceptions
A KeyMissing is thrown if no private key is found.
A KeyBad is thrown if the private key is invalid.
A KeyUnsupported is thrown if the type of private key is not supported.
Implementation
pointy_castle.PrivateKey privateKeyDecode(String str,
{int offset = 0, bool allowPreamble = false, String passphrase = ''}) {
var p = offset;
// Skip leading whitespace
while (p < str.length) {
final ch = str[p];
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') {
p++;
} else {
break;
}
}
// Try the formats that uses the RFC 7468 Textual Encoding
TextualEncoding? teBlock;
try {
teBlock =
TextualEncoding.decode(str, offset: p, allowPreamble: allowPreamble);
} catch (e) {
// Not RFC 7468 Textual Encoding: leave teBlock null
}
if (teBlock != null) {
// Is encoded using RFC 7468 Textual Encoding
if (teBlock.label == 'OPENSSH PRIVATE KEY') {
// Starts with: -----BEGIN OPENSSH PRIVATE KEY-----
return _privateKeyDecodeOpenSSH(teBlock, p); // new OpenSSH format
} else if (teBlock.label == _rsaPrivatePkcs1label) {
// Starts with: -----BEGIN RSA PRIVATE KEY-----
// Unencrypted old OpenSSH format (also known as PKCS#1).
return _privateKeyDecodePkcs1(teBlock, p);
} else if (teBlock.label == 'PRIVATE KEY') {
// Starts with: -----BEGIN PRIVATE KEY-----
// PKCS#8.
throw KeyUnsupported('PKCS#8 private key not yet implemented');
} else {
throw KeyUnsupported(
'unsupported label for a private key: ${teBlock.label}');
}
}
// Try formats that are not RFC 7468 Textual Encoding
if (str.startsWith('-----BEGIN $_rsaPrivatePkcs1label-----')) {
// Starts with: -----BEGIN RSA PRIVATE KEY-----
// Encrypted old OpenSSH format (also known as PKCS#1).
throw KeyUnsupported('Encrypted RSA private key not implemented yet');
} else if (str.startsWith(PuttyPrivateKey.puttyKeyTypeTag, p)) {
// Starts with: PuTTY-User-Key-File-2
// PuTTY Private Key
return _privateKeyDecodePutty(str, p);
} else if (str.startsWith('---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----')) {
// Starts with: ---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----
// Proprietary format by SSH.com's implementation of SSH
throw KeyUnsupported('SSH.com keys not implemented yet');
}
// Finally, give up
throw KeyMissing('no private key found');
}