DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`cryptOff`(vText VARCHAR(255), vKey VARCHAR(255), OUT vResult VARCHAR(255))
BEGIN

	DECLARE vUncryptedText VARCHAR(255) DEFAULT '';
    
	DECLARE vKeyLength INT;
    DECLARE vKeyPosition INT DEFAULT 1;
    DECLARE vKeyChar VARCHAR(1);
    
    DECLARE vTextLength INT;
    DECLARE vTextPosition INT DEFAULT 1;
    DECLARE vTextChar VARCHAR(1);
    
    DECLARE vUncryptedChar VARCHAR(1);
    DECLARE vUncryptedCharPosition INT;
    
    DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz';
    DECLARE vChainTextPosition INT;
    DECLARE vChainKeyPosition INT;
    DECLARE vChainLength INT;
    
    SET vTextLength = LENGTH(vText);	
    SET vKeyLength = LENGTH(vKey);
    SET vChainLength = LENGTH(vChain);
	
	WHILE vTextPosition <= vTextLength DO
    
		SET vTextChar = MID(vText,vTextPosition,1);
        SET vKeyChar =  MID(vKey,vKeyPosition,1);
        
        SET vChainTextPosition = LOCATE(vTextChar, vChain);
        SET vChainKeyPosition = LOCATE(vKeyChar, vChain);
        SET vUncryptedCharPosition = vChainTextPosition - vChainKeyPosition;
        
        IF vUncryptedCharPosition < 1 THEN
        
			SET vUncryptedCharPosition = vUncryptedCharPosition + vChainLength;
            
		END IF;
        
        SET vUncryptedChar = MID(vChain, vUncryptedCharPosition,1);
        
        SET vUncryptedText = CONCAT(vUncryptedText, vUncryptedChar);
        
		SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1);
		SET vTextPosition = vTextPosition + 1;
    
    END WHILE;

	SET vResult = vUncryptedText;

END$$
DELIMITER ;
