aboutsummaryrefslogtreecommitdiffstats
path: root/lib/public_key/src/pubkey_pem.erl
blob: d7e5bc3ad8b650594f27c0e40261debb8f0cac25 (plain) (blame)
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2008-2018. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%%     http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%

%%

%%% Description: Reading and writing of PEM type encoded files.
%% PEM encoded files have the following structure:
%%
%%	<text>
%%	-----BEGIN SOMETHING-----<CR><LF>
%%	<Base64 encoding line><CR><LF>
%%	<Base64 encoding line><CR><LF>
%%	...
%%	-----END SOMETHING-----<CR><LF>
%%	<text>
%%
%% A file can contain several BEGIN/END blocks. Text lines between
%% blocks are ignored.
%%
%% The encoding is divided into lines separated by <NL>, and each line
%% is precisely 64 characters long (excluding the <NL> characters,
%% except the last line which 64 characters long or shorter. <NL> may
%% follow the last line.

-module(pubkey_pem).

-include("public_key.hrl").

-export([encode/1, decode/1, decipher/2, cipher/3]).

-define(ENCODED_LINE_LENGTH, 64).

%%====================================================================
%% Internal application API
%%====================================================================

%%--------------------------------------------------------------------
-spec decode(binary()) -> [public_key:pem_entry()].
%%
%% Description: Decodes a PEM binary.
%%--------------------------------------------------------------------		    
decode(Bin) ->
    decode_pem_entries(split_bin(Bin), []).

%%--------------------------------------------------------------------
-spec encode([public_key:pem_entry()]) -> iolist().
%%
%% Description: Encodes a list of PEM entries.
%%--------------------------------------------------------------------		    
encode(PemEntries) ->
    encode_pem_entries(PemEntries).

%%--------------------------------------------------------------------
-spec decipher({public_key:pki_asn1_type(), DerEncrypted::binary(),
		{Cipher :: string(), Salt :: iodata() | #'PBES2-params'{} 
					   | {#'PBEParameter'{}, atom()}}},
	       string()) -> Der::binary().
%%
%% Description: Deciphers a decrypted pem entry.
%%--------------------------------------------------------------------
decipher({_, DecryptDer, {Cipher, KeyDevParams}}, Password) ->
    pubkey_pbe:decode(DecryptDer, Password, Cipher, KeyDevParams).

%%--------------------------------------------------------------------
-spec cipher(Der::binary(), {Cipher :: string(), Salt :: iodata() | #'PBES2-params'{} 
						       | {#'PBEParameter'{}, atom()}}, 
	     string()) -> binary().
%%
%% Description: Ciphers a PEM entry
%%--------------------------------------------------------------------
cipher(Der, {Cipher, KeyDevParams}, Password)->
    pubkey_pbe:encode(Der, Password, Cipher, KeyDevParams).

%%--------------------------------------------------------------------
%%% Internal functions
%%--------------------------------------------------------------------
encode_pem_entries(Entries) ->
    [encode_pem_entry(Entry) || Entry <- Entries].

encode_pem_entry({Type, Der, not_encrypted}) ->
    StartStr = pem_start(Type),
    [StartStr, "\n", b64encode_and_split(Der), "\n", pem_end(StartStr) ,"\n\n"];
encode_pem_entry({'PrivateKeyInfo', Der, EncParams}) -> 
    EncDer = encode_encrypted_private_keyinfo(Der, EncParams),
    StartStr = pem_start('EncryptedPrivateKeyInfo'),
    [StartStr, "\n", b64encode_and_split(EncDer), "\n", pem_end(StartStr) ,"\n\n"];
encode_pem_entry({Type, Der, {Cipher, Salt}}) ->
    StartStr = pem_start(Type),
    [StartStr,"\n", pem_decrypt(),"\n", pem_decrypt_info(Cipher, Salt),"\n\n",
     b64encode_and_split(Der), "\n", pem_end(StartStr) ,"\n\n"].

decode_pem_entries([], Entries) ->
    lists:reverse(Entries);
decode_pem_entries([<<>>], Entries) ->
   lists:reverse(Entries);
decode_pem_entries([<<>> | Lines], Entries) ->
    decode_pem_entries(Lines, Entries);
decode_pem_entries([Start| Lines], Entries) ->
    case pem_end(Start) of
	undefined ->
	    decode_pem_entries(Lines, Entries);
	_End ->
	    {Entry, RestLines} = join_entry(Lines, []),
	    decode_pem_entries(RestLines, [decode_pem_entry(Start, Entry) | Entries])
    end.

decode_pem_entry(Start, [<<"Proc-Type: 4,ENCRYPTED", _/binary>>, Line | Lines]) ->
    Type = asn1_type(Start),
    Cs = erlang:iolist_to_binary(Lines),
    Decoded = base64:mime_decode(Cs),
    [_, DekInfo0] = string:tokens(binary_to_list(Line), ": "),
    [Cipher, Salt] = string:tokens(DekInfo0, ","), 
    {Type, Decoded, {Cipher, unhex(Salt)}};
decode_pem_entry(Start, Lines) ->
    Type = asn1_type(Start),
    Cs = erlang:iolist_to_binary(Lines),
    Decoded = base64:mime_decode(Cs),
    case Type of
	'EncryptedPrivateKeyInfo'->
	    decode_encrypted_private_keyinfo(Decoded);
	_ ->
	    {Type, Decoded, not_encrypted}
    end.

decode_encrypted_private_keyinfo(Der) ->
    #'EncryptedPrivateKeyInfo'{encryptionAlgorithm = AlgorithmInfo,				  
			       encryptedData = Data} = 
	public_key:der_decode('EncryptedPrivateKeyInfo', Der),
    DecryptParams = pubkey_pbe:decrypt_parameters(AlgorithmInfo), 
    {'PrivateKeyInfo', Data, DecryptParams}.

encode_encrypted_private_keyinfo(EncData, EncryptParmams) ->
    AlgorithmInfo = pubkey_pbe:encrypt_parameters(EncryptParmams),
    public_key:der_encode('EncryptedPrivateKeyInfo',   
			  #'EncryptedPrivateKeyInfo'{encryptionAlgorithm = AlgorithmInfo,
						     encryptedData = EncData}).
split_bin(Bin) ->
    split_bin(0, Bin).

split_bin(N, Bin) ->
    case Bin of
	<<Line:N/binary, "\r\n", Rest/binary>> ->
	    [Line | split_bin(0, Rest)];
	<<Line:N/binary, "\n", Rest/binary>> ->
	    [Line | split_bin(0, Rest)];
	<<Line:N/binary>> ->
	    [Line];
	_ ->
	    split_bin(N+1, Bin)
    end.

b64encode_and_split(Bin) ->
    split_lines(base64:encode(Bin)).

split_lines(<<Text:?ENCODED_LINE_LENGTH/binary>>) ->
    [Text];
split_lines(<<Text:?ENCODED_LINE_LENGTH/binary, Rest/binary>>) ->
    [Text, $\n | split_lines(Rest)];
split_lines(Bin) ->
    [Bin].

%% Ignore white space at end of line
join_entry([<<"-----END ", _/binary>>| Lines], Entry) ->
    {lists:reverse(Entry), Lines};
join_entry([<<"-----END X509 CRL-----", _/binary>>| Lines], Entry) ->
    {lists:reverse(Entry), Lines};
join_entry([Line | Lines], Entry) ->
    join_entry(Lines, [Line | Entry]).

unhex(S) ->
    unhex(S, []).

unhex("", Acc) ->
    list_to_binary(lists:reverse(Acc));
unhex([D1, D2 | Rest], Acc) ->
    unhex(Rest, [erlang:list_to_integer([D1, D2], 16) | Acc]).

hexify(L) -> [[hex_byte(B)] || B <- binary_to_list(L)].

hex_byte(B) when B < 16#10 -> ["0", erlang:integer_to_list(B, 16)];
hex_byte(B) -> erlang:integer_to_list(B, 16).

pem_start('Certificate') ->
    <<"-----BEGIN CERTIFICATE-----">>;
pem_start('RSAPrivateKey') ->
    <<"-----BEGIN RSA PRIVATE KEY-----">>;
pem_start('RSAPublicKey') ->
    <<"-----BEGIN RSA PUBLIC KEY-----">>;
pem_start('SubjectPublicKeyInfo') ->
    <<"-----BEGIN PUBLIC KEY-----">>;
pem_start('DSAPrivateKey') ->
    <<"-----BEGIN DSA PRIVATE KEY-----">>;
pem_start('DHParameter') ->
    <<"-----BEGIN DH PARAMETERS-----">>;
pem_start('PrivateKeyInfo') ->
    <<"-----BEGIN PRIVATE KEY-----">>;
pem_start('EncryptedPrivateKeyInfo') ->
    <<"-----BEGIN ENCRYPTED PRIVATE KEY-----">>;
pem_start('CertificationRequest') ->
    <<"-----BEGIN CERTIFICATE REQUEST-----">>;
pem_start('ContentInfo') ->
    <<"-----BEGIN PKCS7-----">>;
pem_start('CertificateList') ->
     <<"-----BEGIN X509 CRL-----">>;
pem_start('EcpkParameters') ->
    <<"-----BEGIN EC PARAMETERS-----">>;
pem_start('ECPrivateKey') ->
    <<"-----BEGIN EC PRIVATE KEY-----">>;
pem_start({no_asn1, new_openssh}) ->  %% Temporarily in the prototype of this format
    <<"-----BEGIN OPENSSH PRIVATE KEY-----">>.

pem_end(<<"-----BEGIN CERTIFICATE-----">>) ->
    <<"-----END CERTIFICATE-----">>;
pem_end(<<"-----BEGIN RSA PRIVATE KEY-----">>) ->
    <<"-----END RSA PRIVATE KEY-----">>;
pem_end(<<"-----BEGIN RSA PUBLIC KEY-----">>) ->
    <<"-----END RSA PUBLIC KEY-----">>;
pem_end(<<"-----BEGIN PUBLIC KEY-----">>) ->
    <<"-----END PUBLIC KEY-----">>;
pem_end(<<"-----BEGIN DSA PRIVATE KEY-----">>) ->
    <<"-----END DSA PRIVATE KEY-----">>;
pem_end(<<"-----BEGIN DH PARAMETERS-----">>) ->
    <<"-----END DH PARAMETERS-----">>;
pem_end(<<"-----BEGIN PRIVATE KEY-----">>) ->
    <<"-----END PRIVATE KEY-----">>;
pem_end(<<"-----BEGIN ENCRYPTED PRIVATE KEY-----">>) ->
    <<"-----END ENCRYPTED PRIVATE KEY-----">>;
pem_end(<<"-----BEGIN CERTIFICATE REQUEST-----">>) ->
    <<"-----END CERTIFICATE REQUEST-----">>;
pem_end(<<"-----BEGIN PKCS7-----">>) ->
    <<"-----END PKCS7-----">>;
pem_end(<<"-----BEGIN X509 CRL-----">>) ->
    <<"-----END X509 CRL-----">>;
pem_end(<<"-----BEGIN EC PARAMETERS-----">>) ->
    <<"-----END EC PARAMETERS-----">>;
pem_end(<<"-----BEGIN EC PRIVATE KEY-----">>) ->
    <<"-----END EC PRIVATE KEY-----">>;
pem_end(<<"-----BEGIN OPENSSH PRIVATE KEY-----">>) ->
    <<"-----END OPENSSH PRIVATE KEY-----">>;
pem_end(_) ->
    undefined.

asn1_type(<<"-----BEGIN CERTIFICATE-----">>) ->
    'Certificate';
asn1_type(<<"-----BEGIN RSA PRIVATE KEY-----">>) ->
    'RSAPrivateKey';
asn1_type(<<"-----BEGIN RSA PUBLIC KEY-----">>) ->
    'RSAPublicKey';
asn1_type(<<"-----BEGIN PUBLIC KEY-----">>) ->
    'SubjectPublicKeyInfo';
asn1_type(<<"-----BEGIN DSA PRIVATE KEY-----">>) ->
    'DSAPrivateKey';
asn1_type(<<"-----BEGIN DH PARAMETERS-----">>) ->
    'DHParameter';
asn1_type(<<"-----BEGIN PRIVATE KEY-----">>) ->
    'PrivateKeyInfo';
asn1_type(<<"-----BEGIN ENCRYPTED PRIVATE KEY-----">>) ->
    'EncryptedPrivateKeyInfo';
asn1_type(<<"-----BEGIN CERTIFICATE REQUEST-----">>) ->
    'CertificationRequest';
asn1_type(<<"-----BEGIN PKCS7-----">>) ->
    'ContentInfo';
asn1_type(<<"-----BEGIN X509 CRL-----">>) ->
    'CertificateList';
asn1_type(<<"-----BEGIN EC PARAMETERS-----">>) ->
    'EcpkParameters';
asn1_type(<<"-----BEGIN EC PRIVATE KEY-----">>) ->
    'ECPrivateKey';
asn1_type(<<"-----BEGIN OPENSSH PRIVATE KEY-----">>) ->
    {no_asn1, new_openssh}. %% Temporarily in the prototype of this format


pem_decrypt() ->
    <<"Proc-Type: 4,ENCRYPTED">>.

pem_decrypt_info(Cipher, Salt) ->
    io_lib:format("DEK-Info: ~s,~s", [Cipher, lists:flatten(hexify(Salt))]).