]> begriffs open source - ai-pg/blob - full-docs/txt/pgcrypto.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / pgcrypto.txt
1
2 F.26. pgcrypto — cryptographic functions #
3
4    F.26.1. General Hashing Functions
5    F.26.2. Password Hashing Functions
6    F.26.3. PGP Encryption Functions
7    F.26.4. Raw Encryption Functions
8    F.26.5. Random-Data Functions
9    F.26.6. OpenSSL Support Functions
10    F.26.7. Configuration Parameters
11    F.26.8. Notes
12    F.26.9. Author
13
14    The pgcrypto module provides cryptographic functions for PostgreSQL.
15
16    This module is considered “trusted”, that is, it can be installed by
17    non-superusers who have CREATE privilege on the current database.
18
19    pgcrypto requires OpenSSL and won't be installed if OpenSSL support was
20    not selected when PostgreSQL was built.
21
22 F.26.1. General Hashing Functions #
23
24 F.26.1.1. digest() #
25
26 digest(data text, type text) returns bytea
27 digest(data bytea, type text) returns bytea
28
29    Computes a binary hash of the given data. type is the algorithm to use.
30    Standard algorithms are md5, sha1, sha224, sha256, sha384 and sha512.
31    Moreover, any digest algorithm OpenSSL supports is automatically picked
32    up.
33
34    If you want the digest as a hexadecimal string, use encode() on the
35    result. For example:
36 CREATE OR REPLACE FUNCTION sha1(bytea) returns text AS $$
37     SELECT encode(digest($1, 'sha1'), 'hex')
38 $$ LANGUAGE SQL STRICT IMMUTABLE;
39
40 F.26.1.2. hmac() #
41
42 hmac(data text, key text, type text) returns bytea
43 hmac(data bytea, key bytea, type text) returns bytea
44
45    Calculates hashed MAC for data with key key. type is the same as in
46    digest().
47
48    This is similar to digest() but the hash can only be recalculated
49    knowing the key. This prevents the scenario of someone altering data
50    and also changing the hash to match.
51
52    If the key is larger than the hash block size it will first be hashed
53    and the result will be used as key.
54
55 F.26.2. Password Hashing Functions #
56
57    The functions crypt() and gen_salt() are specifically designed for
58    hashing passwords. crypt() does the hashing and gen_salt() prepares
59    algorithm parameters for it.
60
61    The algorithms in crypt() differ from the usual MD5 or SHA-1 hashing
62    algorithms in the following respects:
63     1. They are slow. As the amount of data is so small, this is the only
64        way to make brute-forcing passwords hard.
65     2. They use a random value, called the salt, so that users having the
66        same password will have different encrypted passwords. This is also
67        an additional defense against reversing the algorithm.
68     3. They include the algorithm type in the result, so passwords hashed
69        with different algorithms can co-exist.
70     4. Some of them are adaptive — that means when computers get faster,
71        you can tune the algorithm to be slower, without introducing
72        incompatibility with existing passwords.
73
74    Table F.18 lists the algorithms supported by the crypt() function.
75
76    Table F.18. Supported Algorithms for crypt()
77    Algorithm Max Password Length Adaptive? Salt Bits Output Length
78    Description
79    bf 72 yes 128 60 Blowfish-based, variant 2a
80    md5 unlimited no 48 34 MD5-based crypt
81    xdes 8 yes 24 20 Extended DES
82    des 8 no 12 13 Original UNIX crypt
83    sha256crypt unlimited yes up to 32 80 Adapted from publicly available
84    reference implementation Unix crypt using SHA-256 and SHA-512
85    sha512crypt unlimited yes up to 32 123 Adapted from publicly available
86    reference implementation Unix crypt using SHA-256 and SHA-512
87
88 F.26.2.1. crypt() #
89
90 crypt(password text, salt text) returns text
91
92    Calculates a crypt(3)-style hash of password. When storing a new
93    password, you need to use gen_salt() to generate a new salt value. To
94    check a password, pass the stored hash value as salt, and test whether
95    the result matches the stored value.
96
97    Example of setting a new password:
98 UPDATE ... SET pswhash = crypt('new password', gen_salt('md5'));
99
100    Example of authentication:
101 SELECT (pswhash = crypt('entered password', pswhash)) AS pswmatch FROM ... ;
102
103    This returns true if the entered password is correct.
104
105 F.26.2.2. gen_salt() #
106
107 gen_salt(type text [, iter_count integer ]) returns text
108
109    Generates a new random salt string for use in crypt(). The salt string
110    also tells crypt() which algorithm to use.
111
112    The type parameter specifies the hashing algorithm. The accepted types
113    are: des, xdes, md5, bf, sha256crypt and sha512crypt. The last two,
114    sha256crypt and sha512crypt are modern SHA-2 based password hashes.
115
116    The iter_count parameter lets the user specify the iteration count, for
117    algorithms that have one. The higher the count, the more time it takes
118    to hash the password and therefore the more time to break it. Although
119    with too high a count the time to calculate a hash may be several years
120    — which is somewhat impractical. If the iter_count parameter is
121    omitted, the default iteration count is used. Allowed values for
122    iter_count depend on the algorithm and are shown in Table F.19.
123
124    Table F.19. Iteration Counts for crypt()
125           Algorithm         Default Min     Max
126    xdes                     725     1    16777215
127    bf                       6       4    31
128    sha256crypt, sha512crypt 5000    1000 999999999
129
130    For xdes there is an additional limitation that the iteration count
131    must be an odd number.
132
133    To pick an appropriate iteration count, consider that the original DES
134    crypt was designed to have the speed of 4 hashes per second on the
135    hardware of that time. Slower than 4 hashes per second would probably
136    dampen usability. Faster than 100 hashes per second is probably too
137    fast.
138
139    Table F.20 gives an overview of the relative slowness of different
140    hashing algorithms. The table shows how much time it would take to try
141    all combinations of characters in an 8-character password, assuming
142    that the password contains either only lower case letters, or upper-
143    and lower-case letters and numbers. In the crypt-bf entries, the number
144    after a slash is the iter_count parameter of gen_salt.
145
146    The default iter_count for sha256crypt and sha512crypt of 5000 is
147    considered too low for modern hardware, but can be adjusted to generate
148    stronger password hashes. Otherwise both hashes, sha256crypt and
149    sha512crypt are considered safe.
150
151    Table F.20. Hash Algorithm Speeds
152    Algorithm Hashes/sec For [a-z] For [A-Za-z0-9] Duration relative to md5
153    hash
154    crypt-bf/8 1792 4 years 3927 years 100k
155    crypt-bf/7 3648 2 years 1929 years 50k
156    crypt-bf/6 7168 1 year 982 years 25k
157    crypt-bf/5 13504 188 days 521 years 12.5k
158    crypt-md5 171584 15 days 41 years 1k
159    crypt-des 23221568 157.5 minutes 108 days 7
160    sha1 37774272 90 minutes 68 days 4
161    md5 (hash) 150085504 22.5 minutes 17 days 1
162
163    Notes:
164      * The machine used is an Intel Mobile Core i3.
165      * crypt-des and crypt-md5 algorithm numbers are taken from John the
166        Ripper v1.6.38 -test output.
167      * md5 hash numbers are from mdcrack 1.2.
168      * sha1 numbers are from lcrack-20031130-beta.
169      * crypt-bf numbers are taken using a simple program that loops over
170        1000 8-character passwords. That way the speed with different
171        numbers of iterations can be shown. For reference: john -test shows
172        13506 loops/sec for crypt-bf/5. (The very small difference in
173        results is in accordance with the fact that the crypt-bf
174        implementation in pgcrypto is the same one used in John the
175        Ripper.)
176
177    Note that “try all combinations” is not a realistic exercise. Usually
178    password cracking is done with the help of dictionaries, which contain
179    both regular words and various mutations of them. So, even somewhat
180    word-like passwords could be cracked much faster than the above numbers
181    suggest, while a 6-character non-word-like password may escape
182    cracking. Or not.
183
184 F.26.3. PGP Encryption Functions #
185
186    The functions here implement the encryption part of the OpenPGP (RFC
187    4880) standard. Supported are both symmetric-key and public-key
188    encryption.
189
190    An encrypted PGP message consists of 2 parts, or packets:
191      * Packet containing a session key — either symmetric-key or
192        public-key encrypted.
193      * Packet containing data encrypted with the session key.
194
195    When encrypting with a symmetric key (i.e., a password):
196     1. The given password is hashed using a String2Key (S2K) algorithm.
197        This is rather similar to crypt() algorithms — purposefully slow
198        and with random salt — but it produces a full-length binary key.
199     2. If a separate session key is requested, a new random key will be
200        generated. Otherwise the S2K key will be used directly as the
201        session key.
202     3. If the S2K key is to be used directly, then only S2K settings will
203        be put into the session key packet. Otherwise the session key will
204        be encrypted with the S2K key and put into the session key packet.
205
206    When encrypting with a public key:
207     1. A new random session key is generated.
208     2. It is encrypted using the public key and put into the session key
209        packet.
210
211    In either case the data to be encrypted is processed as follows:
212     1. Optional data-manipulation: compression, conversion to UTF-8,
213        and/or conversion of line-endings.
214     2. The data is prefixed with a block of random bytes. This is
215        equivalent to using a random IV.
216     3. A SHA-1 hash of the random prefix and data is appended.
217     4. All this is encrypted with the session key and placed in the data
218        packet.
219
220 F.26.3.1. pgp_sym_encrypt() #
221
222 pgp_sym_encrypt(data text, psw text [, options text ]) returns bytea
223 pgp_sym_encrypt_bytea(data bytea, psw text [, options text ]) returns bytea
224
225    Encrypt data with a symmetric PGP key psw. The options parameter can
226    contain option settings, as described below.
227
228 F.26.3.2. pgp_sym_decrypt() #
229
230 pgp_sym_decrypt(msg bytea, psw text [, options text ]) returns text
231 pgp_sym_decrypt_bytea(msg bytea, psw text [, options text ]) returns bytea
232
233    Decrypt a symmetric-key-encrypted PGP message.
234
235    Decrypting bytea data with pgp_sym_decrypt is disallowed. This is to
236    avoid outputting invalid character data. Decrypting originally textual
237    data with pgp_sym_decrypt_bytea is fine.
238
239    The options parameter can contain option settings, as described below.
240
241 F.26.3.3. pgp_pub_encrypt() #
242
243 pgp_pub_encrypt(data text, key bytea [, options text ]) returns bytea
244 pgp_pub_encrypt_bytea(data bytea, key bytea [, options text ]) returns bytea
245
246    Encrypt data with a public PGP key key. Giving this function a secret
247    key will produce an error.
248
249    The options parameter can contain option settings, as described below.
250
251 F.26.3.4. pgp_pub_decrypt() #
252
253 pgp_pub_decrypt(msg bytea, key bytea [, psw text [, options text ]]) returns tex
254 t
255 pgp_pub_decrypt_bytea(msg bytea, key bytea [, psw text [, options text ]]) retur
256 ns bytea
257
258    Decrypt a public-key-encrypted message. key must be the secret key
259    corresponding to the public key that was used to encrypt. If the secret
260    key is password-protected, you must give the password in psw. If there
261    is no password, but you want to specify options, you need to give an
262    empty password.
263
264    Decrypting bytea data with pgp_pub_decrypt is disallowed. This is to
265    avoid outputting invalid character data. Decrypting originally textual
266    data with pgp_pub_decrypt_bytea is fine.
267
268    The options parameter can contain option settings, as described below.
269
270 F.26.3.5. pgp_key_id() #
271
272 pgp_key_id(bytea) returns text
273
274    pgp_key_id extracts the key ID of a PGP public or secret key. Or it
275    gives the key ID that was used for encrypting the data, if given an
276    encrypted message.
277
278    It can return 2 special key IDs:
279      * SYMKEY
280        The message is encrypted with a symmetric key.
281      * ANYKEY
282        The message is public-key encrypted, but the key ID has been
283        removed. That means you will need to try all your secret keys on it
284        to see which one decrypts it. pgcrypto itself does not produce such
285        messages.
286
287    Note that different keys may have the same ID. This is rare but a
288    normal event. The client application should then try to decrypt with
289    each one, to see which fits — like handling ANYKEY.
290
291 F.26.3.6. armor(), dearmor() #
292
293 armor(data bytea [ , keys text[], values text[] ]) returns text
294 dearmor(data text) returns bytea
295
296    These functions wrap/unwrap binary data into PGP ASCII-armor format,
297    which is basically Base64 with CRC and additional formatting.
298
299    If the keys and values arrays are specified, an armor header is added
300    to the armored format for each key/value pair. Both arrays must be
301    single-dimensional, and they must be of the same length. The keys and
302    values cannot contain any non-ASCII characters.
303
304 F.26.3.7. pgp_armor_headers #
305
306 pgp_armor_headers(data text, key out text, value out text) returns setof record
307
308    pgp_armor_headers() extracts the armor headers from data. The return
309    value is a set of rows with two columns, key and value. If the keys or
310    values contain any non-ASCII characters, they are treated as UTF-8.
311
312 F.26.3.8. Options for PGP Functions #
313
314    Options are named to be similar to GnuPG. An option's value should be
315    given after an equal sign; separate options from each other with
316    commas. For example:
317 pgp_sym_encrypt(data, psw, 'compress-algo=1, cipher-algo=aes256')
318
319    All of the options except convert-crlf apply only to encrypt functions.
320    Decrypt functions get the parameters from the PGP data.
321
322    The most interesting options are probably compress-algo and
323    unicode-mode. The rest should have reasonable defaults.
324
325 F.26.3.8.1. cipher-algo #
326
327    Which cipher algorithm to use.
328
329    Values: bf, aes128, aes192, aes256, 3des, cast5
330    Default: aes128
331    Applies to: pgp_sym_encrypt, pgp_pub_encrypt
332
333 F.26.3.8.2. compress-algo #
334
335    Which compression algorithm to use. Only available if PostgreSQL was
336    built with zlib.
337
338    Values:
339      0 - no compression
340      1 - ZIP compression
341      2 - ZLIB compression (= ZIP plus meta-data and block CRCs)
342    Default: 0
343    Applies to: pgp_sym_encrypt, pgp_pub_encrypt
344
345 F.26.3.8.3. compress-level #
346
347    How much to compress. Higher levels compress smaller but are slower. 0
348    disables compression.
349
350    Values: 0, 1-9
351    Default: 6
352    Applies to: pgp_sym_encrypt, pgp_pub_encrypt
353
354 F.26.3.8.4. convert-crlf #
355
356    Whether to convert \n into \r\n when encrypting and \r\n to \n when
357    decrypting. RFC 4880 specifies that text data should be stored using
358    \r\n line-feeds. Use this to get fully RFC-compliant behavior.
359
360    Values: 0, 1
361    Default: 0
362    Applies to: pgp_sym_encrypt, pgp_pub_encrypt, pgp_sym_decrypt, pgp_pub_
363    decrypt
364
365 F.26.3.8.5. disable-mdc #
366
367    Do not protect data with SHA-1. The only good reason to use this option
368    is to achieve compatibility with ancient PGP products, predating the
369    addition of SHA-1 protected packets to RFC 4880. Recent gnupg.org and
370    pgp.com software supports it fine.
371
372    Values: 0, 1
373    Default: 0
374    Applies to: pgp_sym_encrypt, pgp_pub_encrypt
375
376 F.26.3.8.6. sess-key #
377
378    Use separate session key. Public-key encryption always uses a separate
379    session key; this option is for symmetric-key encryption, which by
380    default uses the S2K key directly.
381
382    Values: 0, 1
383    Default: 0
384    Applies to: pgp_sym_encrypt
385
386 F.26.3.8.7. s2k-mode #
387
388    Which S2K algorithm to use.
389
390    Values:
391      0 - Without salt.  Dangerous!
392      1 - With salt but with fixed iteration count.
393      3 - Variable iteration count.
394    Default: 3
395    Applies to: pgp_sym_encrypt
396
397 F.26.3.8.8. s2k-count #
398
399    The number of iterations of the S2K algorithm to use. It must be a
400    value between 1024 and 65011712, inclusive.
401
402    Default: A random value between 65536 and 253952
403    Applies to: pgp_sym_encrypt, only with s2k-mode=3
404
405 F.26.3.8.9. s2k-digest-algo #
406
407    Which digest algorithm to use in S2K calculation.
408
409    Values: md5, sha1
410    Default: sha1
411    Applies to: pgp_sym_encrypt
412
413 F.26.3.8.10. s2k-cipher-algo #
414
415    Which cipher to use for encrypting separate session key.
416
417    Values: bf, aes, aes128, aes192, aes256
418    Default: use cipher-algo
419    Applies to: pgp_sym_encrypt
420
421 F.26.3.8.11. unicode-mode #
422
423    Whether to convert textual data from database internal encoding to
424    UTF-8 and back. If your database already is UTF-8, no conversion will
425    be done, but the message will be tagged as UTF-8. Without this option
426    it will not be.
427
428    Values: 0, 1
429    Default: 0
430    Applies to: pgp_sym_encrypt, pgp_pub_encrypt
431
432 F.26.3.9. Generating PGP Keys with GnuPG #
433
434    To generate a new key:
435 gpg --gen-key
436
437    The preferred key type is “DSA and Elgamal”.
438
439    For RSA encryption you must create either DSA or RSA sign-only key as
440    master and then add an RSA encryption subkey with gpg --edit-key.
441
442    To list keys:
443 gpg --list-secret-keys
444
445    To export a public key in ASCII-armor format:
446 gpg -a --export KEYID > public.key
447
448    To export a secret key in ASCII-armor format:
449 gpg -a --export-secret-keys KEYID > secret.key
450
451    You need to use dearmor() on these keys before giving them to the PGP
452    functions. Or if you can handle binary data, you can drop -a from the
453    command.
454
455    For more details see man gpg, The GNU Privacy Handbook and other
456    documentation on https://www.gnupg.org/.
457
458 F.26.3.10. Limitations of PGP Code #
459
460      * No support for signing. That also means that it is not checked
461        whether the encryption subkey belongs to the master key.
462      * No support for encryption key as master key. As such practice is
463        generally discouraged, this should not be a problem.
464      * No support for several subkeys. This may seem like a problem, as
465        this is common practice. On the other hand, you should not use your
466        regular GPG/PGP keys with pgcrypto, but create new ones, as the
467        usage scenario is rather different.
468
469 F.26.4. Raw Encryption Functions #
470
471    These functions only run a cipher over data; they don't have any
472    advanced features of PGP encryption. Therefore they have some major
473    problems:
474     1. They use user key directly as cipher key.
475     2. They don't provide any integrity checking, to see if the encrypted
476        data was modified.
477     3. They expect that users manage all encryption parameters themselves,
478        even IV.
479     4. They don't handle text.
480
481    So, with the introduction of PGP encryption, usage of raw encryption
482    functions is discouraged.
483 encrypt(data bytea, key bytea, type text) returns bytea
484 decrypt(data bytea, key bytea, type text) returns bytea
485
486 encrypt_iv(data bytea, key bytea, iv bytea, type text) returns bytea
487 decrypt_iv(data bytea, key bytea, iv bytea, type text) returns bytea
488
489    Encrypt/decrypt data using the cipher method specified by type. The
490    syntax of the type string is:
491 algorithm [ - mode ] [ /pad: padding ]
492
493    where algorithm is one of:
494      * bf — Blowfish
495      * aes — AES (Rijndael-128, -192 or -256)
496
497    and mode is one of:
498      * cbc — next block depends on previous (default)
499      * cfb — next block depends on previous encrypted block
500      * ecb — each block is encrypted separately (for testing only)
501
502    and padding is one of:
503      * pkcs — data may be any length (default)
504      * none — data must be multiple of cipher block size
505
506    So, for example, these are equivalent:
507 encrypt(data, 'fooz', 'bf')
508 encrypt(data, 'fooz', 'bf-cbc/pad:pkcs')
509
510    In encrypt_iv and decrypt_iv, the iv parameter is the initial value for
511    the CBC and CFB mode; it is ignored for ECB. It is clipped or padded
512    with zeroes if not exactly block size. It defaults to all zeroes in the
513    functions without this parameter.
514
515 F.26.5. Random-Data Functions #
516
517 gen_random_bytes(count integer) returns bytea
518
519    Returns count cryptographically strong random bytes. At most 1024 bytes
520    can be extracted at a time. This is to avoid draining the randomness
521    generator pool.
522 gen_random_uuid() returns uuid
523
524    Returns a version 4 (random) UUID. (Obsolete, this function internally
525    calls the core function of the same name.)
526
527 F.26.6. OpenSSL Support Functions #
528
529 fips_mode() returns boolean
530
531    Returns true if OpenSSL is running with FIPS mode enabled, otherwise
532    false.
533
534 F.26.7. Configuration Parameters #
535
536    There is one configuration parameter that controls the behavior of
537    pgcrypto.
538
539    pgcrypto.builtin_crypto_enabled (enum) #
540           pgcrypto.builtin_crypto_enabled determines if the built in
541           crypto functions gen_salt(), and crypt() are available for use.
542           Setting this to off disables these functions. on (the default)
543           enables these functions to work normally. fips disables these
544           functions if OpenSSL is detected to operate in FIPS mode.
545
546    In ordinary usage, this parameter is set in postgresql.conf, although
547    superusers can alter it on-the-fly within their own sessions.
548
549 F.26.8. Notes #
550
551 F.26.8.1. Configuration #
552
553    pgcrypto configures itself according to the findings of the main
554    PostgreSQL configure script. The options that affect it are --with-zlib
555    and --with-ssl=openssl.
556
557    When compiled with zlib, PGP encryption functions are able to compress
558    data before encrypting.
559
560    pgcrypto requires OpenSSL. Otherwise, it will not be built or
561    installed.
562
563    When compiled against OpenSSL 3.0.0 and later versions, the legacy
564    provider must be activated in the openssl.cnf configuration file in
565    order to use older ciphers like DES or Blowfish.
566
567 F.26.8.2. NULL Handling #
568
569    As is standard in SQL, all functions return NULL, if any of the
570    arguments are NULL. This may create security risks on careless usage.
571
572 F.26.8.3. Security Limitations #
573
574    All pgcrypto functions run inside the database server. That means that
575    all the data and passwords move between pgcrypto and client
576    applications in clear text. Thus you must:
577     1. Connect locally or use SSL connections.
578     2. Trust both system and database administrator.
579
580    If you cannot, then better do crypto inside client application.
581
582    The implementation does not resist side-channel attacks. For example,
583    the time required for a pgcrypto decryption function to complete varies
584    among ciphertexts of a given size.
585
586 F.26.9. Author #
587
588    Marko Kreen <markokr@gmail.com>
589
590    pgcrypto uses code from the following sources:
591      Algorithm            Author           Source origin
592    DES crypt      David Burren and others FreeBSD libcrypt
593    MD5 crypt      Poul-Henning Kamp       FreeBSD libcrypt
594    Blowfish crypt Solar Designer          www.openwall.com