2 F.26. pgcrypto — cryptographic functions #
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
14 The pgcrypto module provides cryptographic functions for PostgreSQL.
16 This module is considered “trusted”, that is, it can be installed by
17 non-superusers who have CREATE privilege on the current database.
19 pgcrypto requires OpenSSL and won't be installed if OpenSSL support was
20 not selected when PostgreSQL was built.
22 F.26.1. General Hashing Functions #
26 digest(data text, type text) returns bytea
27 digest(data bytea, type text) returns bytea
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
34 If you want the digest as a hexadecimal string, use encode() on the
36 CREATE OR REPLACE FUNCTION sha1(bytea) returns text AS $$
37 SELECT encode(digest($1, 'sha1'), 'hex')
38 $$ LANGUAGE SQL STRICT IMMUTABLE;
42 hmac(data text, key text, type text) returns bytea
43 hmac(data bytea, key bytea, type text) returns bytea
45 Calculates hashed MAC for data with key key. type is the same as in
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.
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.
55 F.26.2. Password Hashing Functions #
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.
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.
74 Table F.18 lists the algorithms supported by the crypt() function.
76 Table F.18. Supported Algorithms for crypt()
77 Algorithm Max Password Length Adaptive? Salt Bits Output Length
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
90 crypt(password text, salt text) returns text
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.
97 Example of setting a new password:
98 UPDATE ... SET pswhash = crypt('new password', gen_salt('md5'));
100 Example of authentication:
101 SELECT (pswhash = crypt('entered password', pswhash)) AS pswmatch FROM ... ;
103 This returns true if the entered password is correct.
105 F.26.2.2. gen_salt() #
107 gen_salt(type text [, iter_count integer ]) returns text
109 Generates a new random salt string for use in crypt(). The salt string
110 also tells crypt() which algorithm to use.
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.
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.
124 Table F.19. Iteration Counts for crypt()
125 Algorithm Default Min Max
128 sha256crypt, sha512crypt 5000 1000 999999999
130 For xdes there is an additional limitation that the iteration count
131 must be an odd number.
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
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.
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.
151 Table F.20. Hash Algorithm Speeds
152 Algorithm Hashes/sec For [a-z] For [A-Za-z0-9] Duration relative to md5
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
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
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
184 F.26.3. PGP Encryption Functions #
186 The functions here implement the encryption part of the OpenPGP (RFC
187 4880) standard. Supported are both symmetric-key and public-key
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.
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
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.
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
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
220 F.26.3.1. pgp_sym_encrypt() #
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
225 Encrypt data with a symmetric PGP key psw. The options parameter can
226 contain option settings, as described below.
228 F.26.3.2. pgp_sym_decrypt() #
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
233 Decrypt a symmetric-key-encrypted PGP message.
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.
239 The options parameter can contain option settings, as described below.
241 F.26.3.3. pgp_pub_encrypt() #
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
246 Encrypt data with a public PGP key key. Giving this function a secret
247 key will produce an error.
249 The options parameter can contain option settings, as described below.
251 F.26.3.4. pgp_pub_decrypt() #
253 pgp_pub_decrypt(msg bytea, key bytea [, psw text [, options text ]]) returns tex
255 pgp_pub_decrypt_bytea(msg bytea, key bytea [, psw text [, options text ]]) retur
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
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.
268 The options parameter can contain option settings, as described below.
270 F.26.3.5. pgp_key_id() #
272 pgp_key_id(bytea) returns text
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
278 It can return 2 special key IDs:
280 The message is encrypted with a symmetric key.
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
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.
291 F.26.3.6. armor(), dearmor() #
293 armor(data bytea [ , keys text[], values text[] ]) returns text
294 dearmor(data text) returns bytea
296 These functions wrap/unwrap binary data into PGP ASCII-armor format,
297 which is basically Base64 with CRC and additional formatting.
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.
304 F.26.3.7. pgp_armor_headers #
306 pgp_armor_headers(data text, key out text, value out text) returns setof record
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.
312 F.26.3.8. Options for PGP Functions #
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
317 pgp_sym_encrypt(data, psw, 'compress-algo=1, cipher-algo=aes256')
319 All of the options except convert-crlf apply only to encrypt functions.
320 Decrypt functions get the parameters from the PGP data.
322 The most interesting options are probably compress-algo and
323 unicode-mode. The rest should have reasonable defaults.
325 F.26.3.8.1. cipher-algo #
327 Which cipher algorithm to use.
329 Values: bf, aes128, aes192, aes256, 3des, cast5
331 Applies to: pgp_sym_encrypt, pgp_pub_encrypt
333 F.26.3.8.2. compress-algo #
335 Which compression algorithm to use. Only available if PostgreSQL was
341 2 - ZLIB compression (= ZIP plus meta-data and block CRCs)
343 Applies to: pgp_sym_encrypt, pgp_pub_encrypt
345 F.26.3.8.3. compress-level #
347 How much to compress. Higher levels compress smaller but are slower. 0
348 disables compression.
352 Applies to: pgp_sym_encrypt, pgp_pub_encrypt
354 F.26.3.8.4. convert-crlf #
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.
362 Applies to: pgp_sym_encrypt, pgp_pub_encrypt, pgp_sym_decrypt, pgp_pub_
365 F.26.3.8.5. disable-mdc #
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.
374 Applies to: pgp_sym_encrypt, pgp_pub_encrypt
376 F.26.3.8.6. sess-key #
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.
384 Applies to: pgp_sym_encrypt
386 F.26.3.8.7. s2k-mode #
388 Which S2K algorithm to use.
391 0 - Without salt. Dangerous!
392 1 - With salt but with fixed iteration count.
393 3 - Variable iteration count.
395 Applies to: pgp_sym_encrypt
397 F.26.3.8.8. s2k-count #
399 The number of iterations of the S2K algorithm to use. It must be a
400 value between 1024 and 65011712, inclusive.
402 Default: A random value between 65536 and 253952
403 Applies to: pgp_sym_encrypt, only with s2k-mode=3
405 F.26.3.8.9. s2k-digest-algo #
407 Which digest algorithm to use in S2K calculation.
411 Applies to: pgp_sym_encrypt
413 F.26.3.8.10. s2k-cipher-algo #
415 Which cipher to use for encrypting separate session key.
417 Values: bf, aes, aes128, aes192, aes256
418 Default: use cipher-algo
419 Applies to: pgp_sym_encrypt
421 F.26.3.8.11. unicode-mode #
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
430 Applies to: pgp_sym_encrypt, pgp_pub_encrypt
432 F.26.3.9. Generating PGP Keys with GnuPG #
434 To generate a new key:
437 The preferred key type is “DSA and Elgamal”.
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.
443 gpg --list-secret-keys
445 To export a public key in ASCII-armor format:
446 gpg -a --export KEYID > public.key
448 To export a secret key in ASCII-armor format:
449 gpg -a --export-secret-keys KEYID > secret.key
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
455 For more details see man gpg, The GNU Privacy Handbook and other
456 documentation on https://www.gnupg.org/.
458 F.26.3.10. Limitations of PGP Code #
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.
469 F.26.4. Raw Encryption Functions #
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
474 1. They use user key directly as cipher key.
475 2. They don't provide any integrity checking, to see if the encrypted
477 3. They expect that users manage all encryption parameters themselves,
479 4. They don't handle text.
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
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
489 Encrypt/decrypt data using the cipher method specified by type. The
490 syntax of the type string is:
491 algorithm [ - mode ] [ /pad: padding ]
493 where algorithm is one of:
495 * aes — AES (Rijndael-128, -192 or -256)
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)
502 and padding is one of:
503 * pkcs — data may be any length (default)
504 * none — data must be multiple of cipher block size
506 So, for example, these are equivalent:
507 encrypt(data, 'fooz', 'bf')
508 encrypt(data, 'fooz', 'bf-cbc/pad:pkcs')
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.
515 F.26.5. Random-Data Functions #
517 gen_random_bytes(count integer) returns bytea
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
522 gen_random_uuid() returns uuid
524 Returns a version 4 (random) UUID. (Obsolete, this function internally
525 calls the core function of the same name.)
527 F.26.6. OpenSSL Support Functions #
529 fips_mode() returns boolean
531 Returns true if OpenSSL is running with FIPS mode enabled, otherwise
534 F.26.7. Configuration Parameters #
536 There is one configuration parameter that controls the behavior of
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.
546 In ordinary usage, this parameter is set in postgresql.conf, although
547 superusers can alter it on-the-fly within their own sessions.
551 F.26.8.1. Configuration #
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.
557 When compiled with zlib, PGP encryption functions are able to compress
558 data before encrypting.
560 pgcrypto requires OpenSSL. Otherwise, it will not be built or
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.
567 F.26.8.2. NULL Handling #
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.
572 F.26.8.3. Security Limitations #
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.
580 If you cannot, then better do crypto inside client application.
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.
588 Marko Kreen <markokr@gmail.com>
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