Open In App

SQL | ENCRYPT Function

Last Updated : 31 Oct, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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 

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads