SQL | ENCRYPT Function

The SQL Encrypt function is used to encrypt a string using UNIX crypt(). The function is based on Unix crypt() system call, hence it returns NULL on Windows systems. The Encrypt function accepts two parameters which are the string and the salt to be encrypted.
The Encrypt function returns a binary string.

Syntax:

ENCRYPT(string, salt)

Parameters Used:

  • string – It is used to specify the plain text string that is to be encrypted using UNIX crypt().
  • salt – It is used to specify a string that is at least 2 characters long and cab be used in the encryption process. If salt is not provided, the ENCRYPT function uses a random value.

Return Value:
The Encrypt function in SQL returns a binary string.

The Encrypt function returns null in the following cases:



  • If salt is less than 2 characters in length, then the Encrypt function returns NULL.
  • If the string is NULL, then the Encrypt function returns NULL.
  • If UNIX crypt() is not available on the system, then the Encrypt function returns NULL.

Supported Versions of MySQL:

  • MySQL 5.7
  • MySQL 5.6
  • MySQL 5.5
  • MySQL 5.1
  • MySQL 5.0
  • MySQL 4.1

Example-1: Implementing Encrypt function on a string.

SELECT 
ENCRYPT('xyz'); 

Output:

sf3Le/pz2ApNY 

Example-2: Implementing Encrypt function on a bigger string.

SELECT 
ENCRYPT('geeksforgeeks'); 

Output:

.mblNS3yOZxb2 

Example-3: Implementing Encrypt function on a string by passing both the arguments.

SELECT 
ENCRYPT('geeksforgeeks', '123'); 

Output:

12SrVMQf0pwFU 

Example-4: Implementing Encrypt function on a string by passing less than 2 characters in the salt argument.

SELECT 
ENCRYPT('geeksforgeeks', '2'); 

Output:

NULL 

Since the salt argument is less than 2 characters in length, the Encrypt function returns NULL.

Example-5: Implementing Encrypt function on a NULL string.

SELECT 
ENCRYPT(NULL); 

Output:

NULL 
My Personal Notes arrow_drop_up

I am a technology enthusiast who has a keen interest in programming I am pursuing Engineering in Computer Science from GEU, Dehradun I like to unwind by watching movies and English sitcomsI have a keen interest in music

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.