Created
December 30, 2015 12:14
-
-
Save rstriquer/d7d702b91577f0c927b4 to your computer and use it in GitHub Desktop.
Função para encodar strings em MySQL com o algoritmo base64 http://www.programabrasil.org/mysql-base64-encode-sem-tabela-de-conversao/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DELIMITER $$ | |
USE `YOUR DATABASE`$$ | |
DROP FUNCTION IF EXISTS `BASE64_ENCODE`$$ | |
CREATE DEFINER=`YOUR DATABASE`@`%` FUNCTION `BASE64_ENCODE`(input BLOB) RETURNS BLOB | |
DETERMINISTIC | |
SQL SECURITY INVOKER | |
BEGIN | |
DECLARE ret BLOB DEFAULT ''; | |
DECLARE done TINYINT DEFAULT 0; | |
IF input IS NULL THEN | |
RETURN NULL; | |
END IF; | |
each_block: | |
WHILE NOT done DO BEGIN | |
DECLARE accum_value BIGINT UNSIGNED DEFAULT 0; | |
DECLARE in_count TINYINT DEFAULT 0; | |
DECLARE out_count TINYINT; | |
each_input_char: | |
WHILE in_count < 3 DO BEGIN | |
DECLARE first_char BLOB(1); | |
IF LENGTH(input) = 0 THEN | |
SET done = 1; | |
SET accum_value = accum_value << (8 * (3 - in_count)); | |
LEAVE each_input_char; | |
END IF; | |
SET first_char = SUBSTRING(input,1,1); | |
SET input = SUBSTRING(input,2); | |
SET accum_value = (accum_value << 8) + ASCII(first_char); | |
SET in_count = in_count + 1; | |
END; END WHILE; | |
-- We've now accumulated 24 bits; deaccumulate into base64 characters | |
-- We have to work from the left, so use the third byte position and shift left | |
CASE | |
WHEN in_count = 3 THEN SET out_count = 4; | |
WHEN in_count = 2 THEN SET out_count = 3; | |
WHEN in_count = 1 THEN SET out_count = 2; | |
ELSE RETURN ret; | |
END CASE; | |
WHILE out_count > 0 DO BEGIN | |
BEGIN | |
DECLARE out_char CHAR(1); | |
DECLARE base64_getval CURSOR FOR SELECT c FROM core_base64_data WHERE val = (accum_value >> 18); | |
OPEN base64_getval; | |
FETCH base64_getval INTO out_char; | |
CLOSE base64_getval; | |
SET ret = CONCAT(ret,out_char); | |
SET out_count = out_count - 1; | |
SET accum_value = accum_value << 6 & 0xffffff; | |
END; | |
END; END WHILE; | |
CASE | |
WHEN in_count = 2 THEN SET ret = CONCAT(ret,'='); | |
WHEN in_count = 1 THEN SET ret = CONCAT(ret,'=='); | |
ELSE BEGIN END; | |
END CASE; | |
END; END WHILE; | |
RETURN ret; | |
END$$ | |
DELIMITER ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment