2 * Read SSH public keys from files.
4 * First implementation: only supports unencrypted SSH 1.1 format
5 * RSA keys. Encryption, and SSH 2 DSS keys, to be supported later.
10 #include <stdio.h> /* FIXME */
11 #include <stdarg.h> /* FIXME */
12 #include <windows.h> /* FIXME */
13 #include "putty.h" /* FIXME */
17 #define GET_32BIT(cp) \
18 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
19 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
20 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
21 ((unsigned long)(unsigned char)(cp)[3]))
23 #define rsa_signature "SSH PRIVATE KEY FILE FORMAT 1.1\n"
25 int loadrsakey(char *filename
, struct RSAKey
*key
, char *passphrase
) {
27 unsigned char buf
[16384];
28 unsigned char keybuf
[16];
32 struct MD5Context md5c
;
34 fp
= fopen(filename
, "rb");
38 /* Slurp the whole file into a buffer. */
39 len
= fread(buf
, 1, sizeof(buf
), fp
);
41 if (len
< 0 || len
== sizeof(buf
))
42 goto end
; /* file too big or not read */
44 if (len
< sizeof(rsa_signature
) ||
45 memcmp(buf
, rsa_signature
, sizeof(rsa_signature
)) != 0)
46 goto end
; /* failure to have sig at front */
48 i
= sizeof(rsa_signature
);
50 /* Next, one byte giving encryption type, and one reserved uint32. */
54 if (ciphertype
!= 0 && ciphertype
!= SSH_CIPHER_3DES
)
58 goto end
; /* reserved field not present */
59 if (buf
[i
] != 0 || buf
[i
+1] != 0 || buf
[i
+2] != 0 || buf
[i
+3] != 0)
60 goto end
; /* reserved field nonzero, panic! */
63 /* Now the serious stuff. An ordinary SSH 1 public key. */
64 i
+= makekey(buf
+i
, key
, NULL
, 1);
66 goto end
; /* overran */
68 /* Next, the comment field. */
70 if (len
-i
< 4+j
) goto end
; i
+= 4+j
;
72 * FIXME: might need to use this string.
76 * Decrypt remainder of buffer.
80 MD5Update(&md5c
, passphrase
, strlen(passphrase
));
81 MD5Final(keybuf
, &md5c
);
82 des3_decrypt_pubkey(keybuf
, buf
+i
, (len
-i
+7)&~7);
83 memset(keybuf
, 0, sizeof(buf
)); /* burn the evidence */
87 * We are now in the secret part of the key. The first four
88 * bytes should be of the form a, b, a, b.
90 if (len
-i
< 4) goto end
;
91 if (buf
[i
] != buf
[i
+2] || buf
[i
+1] != buf
[i
+3]) { ret
= -1; goto end
; }
95 * After that, we have one further bignum which is our
96 * decryption modulus, and then we're done.
98 i
+= makeprivate(buf
+i
, key
);
99 if (len
-i
< 0) goto end
;
103 memset(buf
, 0, sizeof(buf
)); /* burn the evidence */
108 * See whether an RSA key is encrypted.
110 int rsakey_encrypted(char *filename
) {
112 unsigned char buf
[1+sizeof(rsa_signature
)];
115 fp
= fopen(filename
, "rb");
117 return 0; /* doesn't even exist */
119 /* Slurp the whole file into a buffer. */
120 len
= fread(buf
, 1, sizeof(buf
), fp
);
122 if (len
< sizeof(buf
))
123 return 0; /* not even valid */
124 if (buf
[sizeof(buf
)-1])
125 return 1; /* encrypted */