2013. 7. 10. 18:53
[ 암호화 ] AES crypto ctr 모드 C 샘플 by openssl 용-ILE/LNAG-C/C++2013. 7. 10. 18:53
http://suite.tistory.com 2013.07 fs
패딩이 필요 없는 CTR 모드를
openssl(http://www.openssl.org/) 라이브러리 함수 이용하여
aes ctr 함수 [ AES_ctr128_encrypt() ] 샘플 작성해봄
참고 소스 링크
http://stackoverflow.com/questions/3141860/aes-ctr-256-encryption-mode-of-operation-on-openssl
참조 링크에서 다른점은 구현시 1024bytes 단위로 적용
openssl 라이브러리참조 빌드는 링크 참조 :
http://suite.tistory.com/entry/AES-암호화-crypto-cbc-모드-샘플-by-openssl
샘플 코드
#define BYTES_SIZE 1024 #define KEY_SIZE 128 unsigned char iv[8]={0x66,0x61,0x63,0x65,0x73,0x65,0x61,0x00}; struct ctr_state { unsigned char ivec[AES_BLOCK_SIZE]; unsigned int num; unsigned char ecount[AES_BLOCK_SIZE]; }; unsigned char ckey[] = "slrkrkfkgkdhkdld"; // It is 128bits though.. AES_KEY key; int init_ctr(struct ctr_state *state, const unsigned char iv[8]){ state->num = 0; memset(state->ecount, 0, AES_BLOCK_SIZE); memset(state->ivec+8 , 0, 8); memcpy(state->ivec, iv, 8); } // encrypt twice == decrypt void encrypt(unsigned char *indata,unsigned char *outdata ,int bytes_read){ int i=0; int mod_len=0; AES_set_encrypt_key(ckey, KEY_SIZE, &key); if( bytes_read < BYTES_SIZE){ struct ctr_state state; init_ctr(&state, iv); AES_ctr128_encrypt(indata, outdata, bytes_read, &key, state.ivec, state.ecount, &state.num); return; } // loop block size = [ BYTES_SIZE ] for(i=BYTES_SIZE; i <= bytes_read ;i+=BYTES_SIZE){ struct ctr_state state; init_ctr(&state, iv); AES_ctr128_encrypt(indata, outdata, BYTES_SIZE, &key, state.ivec, state.ecount, &state.num); indata+=BYTES_SIZE; outdata+=BYTES_SIZE; } mod_len = bytes_read % BYTES_SIZE; if( mod_len != 0 ){ struct ctr_state state; init_ctr(&state, iv); AES_ctr128_encrypt(indata, outdata, mod_len, &key, state.ivec, state.ecount, &state.num); } } int main(int argc, char *argv[]){ int i=0; unsigned char fs[]={"abcdefgh"}; printf("plain :[%s]\ne",fs); encrypt(fs ,fs ,8); printf("encode:[%s]\n",fs); encrypt(fs ,fs ,8); printf("decode:[%s]\n",fs); return 0; }
'용-ILE > LNAG-C/C++' 카테고리의 다른 글
[ 암호화 ] AES crypto cbc 모드 C 샘플 by openssl (0) | 2013.06.04 |
---|---|
[ 암호화 ] cipher 학습해 보면 이거 저거 용어 (대칭형,공개키,des,aes,cbc,iv..) 작성중... (0) | 2013.06.03 |
[gdb] shared-libraries so 공유 라이브러리 디버깅 attach 활용 (0) | 2011.10.27 |
[ 도미노 / 노츠 6.5.6 ] C API 텍스트 추출 샘플 (0) | 2010.01.27 |
[C - 당연한거 2] strcpy ( str , "" ) 하고 memset ( str , '\0',sizeof(SEC_TMP) ) (1) | 2008.08.26 |