[Java] 암호화 복호화 Base64

2013. 11. 13. 11:11개발관련기록/Java

반응형

암호화 복호화 너가 짱이다.


출처 : http://blog.naver.com/PostView.nhn?blogId=erroring&logNo=150111219347


페이지에서는 비밀번호, 파라매터등이 사용자에게 보여지면서 생길 수 있는 문제를 방지하기 위한 base64 인코딩 방법.

base64_Encode SQL 함수

   1:  
   2: /****** 개체:  UserDefinedFunction [dbo].[base64_encode]    스크립트 날짜: 12/04/2009 10:15:17 ******/
   3: SET ANSI_NULLS ON
   4: GO
   5: SET QUOTED_IDENTIFIER ON
   6: GO
   7: -- =============================================
   8: -- Create date: 2009-12-02
   9: -- Description:    base64 인코딩 함수
  10: -- =============================================
  11: CREATE FUNCTION [dbo].[base64_encode]
  12: (
  13:     @plain_text varchar(6000)
  14: )
  15: RETURNS 
  16:           varchar(8000)
  17: AS BEGIN
  18: --local variables
  19: DECLARE
  20:   @output            varchar(8000),
  21:   @input_length      integer,
  22:   @block_start       integer,
  23:   @partial_block_start  integer, -- position of last 0, 1 or 2 characters
  24:   @partial_block_length integer,
  25:   @block_val         integer,
  26:   @map               char(64)
  27: SET @map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  28: --initialise variables
  29: SET @output   = ''
  30: --set length and count
  31: SET @input_length      = LEN( @plain_text + '#' ) - 1
  32: SET @partial_block_length = @input_length % 3
  33: SET @partial_block_start = @input_length - @partial_block_length
  34: SET @block_start       = 1
  35: --for each block
  36: WHILE @block_start < @partial_block_start  BEGIN
  37:   SET @block_val = CAST(SUBSTRING(@plain_text, @block_start, 3) AS BINARY(3))
  38:   --encode the 3 character block and add to the output
  39:   SET @output = @output + SUBSTRING(@map, @block_val / 262144 + 1, 1)
  40:                         + SUBSTRING(@map, (@block_val / 4096 & 63) + 1, 1)
  41:                         + SUBSTRING(@map, (@block_val / 64 & 63  ) + 1, 1)
  42:                         + SUBSTRING(@map, (@block_val & 63) + 1, 1)
  43:   --increment the counter
  44:   SET @block_start = @block_start + 3
  45: END
  46: IF @partial_block_length > 0
  47: BEGIN
  48:   SET @block_val = CAST(SUBSTRING(@plain_text, @block_start, @partial_block_length)
  49:                       + REPLICATE(CHAR(0), 3 - @partial_block_length) AS BINARY(3))
  50:   SET @output = @output
  51:  + SUBSTRING(@map, @block_val / 262144 + 1, 1)
  52:  + SUBSTRING(@map, (@block_val / 4096 & 63) + 1, 1)
  53:  + CASE WHEN @partial_block_length < 2
  54:     THEN REPLACE(SUBSTRING(@map, (@block_val / 64 & 63  ) + 1, 1), 'A', '=')
  55:     ELSE SUBSTRING(@map, (@block_val / 64 & 63  ) + 1, 1) END
  56:  + CASE WHEN @partial_block_length < 3
  57:     THEN REPLACE(SUBSTRING(@map, (@block_val & 63) + 1, 1), 'A', '=')
  58:     ELSE SUBSTRING(@map, (@block_val & 63) + 1, 1) END
  59: END
  60: --return the result
  61: RETURN @output
  62: END


base64_Decode SQL 함수

   1:  
   2: /****** 개체:  UserDefinedFunction [dbo].[base64_decode]    스크립트 날짜: 12/04/2009 10:19:32 ******/
   3: SET ANSI_NULLS ON
   4: GO
   5: SET QUOTED_IDENTIFIER ON
   6: GO
   7: -- =============================================
   8:  
   9: -- Create date: 2009-12-02
  10: -- Description:    base64 디코딩 함수
  11: -- =============================================
  12: CREATE FUNCTION [dbo].[base64_decode]
  13: (
  14:     @encoded_text varchar(8000)
  15: )
  16: RETURNS 
  17:           varchar(6000)
  18: AS BEGIN
  19: --local variables
  20: DECLARE
  21:   @output           varchar(8000),
  22:   @block_start      int,
  23:   @encoded_length   int,
  24:   @decoded_length   int,
  25:   @mapr             binary(122)
  26: --IF @encoded_text COLLATE LATIN1_GENERAL_BIN
  27: -- LIKE '%[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=]%'
  28: --     COLLATE LATIN1_GENERAL_BIN
  29: --  RETURN NULL
  30: --IF LEN(@encoded_text) & 3 > 0
  31: --  RETURN NULL
  32: SET @output   = ''
  33: -- The nth byte of @mapr contains the base64 value
  34: -- of the character with an ASCII value of n.
  35: -- EG, 65th byte = 0x00 = 0 = value of 'A'
  36: SET @mapr =
  37:   0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF -- 1-33
  38: + 0xFFFFFFFFFFFFFFFFFFFF3EFFFFFF3F3435363738393A3B3C3DFFFFFF00FFFFFF -- 33-64
  39: + 0x000102030405060708090A0B0C0D0E0F10111213141516171819FFFFFFFFFFFF -- 65-96
  40: + 0x1A1B1C1D1E1F202122232425262728292A2B2C2D2E2F30313233 -- 97-122
  41: --get the number of blocks to be decoded
  42: SET @encoded_length = LEN(@encoded_text)
  43: SET @decoded_length = @encoded_length / 4 * 3
  44: --for each block
  45: SET @block_start = 1
  46: WHILE @block_start < @encoded_length BEGIN
  47:   --decode the block and add to output
  48:   --BINARY values between 1 and 4 bytes can be implicitly cast to INT
  49:   SET @output = @output +  CAST(CAST(CAST(
  50:    substring( @mapr, ascii( substring( @encoded_text, @block_start    , 1) ), 1) * 262144
  51:  + substring( @mapr, ascii( substring( @encoded_text, @block_start + 1, 1) ), 1) * 4096
  52:  + substring( @mapr, ascii( substring( @encoded_text, @block_start + 2, 1) ), 1) * 64
  53:  + substring( @mapr, ascii( substring( @encoded_text, @block_start + 3, 1) ), 1) 
  54:    AS INTEGER) AS BINARY(3)) AS VARCHAR(3))
  55:   SET @block_start = @block_start + 4
  56: END
  57: IF RIGHT(@encoded_text, 2) = '=='
  58:  SET @decoded_length = @decoded_length - 2
  59: ELSE IF RIGHT(@encoded_text, 1) = '='
  60:  SET @decoded_length = @decoded_length - 1
  61: --IF SUBSTRING(@output, @decoded_length, 1) = CHAR(0)
  62: -- SET @decoded_length = @decoded_length - 1
  63: --return the decoded string
  64: RETURN LEFT(@output, @decoded_length)
  65: END


base64_Encode VBScript 함수

   1: Function Base64Encode(inData)
   2:  
   3:             Const Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
   4:             Dim cOut, sOut, I
   5:               
   6:             For I = 1 To Len(inData) Step 3
   7:                 Dim nGroup, pOut, sGroup
   8:                 
   9:                 nGroup = &H10000 * Asc(Mid(inData, I, 1)) + _
  10:                 &H100 * MyASC(Mid(inData, I + 1, 1)) + MyASC(Mid(inData, I + 2, 1))
  11:                 
  12:  
  13:                 nGroup = Oct(nGroup)
  14:                 
  15:  
  16:                 nGroup = String(8 - Len(nGroup), "0") & nGroup
  17:                 
  18:  
  19:                 pOut = Mid(Base64, CLng("&o" & Mid(nGroup, 1, 2)) + 1, 1) + _
  20:                 Mid(Base64, CLng("&o" & Mid(nGroup, 3, 2)) + 1, 1) + _
  21:                 Mid(Base64, CLng("&o" & Mid(nGroup, 5, 2)) + 1, 1) + _
  22:                 Mid(Base64, CLng("&o" & Mid(nGroup, 7, 2)) + 1, 1)
  23:                 
  24:  
  25:                 sOut = sOut + pOut
  26:  
  27:             Next
  28:             Select Case Len(inData) Mod 3
  29:                 Case 1: 
  30:                 sOut = Left(sOut, Len(sOut) - 2) + "=="
  31:                 Case 2: 
  32:                 sOut = Left(sOut, Len(sOut) - 1) + "="
  33:             End Select
  34:             Base64Encode = sOut
  35:         End Function
  36:  
  37:         

base64_Decode VBScript 함수

   1: Function Base64Decode(ByVal base64String)
   2:  
   3:         Const Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
   4:         Dim dataLength, sOut, groupBegin
   5:           
   6:         
   7:         base64String = Replace(base64String, vbCrLf, "")
   8:         base64String = Replace(base64String, vbTab, "")
   9:         base64String = Replace(base64String, " ", "")
  10:           
  11:         
  12:         dataLength = Len(base64String)
  13:         If dataLength Mod 4 <> 0 Then
  14:             Err.Raise 1, "Base64Decode", "Bad Base64 string."
  15:             Exit Function
  16:         End If
  17:  
  18:           
  19:         
  20:         For groupBegin = 1 To dataLength Step 4
  21:             Dim numDataBytes, CharCounter, thisChar, thisData, nGroup, pOut
  22:             
  23:             numDataBytes = 3
  24:             nGroup = 0
  25:  
  26:             For CharCounter = 0 To 3
  27:  
  28:             thisChar = Mid(base64String, groupBegin + CharCounter, 1)
  29:  
  30:             If thisChar = "=" Then
  31:                 numDataBytes = numDataBytes - 1
  32:                 thisData = 0
  33:             Else
  34:                 thisData = InStr(1, Base64, thisChar, vbBinaryCompare) - 1
  35:             End If
  36:             If thisData = -1 Then
  37:                 Err.Raise 2, "Base64Decode", "Bad character In Base64 string."
  38:                 Exit Function
  39:             End If
  40:  
  41:             nGroup = 64 * nGroup + thisData
  42:             Next
  43:             
  44:             
  45:             nGroup = Hex(nGroup)
  46:             
  47:             
  48:             nGroup = String(6 - Len(nGroup), "0") & nGroup
  49:             
  50:             
  51:             pOut = Chr(CByte("&H" & Mid(nGroup, 1, 2))) + _
  52:             Chr(CByte("&H" & Mid(nGroup, 3, 2))) + _
  53:             Chr(CByte("&H" & Mid(nGroup, 5, 2)))
  54:             
  55:             sOut = sOut & Left(pOut, numDataBytes)
  56:         Next
  57:  
  58:         Base64Decode = sOut
  59:     End Function

base64_Encode C# 함수

   1: public string Base64Encode(string data)
   2:         {
   3:             try
   4:             {
   5:                 byte[] encData_byte = new byte[data.Length];
   6:                 encData_byte = System.Text.Encoding.UTF8.GetBytes(data);    
   7:                 string encodedData = Convert.ToBase64String(encData_byte);
   8:                 return encodedData;
   9:             }
  10:             catch(Exception e)
  11:             {
  12:                 throw new Exception("Error in base64Encode" + e.Message);
  13:             }
  14:         }

base64_Decode C# 함수

   1: public string Base64Decode(string data)
   2:         {
   3:             try
   4:             {
   5:                 System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();  
   6:                 System.Text.Decoder utf8Decode = encoder.GetDecoder();
   7:     
   8:                 byte[] todecode_byte = Convert.FromBase64String(data);
   9:                 int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);    
  10:                 char[] decoded_char = new char[charCount];
  11:                 utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);                   
  12:                 string result = new String(decoded_char);
  13:                 return result;
  14:             }
  15:             catch(Exception e)
  16:             {
  17:                 throw new Exception("Error in base64Decode" + e.Message);
  18:             }
  19:         }


base64_Encode+Decode JavaScript 함수

   1:  
   2: var Base64 = {
   3:  
   4:     // private property
   5:     _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
   6:  
   7:     // public method for encoding
   8:     encode : function (input) {
   9:         var output = "";
  10:         var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  11:         var i = 0;
  12:  
  13:         input = Base64._utf8_encode(input);
  14:  
  15:         while (i < input.length) {
  16:  
  17:             chr1 = input.charCodeAt(i++);
  18:             chr2 = input.charCodeAt(i++);
  19:             chr3 = input.charCodeAt(i++);
  20:  
  21:             enc1 = chr1 >> 2;
  22:             enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  23:             enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  24:             enc4 = chr3 & 63;
  25:  
  26:             if (isNaN(chr2)) {
  27:                 enc3 = enc4 = 64;
  28:             } else if (isNaN(chr3)) {
  29:                 enc4 = 64;
  30:             }
  31:  
  32:             output = output +
  33:             this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
  34:             this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
  35:  
  36:         }
  37:  
  38:         return output;
  39:     },
  40:  
  41:     // public method for decoding
  42:     decode : function (input) {
  43:         var output = "";
  44:         var chr1, chr2, chr3;
  45:         var enc1, enc2, enc3, enc4;
  46:         var i = 0;
  47:  
  48:         input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  49:  
  50:         while (i < input.length) {
  51:  
  52:             enc1 = this._keyStr.indexOf(input.charAt(i++));
  53:             enc2 = this._keyStr.indexOf(input.charAt(i++));
  54:             enc3 = this._keyStr.indexOf(input.charAt(i++));
  55:             enc4 = this._keyStr.indexOf(input.charAt(i++));
  56:  
  57:             chr1 = (enc1 << 2) | (enc2 >> 4);
  58:             chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  59:             chr3 = ((enc3 & 3) << 6) | enc4;
  60:  
  61:             output = output + String.fromCharCode(chr1);
  62:  
  63:             if (enc3 != 64) {
  64:                 output = output + String.fromCharCode(chr2);
  65:             }
  66:             if (enc4 != 64) {
  67:                 output = output + String.fromCharCode(chr3);
  68:             }
  69:  
  70:         }
  71:  
  72:         output = Base64._utf8_decode(output);
  73:  
  74:         return output;
  75:  
  76:     },
  77:  
  78:     // private method for UTF-8 encoding
  79:     _utf8_encode : function (string) {
  80:         string = string.replace(/\r\n/g,"\n");
  81:         var utftext = "";
  82:  
  83:         for (var n = 0; n < string.length; n++) {
  84:  
  85:             var c = string.charCodeAt(n);
  86:  
  87:             if (c < 128) {
  88:                 utftext += String.fromCharCode(c);
  89:             }
  90:             else if((c > 127) && (c < 2048)) {
  91:                 utftext += String.fromCharCode((c >> 6) | 192);
  92:                 utftext += String.fromCharCode((c & 63) | 128);
  93:             }
  94:             else {
  95:                 utftext += String.fromCharCode((c >> 12) | 224);
  96:                 utftext += String.fromCharCode(((c >> 6) & 63) | 128);
  97:                 utftext += String.fromCharCode((c & 63) | 128);
  98:             }
  99:  
 100:         }
 101:  
 102:         return utftext;
 103:     },
 104:  
 105:     // private method for UTF-8 decoding
 106:     _utf8_decode : function (utftext) {
 107:         var string = "";
 108:         var i = 0;
 109:         var c = c1 = c2 = 0;
 110:  
 111:         while ( i < utftext.length ) {
 112:  
 113:             c = utftext.charCodeAt(i);
 114:  
 115:             if (c < 128) {
 116:                 string += String.fromCharCode(c);
 117:                 i++;
 118:             }
 119:             else if((c > 191) && (c < 224)) {
 120:                 c2 = utftext.charCodeAt(i+1);
 121:                 string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
 122:                 i += 2;
 123:             }
 124:             else {
 125:                 c2 = utftext.charCodeAt(i+1);
 126:                 c3 = utftext.charCodeAt(i+2);
 127:                 string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
 128:                 i += 3;
 129:             }
 130:  
 131:         }
 132:  
 133:         return string;
 134:     }
 135:  
 136: }


반응형