달력

4

« 2024/4 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

'crypto ctr'에 해당되는 글 1

  1. 2013.07.10 [ 암호화 ] AES crypto ctr 모드 C 샘플 by openssl

 


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

 

샘플 코드

 

/** [AES KEY_SIZEbit - CTR MODE] implemented block 1024 bytes Reference source : http://stackoverflow.com/questions/3141860/aes-ctr-256-encryption-mode-of-operation-on-openssl Reference lib : openssl - libcrypto.a @copyleft http://suite.tistory.com fs 2013.07 **/ #include <openssl/aes.h> #include <stdio.h> #include <string.h> #include <stdlib.h>
#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;
}

 

 

 

 

 

:
Posted by mastar