1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
|
/*
* Example of reading SSH2 format public keys (see RFC 4716)
*/
#include <fstream>
#include <botan/x509_key.h>
#include <botan/filters.h>
#include <botan/rsa.h>
#include <botan/dsa.h>
using namespace Botan;
inline u32bit make_u32bit(byte i0, byte i1, byte i2, byte i3)
{
return ((static_cast<u32bit>(i0) << 24) |
(static_cast<u32bit>(i1) << 16) |
(static_cast<u32bit>(i2) << 8) |
(static_cast<u32bit>(i3)));
}
u32bit read_u32bit(Pipe& pipe)
{
byte sz[4] = { 0 };
pipe.read(sz, 4);
u32bit len = make_u32bit(sz[0], sz[1], sz[2], sz[3]);
if(len > 10000)
throw Decoding_Error("Huge size in read_u32bit, something went wrong");
return len;
}
std::string read_string(Pipe& pipe)
{
u32bit len = read_u32bit(pipe);
std::string out(len, 'X');
pipe.read(reinterpret_cast<byte*>(&out[0]), len);
return out;
}
BigInt read_bigint(Pipe& pipe)
{
u32bit len = read_u32bit(pipe);
SecureVector<byte> buf(len);
pipe.read(&buf[0], len);
return BigInt::decode(buf);
}
Public_Key* read_ssh_pubkey(const std::string& file)
{
std::ifstream in(file.c_str());
const std::string ssh_header = "---- BEGIN SSH2 PUBLIC KEY ----";
const std::string ssh_trailer = "---- END SSH2 PUBLIC KEY ----";
std::string hex_bits;
std::string line;
std::getline(in, line);
if(line != ssh_header)
return 0;
while(in.good())
{
std::getline(in, line);
if(line.find("Comment: ") == 0)
{
while(line[line.size()-1] == '\\')
std::getline(in, line);
std::getline(in, line);
}
if(line == ssh_trailer)
break;
hex_bits += line;
}
Pipe pipe(new Base64_Decoder);
pipe.process_msg(hex_bits);
std::string key_type = read_string(pipe);
if(key_type != "ssh-rsa" && key_type != "ssh-dss")
return 0;
if(key_type == "ssh-rsa")
{
BigInt e = read_bigint(pipe);
BigInt n = read_bigint(pipe);
return new RSA_PublicKey(n, e);
}
else if(key_type == "ssh-dss")
{
BigInt p = read_bigint(pipe);
BigInt q = read_bigint(pipe);
BigInt g = read_bigint(pipe);
BigInt y = read_bigint(pipe);
return new DSA_PublicKey(DL_Group(p, q, g), y);
}
return 0;
}
#include <botan/init.h>
#include <iostream>
int main()
{
LibraryInitializer init;
Public_Key* key = read_ssh_pubkey("dsa.ssh");
if(key == 0)
{
std::cout << "Failed\n";
return 1;
}
std::cout << X509::PEM_encode(*key);
return 0;
}
|