1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MySQLのファンクションでパスワードの暗号化、複号化

Posted at

DBのストアドプロシージャ/ファンクションの覚え書き
PHPでやるより管理が楽&共通化ということでパスワードファンクションを作成。


DROP FUNCTION  IF EXISTS GET_PASSWORD;

DELIMITER //
CREATE FUNCTION GET_PASSWORD(
	IN_MODE INT,					/* 1:暗号化 2:複号化 */
	IN_PASSWORDKEY VARCHAR(100)		/* 1:暗号化、複号化する文字 */
)
RETURNS VARCHAR(100) DETERMINISTIC
BEGIN
    DECLARE STR_AESKEY 		VARCHAR(10)  DEFAULT NULL;
    DECLARE STR_PASSWORD 	VARCHAR(100) DEFAULT NULL;
	DECLARE EXIT HANDLER FOR SQLWARNING, NOT FOUND, SQLEXCEPTION
	BEGIN
		RETURN NULL;
	END;
	
	SET STR_PASSWORD := NULL;
	SET STR_AESKEY := 'TEST'; /* 共通AESキー */
	
	IF IN_MODE = 1 THEN /* 暗号化 */
	
		SET STR_PASSWORD := HEX(AES_ENCRYPT(IN_PASSWORDKEY, STR_AESKEY));
	
	ELSEIF IN_MODE = 2 THEN /* 複号化 */
	
		SET STR_PASSWORD := AES_DECRYPT(UNHEX(IN_PASSWORDKEY), STR_AESKEY);

	END IF;
	
	RETURN STR_PASSWORD;
	
END;
//
DELIMITER ;

ファンクションが作成されたかの確認

SHOW FUNCTION STATUS;

実際に使ってみる。

	SELECT GET_PASSWORD(1,'pass') FROM DUAL
	
	SELECT GET_PASSWORD(2,'555939D89BE849A54A2BCD6084AD0BE6') FROM DUAL

	--1
	SELECT COUNT(*) FROM DUAL
	WHERE 'pass' = GET_PASSWORD(2,'555939D89BE849A54A2BCD6084AD0BE6')

カウント1取れました。今回のDBファンクション作成は成功です!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?