How do I install pgcrypto in PostgreSQL 8.4?

PostgreSQL 9.1+

Note that I'm working on Ubuntu 12.04, which uses postgresql 9.1.

There, I needed to:

sudo apt-get install postgresql-contrib

And then in my database:

postgres@ztrustee:~$ psql test
psql (9.1.3)
Type "help" for help.
test=# CREATE EXTENSION pgcrypto;
CREATE EXTENSION

And now I can use pgcrypto functionality, gen_random_bytes():

test=# create table test ( 
  id 
    text 
    not null 
    default encode( gen_random_bytes( 32 ), 'hex' ) 
    primary key, 
  value 
    text 
); 
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "test_pkey" for table "test"
CREATE TABLE
test=# \d test
                            Table "public.test"
 Column | Type |                         Modifiers                          
--------+------+------------------------------------------------------------
 id     | text | not null default encode(gen_random_bytes(32), 'hex'::text)
 value  | text | 
Indexes:
    "test_pkey" PRIMARY KEY, btree (id)

test=# insert into test (value) VALUES ('scoobydoo');
INSERT 0 1
test=# select * from test;
                                id                                |   value   
------------------------------------------------------------------+-----------
 76dd5bd0120d3df797f932fbcb4f8aa5088e215ee2b920dddbff59c8595fbac7 | scoobydoo

For newer version of PG, check out the answer below by Dustin Kirkland

It's an external module for Postgres. You should install the postgresql-contrib-8.4 (or your pg version) package via apt:

apt-get install postgresql-contrib-8.4

Then you find the sql install file somewhere in the /usr/share/postgresql folder, and you'll need to run pgcryto.sql on the database.

psql -d <database> -f /usr/share/postgresql/8.4/contrib/pgcrypto.sql

Or,

$ cd /usr/share/postgresql/8.4/contrib
$ psql -d <database>
    psql (8.4.8)
    Type "help" for help.

    database=# \i pgcrypto.sql

For the latest version, there is no file path end with pgcrypto.sql .

Create an extension pgcrypto under the required user.

$ psql -U <username> -d mydb

psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1))
Type "help" for help.

mydb=> CREATE EXTENSION pgcrypto;

CREATE EXTENSION
mydb=> 

If in case, the user does not have permission to create an extension, give superuser permission by login as postgres(default) user and try again.

$ psql --u postgres

psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1))
Type "help" for help.

postgres=# ALTER USER <username> WITH SUPERUSER;

ALTER ROLE