privateKeyDecode function Null safety
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;
}
}
if (str.startsWith(PuttyPrivateKey.puttyKeyTypeTag, p)) {
final ppk = PuttyPrivateKey.decode(str, offset: p);
switch (ppk.keyType) {
case 'ssh-rsa':
break;
default:
throw KeyUnsupported('unsupported algorithm: ${ppk.keyType}');
}
return _rsaPrivateFromPPK(
ppk.publicKeyBytes, ppk.privateKeyBytes, ppk.comment, ppk.source);
// TODO
} else if (str.startsWith('---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----')) {
throw KeyUnsupported('SSH.com keys not implemented yet');
} else {
// Try Textual Encoding
final block =
TextualEncoding.decode(str, offset: p, allowPreamble: allowPreamble);
if (block.label == 'OPENSSH PRIVATE KEY') {
// OpenSSH Private Key (i.e. the new OpenSSH format)
// Data is ... TODO
final ospk = OpenSshPrivateKey.decode(block.data,
source:
PvtTextSource.setEncoding(block.source!, PvtKeyEncoding.openSsh));
// TODO: use private key format!!!
switch (ospk.privateKeyType) {
case 'ssh-rsa':
return _rsaPrivateFromOpenSSH(
ospk.publicKeyBytes, ospk.privateKeyBytes, ospk.source);
default:
throw KeyUnsupported('unsupported algorithm: ${ospk.privateKeyType}');
}
} else if (block.label == 'RSA PRIVATE KEY') {
// PKCS #1 Private Key (i.e. the original OpenSSH format)
//print(_hexDump(block.data, name: 'PKCS #1 Private Key data'));
print('PKCS #1 data length: ${block.data.length}');
throw KeyUnsupported('Decoding PKCS #1 Private Key not implemented yet');
} else {
throw KeyUnsupported('unsupported label: ${block.label}');
}
}
}