Fogeaters, Light The World.

28

2017-Aug

[php] AES / mcrypt 양방향 대칭키 암호화/복호화

작성자: title: MoonBlonix IP ADRESS: *.64.228.3 조회 수: 1238

AES 암호화를 원할 경우 아래 링크를 참고하자

-> php 5.2 이하는 mcrypt를 이용하고, 그 위로는  openssl을 이용할 수 있다.

-> 가능하다면 차후 ssl 인증서를 위해서라도 openssl로 가자 -> 리눅스 기본설치되어있을 수 있으니 먼저 phpinfo() 이용 로드 확인

https://m.blog.naver.com/PostView.nhn?blogId=oohyes&logNo=220153599906&proxyReferer=https%3A%2F%2Fwww.google.co.kr%2F


----------------------


1. 자신의 php 버전에 맞는 mcrypt 를 다운받아야 한다.


sudo apt-get update

이후에

sudo apt-get install mcrypt php5-mcrypt

를 하든지

sudo apt-get install mcrypt php7.0-mcrypt

를 하든지

sudo apt-get install mcrypt php7.1-mcrypt

를 하든지 알아서 잘 깔자.



2. http://solskjaer.tistory.com/169 참고


$key = "열쇠";

$plainData = "개인정보";

$encryptedDataOnBinary = mcrypt_ecb(MCRYPT_GOST, $key, $plainData, MCRYPT_ENCRYPT);

$encryptedData = base64_encode($encryptedDataOnBinary);

echo "암호화 할 평문 : ".$plainData;

echo "<BR>";

echo "암호화 결과로 나온 바이너리 값: ".$encryptedDataOnBinary;

echo "<BR>";

echo "암호화 결과를 아스키 코드로 변환한 값 : ".$encryptedData;


위에서는 암호화 방식으로 GOST를 이용했는데, 다른 방식을 원하면 아래 링크를 확인하자.

http://www.php.net/manual/en/mcrypt.ciphers.php

http://mcrypt.sourceforge.net/

추천하는 방식은 AES128, SEED, ARIA128 등..



$decryptedDataOnBinary = base64_decode($encryptedData);

$decryptedData = mcrypt_ecb(MCRYPT_GOST, $key, $decryptedDataOnBinary, MCRYPT_DECRYPT);

echo "바이너리 값으로 다시 변환한 암호화 결과 값 : ".$decryptedDataOnBinary;

echo "<BR>";

echo "바이너리 값을 복호화 한 결과 값 : ".$decryptedData;



아래처럼 함수화해두면 쓰기 편하다.


$key = "1dasd12WESA12dsaasd456TGDFsd";


function function_for_encryption($plain_data){

 global $key;

 $encrypted_data_on_binary = mcrypt_ecb (MCRYPT_SERPENT, $key, $plain_data, MCRYPT_ENCRYPT);

 $encrypted_data = base64_encode($encrypted_data_on_binary);

 return $encrypted_data;

}

function function_for_decryption($encrypted_data){

 global $key;

 $decrypted_data_on_binary = base64_decode($encrypted_data);

 $plain_data = mcrypt_ecb (MCRYPT_SERPENT, $key, $decrypted_data_on_binary, MCRYPT_DECRYPT);

 return $plain_data;

}

profile
profile

title: MoonBlonix

2017.08.30 18:26
*.64.228.3

AES128/256 암호화/복호화 코드



<?
########   암호화 함수  ############################################
$strAESKey128 = "zKx^IcOo12345678";  // 16자리
$strAESKeyIV = str_repeat(chr(0), 16); #Same as in JAVA  16자리

function AES_Encode128($plain_text)
{
    global $strAESKey128, $strAESKeyIV;
    return strtoupper(bin2hex(openssl_encrypt($plain_text, "aes-128-cbc", $strAESKey128, true, $strAESKeyIV)));
}

function AES_Decode128($base64_text)
{
    global $strAESKey128, $strAESKeyIV;
    return openssl_decrypt(hex2bin($base64_text), "aes-128-cbc", $strAESKey128, true, $strAESKeyIV);
}

if ( !function_exists( 'hex2bin' ) ) {
 function hex2bin($hexdata) {
  $bindata = '';

  for ($i = 0; $i < strlen($hexdata); $i += 2) {
   $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
  }
  return $bindata;
 }
}


#############################################################

#  PHP 5.2 이하 버젼 openssl 미지원시 mcrypt 사용버젼 : 
function encrypt ($value)
{                
    global $strAESKey128, $strAESKeyIV;
    $padSize = 16 - (strlen ($value) % 16) ;
    $value = $value . str_repeat (chr ($padSize), $padSize) ;
    $output = mcrypt_encrypt (MCRYPT_RIJNDAEL_128, $strAESKey128, $value, MCRYPT_MODE_CBC, str_repeat(chr(0),16)) ;                
    return strtoupper(bin2hex ($output)) ;        
}

function decrypt ($value)        
{                     
    global $strAESKey128, $strAESKeyIV;
    $value = hex2bin($value) ;                
    $output = mcrypt_decrypt (MCRYPT_RIJNDAEL_128, $strAESKey128, $value, MCRYPT_MODE_CBC, str_repeat(chr(0),16)) ;                
    
    $valueLen = strlen ($output) ;
    if ( $valueLen % 16 > 0 )
        $output = "";

    $padSize = ord ($output{$valueLen - 1}) ;
    if ( ($padSize < 1) or ($padSize > 16) )
        $output = "";                // Check padding.               

    for ($i = 0; $i < $padSize; $i++)
    {
        if ( ord ($output{$valueLen - $i - 1}) != $padSize )
            $output = "";
    }
    $output = substr ($output, 0, $valueLen - $padSize) ;

    return $output;        
}

?>










if ( !function_exists( 'hex2bin' ) ) {
 function hex2bin($hexdata) {
  $bindata = '';

  for ($i = 0; $i < strlen($hexdata); $i += 2) {
   $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
  }
  return $bindata;
 }
}
#############################################################


function encrypt ($value)
{                
    global $strAESKey128, $strAESKeyIV;
    $padSize = 16 - (strlen ($value) % 16) ;
    $value = $value . str_repeat (chr ($padSize), $padSize) ;
    $output = mcrypt_encrypt (MCRYPT_RIJNDAEL_128, $strAESKey128, $value, MCRYPT_MODE_CBC, str_repeat(chr(0),16)) ;                
    return strtoupper(bin2hex ($output)) ;        
}

function decrypt ($value)        
{                     
    global $strAESKey128, $strAESKeyIV;
    $value = hex2bin($value) ;                
    $output = mcrypt_decrypt (MCRYPT_RIJNDAEL_128, $strAESKey128, $value, MCRYPT_MODE_CBC, str_repeat(chr(0),16)) ;                
    
    $valueLen = strlen ($output) ;
    if ( $valueLen % 16 > 0 )
        $output = "";

    $padSize = ord ($output{$valueLen - 1}) ;
    if ( ($padSize < 1) or ($padSize > 16) )
        $output = "";                // Check padding.               

    for ($i = 0; $i < $padSize; $i++)
    {
        if ( ord ($output{$valueLen - $i - 1}) != $padSize )
            $output = "";
    }
    $output = substr ($output, 0, $valueLen - $padSize) ;

    return $output;        
}














<?php
/*
 http://www.imcore.net | hosihito@gmail.com
 Developer. Kyoungbin Lee
 2012.09.07

 AES256 EnCrypt / DeCrypt
*/

###  256  ##################################################################################

$key = 'abcdefghijklmnopqrstuvwxyz123456';   // 32


function AES_Encode256($plain_text)
{
    global $key;
    return base64_encode(openssl_encrypt($plain_text, "aes-256-cbc", $key, true, str_repeat(chr(0), 16)));
}

function AES_Decode256($base64_text)
{
    global $key;
    return openssl_decrypt(base64_decode($base64_text), "aes-256-cbc", $key, true, str_repeat(chr(0), 16));
}
echo $kk = AES_Encode256('imcore.net');
echo AES_Decode256($kk);



###  128  ##################################################################################

$key = 'z=123+42#2@#$^*K';  //16


function AES_Encode128($plain_text)
{
    global $key;
    return base64_encode(openssl_encrypt($plain_text, "aes-128-cbc", $key, true, str_repeat(chr(0), 16)));
}

function AES_Decode128($base64_text)
{
    global $key;
    return openssl_decrypt(base64_decode($base64_text), "aes-128-cbc", $key, true, str_repeat(chr(0), 16));
}

echo $kk = AES_Encode128('imcore.net');
echo AES_Decode128($kk);


//  get 파라메터 사용시 깨질 경우  urlencode 해줌.  or  bin2hex hex2bin 사용

    return bin2hex(openssl_encrypt($plain_text, "aes-128-cbc", $key, true, str_repeat(chr(0), 16)));

    return openssl_decrypt(hex2bin($base64_text), "aes-128-cbc", $key, true, str_repeat(chr(0), 16));  //

 // hex2bin 함수 PHP >= 5.4.0  이상 지원  아래에서는

function hex2bin($hexdata) {
 // PHP >= 5.4.0  이상에 지원 - 삭제
 $bindata = '';

 for ($i = 0; $i < strlen($hexdata); $i += 2) {
  $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
 }

 return $bindata;
}


 

?> 

profile

title: MoonBlonix

2017.08.30 18:50
*.64.228.3

openssl_encrypt

1
string openssl_encrypt ( string $data , string $method , string $password [, int $options = 0 [, string $iv = "" ]] )

openssl_decrypt

1
string openssl_decrypt ( string $data , string $method , string $password [, int $options = 0 [, string $iv = "" ]] )

예제 소스

1
2
3
4
5
6
7
8
9
10
11
$data = "가나다라마바사";
$crypt_pass = "abcdefghij123456"; // 16자리
$crypt_iv = "abcdefghij123456"; // 16자리
// 암호화
$endata = @openssl_encrypt($data , "aes-128-cbc", $crypt_pass, true, $crypt_iv);
$endata = base64_encode($endata);
echo "ENCODE DATA : " . $endata . "<br>";
// 복호화
$data = base64_decode($endata);
$endata = @openssl_decrypt($data, "aes-128-cbc", $crypt_pass, true, $crypt_iv);
echo "DECODE DATA : " . $endata . "<br>";

crypt_iv는 랜덤출력을 위한 시드값인 셈이다.

crypt_key는 말그대로 키값 


결과 출력

1
2
ENCODE DATA : ypNDtWwSkJqS5hSXiI8ctSstbfj37ral3T2EkHwgfzQ=
DECODE DATA : 가나다라마바사

$method

  • AES-128-CBC
  • AES-128-CFB
  • AES-128-CFB1
  • AES-128-CFB8
  • AES-128-ECB
  • AES-128-OFB
  • AES-192-CBC
  • AES-192-CFB
  • AES-192-CFB1
  • AES-192-CFB8
  • AES-192-ECB
  • AES-192-OFB
  • AES-256-CBC
  • AES-256-CFB
  • AES-256-CFB1
  • AES-256-CFB8
  • AES-256-ECB
  • AES-256-OFB
  • BF-CBC
  • BF-CFB
  • BF-ECB
  • BF-OFB
  • CAST5-CBC
  • CAST5-CFB
  • CAST5-ECB
  • CAST5-OFB
  • DES-CBC
  • DES-CFB
  • DES-CFB1
  • DES-CFB8
  • DES-ECB
  • DES-EDE
  • DES-EDE-CBC
  • DES-EDE-CFB
  • DES-EDE-OFB
  • DES-EDE3
  • DES-EDE3-CBC
  • DES-EDE3-CFB
  • DES-EDE3-OFB
  • DES-OFB
  • DESX-CBC
  • IDEA-CBC
  • IDEA-CFB
  • IDEA-ECB
  • IDEA-OFB
  • RC2-40-CBC
  • RC2-64-CBC
  • RC2-CBC
  • RC2-CFB
  • RC2-ECB
  • RC2-OFB
  • RC4
  • RC4-40
  • aes-128-cbc
  • aes-128-cfb
  • aes-128-cfb1
  • aes-128-cfb8
  • aes-128-ecb
  • aes-128-ofb
  • aes-192-cbc
  • aes-192-cfb
  • aes-192-cfb1
  • aes-192-cfb8
  • aes-192-ecb
  • aes-192-ofb
  • aes-256-cbc
  • aes-256-cfb
  • aes-256-cfb1
  • aes-256-cfb8
  • aes-256-ecb
  • aes-256-ofb
  • bf-cbc
  • bf-cfb
  • bf-ecb
  • bf-ofb
  • cast5-cbc
  • cast5-cfb
  • cast5-ecb
  • cast5-ofb
  • des-cbc
  • des-cfb
  • des-cfb1
  • des-cfb8
  • des-ecb
  • des-ede
  • des-ede-cbc
  • des-ede-cfb
  • des-ede-ofb
  • des-ede3
  • des-ede3-cbc
  • des-ede3-cfb
  • des-ede3-ofb
  • des-ofb
  • desx-cbc
  • idea-cbc
  • idea-cfb
  • idea-ecb
  • idea-ofb
  • rc2-40-cbc
  • rc2-64-cbc
  • rc2-cbc
  • rc2-cfb
  • rc2-ecb
  • rc2-ofb
  • rc4
  • rc4-40

$password

  • The password.

$options

  • options is a bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.

$iv

  • A non-NULL Initialization Vector.
profile

title: MoonBlonix

2017.09.03 23:32
*.64.228.3

AES-128의 경우 암호화 블럭사이즈가 16byte 이다.

-> 16byte 아래 크기의 원문을 암호화하면 16byte 결과가 나오고, 32byte 이하의 원문은 32byte 결과, 이런식으로 16byte씩 커진다.

-> 물론 base64로 추가 인코딩시 길이는 더 길어진다. 32 -> 44 

List of Articles
번호 제목 글쓴이 날짜 조회 수
공지 [Web] 클라우드 IDE + 2 title: MoonBlonix 2017-06-25 15124
112 [jQuery] Ajax 옵션 설명 title: MoonBlonix 2017-09-15 1441
111 [jQuery] 페이지 부분 새로고침 + 1 title: MoonBlonix 2017-09-13 1126
110 정규표현식 분석 + 1 title: MoonBlonix 2017-09-12 1087
109 [php/mysql] 모든 uft-8 한글 인코딩 문제 title: MoonBlonix 2017-09-12 1497
» [php] AES / mcrypt 양방향 대칭키 암호화/복호화 + 3 title: MoonBlonix 2017-08-28 1238
107 [php/jQuery/Ajax] 파일 업로드 구현 title: MoonBlonix 2017-08-28 1462
106 [jQuery] ajax 사용 기초 title: MoonBlonix 2017-08-19 1461
105 [php] 서버 용량 구하기 title: MoonBlonix 2017-08-15 1353
104 [jQuery] 레이어 팝업 title: MoonBlonix 2017-08-15 1489
103 [php/jQuery] 선택된 다수의 체크박스 값 넘기기 / 체크박스 제어 + 2 title: MoonBlonix 2017-08-15 1475
102 [mysql] 저장 프로시저 / 저장 함수 / 트리거 title: MoonBlonix 2017-08-15 1511
101 [mysql] 저장엔진 title: MoonBlonix 2017-08-15 1472
100 [mssql / mysql] sql 트랜잭션(Transaction) + 1 title: MoonBlonix 2017-08-14 1507
99 [mysql] mysqli_fetch_row() mysqli_fetch_assoc() mysqli_fetch_array() 차이 title: MoonBlonix 2017-08-08 1482
98 [javascript/jQuery] Ajax의 흐름과 예제 title: MoonBlonix 2017-08-05 1539
97 [web] html 게시글 에디터 title: MoonBlonix 2017-08-05 1456
96 [mysql] JOIN 쿼리 사용하기 title: MoonBlonix 2017-08-05 1458
95 [mysql] 인덱스 (Index) 사용 방법 및 설명 + 2 title: MoonBlonix 2017-08-05 1716
94 [mysql] TEXT 타입, INT 타입 title: MoonBlonix 2017-08-05 1516
93 [mysql] 성능 향상 전략 + 4 title: MoonBlonix 2017-08-05 1467