달력

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

 


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

http://suite.tistory.com 2013.06 fs

 

openssl 라이브러리 함수 이용하여 aes cbc 함수 샘플 작성해봄

 

1. openssl 최신버전 2013.06 기준 다운로드

$>wget http://www.openssl.org/source/openssl-1.0.1e.tar.gz

 

2. 압축 풀기

$>tar fxz openssl-1.0.1e.tar.gz

 

3. libcrypto.a 생성 


$>cd openssl-1.0.1e;make
-> $> ls 해서 libcrypto.a 파일 확인

 

4. openssl-1.0.1e/apps/speed.c 참고해서

 

build :  $>gcc fs_aes_cbc.c libcrypto.a

 

 

 

/* ================================================================================ OpenSSL 1.0.1e 11 Feb 2013 Copyright (c) 1998-2011 The OpenSSL Project Copyright (c) 1995-1998 Eric A. Young, Tim J. Hudson All rights reserved. DESCRIPTION ----------- The OpenSSL Project is a collaborative effort to develop a robust, commercial-grade, fully featured, and Open Source toolkit implementing the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols as well as a full-strength general purpose cryptography library. The project is managed by a worldwide community of volunteers that use the Internet to communicate, plan, and develop the OpenSSL toolkit and its related documentation. OpenSSL is based on the excellent SSLeay library developed from Eric A. Young and Tim J. Hudson. The OpenSSL toolkit is licensed under a dual-license (the OpenSSL license plus the SSLeay license) situation, which basically means that you are free to get and use it for commercial and non-commercial purposes as long as you fulfill the conditions of both licenses. ================================================================================ * aes_cbc() mode sample by openssl * openssl : wget http://www.openssl.org/source/openssl-1.0.1e.tar.gz * reference source : openssl-1.0.1e/apps/speed.c * build : $>gcc test_fs_aes_cbc.c libcrypto.a * copyleft @http://suite.tistory.com fs */ #include <stdio.h> #include <string.h> #include <openssl/aes.h>
  
 static const unsigned char key32[32]=
{0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,
0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12,
0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12,0x34,
0x78,0x9a,0xbc,0xde,0xf0,0x12,0x34,0x56};
#define BLOCK_SIZE 16
#define FREAD_COUNT 4096
#define KEY_BIT 256
#define IV_SIZE 16
#define RW_SIZE 1
#define SUCC 0
#define FAIL -1

AES_KEY aes_ks3;
unsigned char iv[IV_SIZE];

int fs_encrypt_aes(char *in_file,char *out_file)
{
    int i=0;
    int len=0;
    int padding_len=0;
    char buf[FREAD_COUNT+BLOCK_SIZE];

    FILE *fp=fopen(in_file,"rb");
    if( fp == NULL ){
        fprintf(stderr,"[ERROR] %d can not fopen('%s')\n",__LINE__,in_file);
        return FAIL;
    }

    FILE *wfp=fopen(out_file,"wb");
    if( wfp == NULL ){
        fprintf(stderr,"[ERROR] %d can not fopen('%s')\n",__LINE__,out_file);
        return FAIL;
    }

    memset(iv,0,sizeof(iv)); // init iv
    AES_set_encrypt_key(key32 ,KEY_BIT ,&aes_ks3);
    while( len = fread( buf ,RW_SIZE ,FREAD_COUNT, fp) ){
        if( FREAD_COUNT != len ){
            break;
        }

        AES_cbc_encrypt(buf ,buf ,len ,&aes_ks3 ,iv ,AES_ENCRYPT);
        fwrite(buf ,RW_SIZE ,len ,wfp);
    }


    // padding  : pkcs5? pkcs7?? http://wiki.dgoon.net/doku.php?id=ssl:pkcs_5
    padding_len=BLOCK_SIZE - len % BLOCK_SIZE;
    printf("enc padding len:%d\n",padding_len);
    memset(buf+len, padding_len, padding_len);
/**
    for(i=len; i < len+padding_len ;i++){
        buf[i]=padding_len;
    }
**/
    AES_cbc_encrypt(buf ,buf ,len+padding_len ,&aes_ks3, iv,AES_ENCRYPT);
    fwrite(buf ,RW_SIZE ,len+padding_len ,wfp);

    fclose(wfp);
    fclose(fp);

    return SUCC;
}

int fs_decrypt_aes(char *in_file,char *out_file)
{
    char buf[FREAD_COUNT+BLOCK_SIZE];
    int len=0;
    int total_size=0;
    int save_len=0;
    int w_len=0;

    FILE *fp=fopen(in_file,"rb");
    if( fp == NULL ){
        fprintf(stderr,"[ERROR] %d can not fopen('%s')\n",__LINE__,in_file);
        return FAIL;
    }

    FILE *wfp=fopen(out_file,"wb");
    if( wfp == NULL ){
        fprintf(stderr,"[ERROR] %d can not fopen('%s')\n",__LINE__,out_file);
        return FAIL;
    }

    memset(iv,0,sizeof(iv)); // the same iv
    AES_set_decrypt_key(key32 ,KEY_BIT ,&aes_ks3);

    fseek(fp ,0 ,SEEK_END);
    total_size=ftell(fp);
    fseek(fp ,0 ,SEEK_SET);
    printf("total_size %d\n",total_size);

    while( len = fread( buf ,RW_SIZE ,FREAD_COUNT ,fp) ){
        if( FREAD_COUNT == 0 ){
            break;
        }
        save_len+=len;
        w_len=len;

        AES_cbc_encrypt(buf ,buf ,len ,&aes_ks3 ,iv ,AES_DECRYPT);
        if( save_len == total_size ){ // check last block
            w_len=len - buf[len-1];
            printf("dec padding size %d\n" ,buf[len-1]);
        }

        fwrite(buf ,RW_SIZE ,w_len ,wfp);
    }

    fclose(wfp);
    fclose(fp);

    return SUCC;
}
//copyleft @http://suite.tistory.com fs
int main(int argc, char *args[])
{
    if( argc != 2 ){
        printf("[Usage] %s fs_src_file\n",args[0]);
        return FAIL;
    }


    if( fs_encrypt_aes(args[1],"fs_in.file") == SUCC){
        fs_decrypt_aes("fs_in.file","fs_out.file");
        printf("result:[fs_out.file]\n");
    }

    return 0;
}

 

* 실행 결과

  
$ vi fs_aes_cbc.c
$ make
gcc fs_aes_cbc.c libcrypto.a
$ ./a.out fs_aes_cbc.c
result:[out.file]
$ ls -ltr
합계 11512
-rw-rw-r--. 1 ir ir 3914268 2013-05-31 17:03 libcrypto.a
-rw-rw-r--. 1 ir ir      36 2013-06-04 15:10 Makefile
-rw-rw-r--. 1 i ir   2979 2013-06-04 15:10 fs_aes_cbc.c
-rwxrwxr-x. 1 ir i   23698 2013-06-04 16:21 a.out
-rw-rw-r--. 1 i ir    2992 2013-06-04 16:21 fs_in.file
-rw-rw-r--. 1 irtu irt   2979 2013-06-04 16:21 fs_out.file

실제 업무에서는 C++ 기반이면 class화 사용이 BEST!

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

* 참고 링크 :  http://misc-file.googlecode.com/svn/vm/aes_cbc_encrypt.cpp

 

* EVP? : openssl 암호화 관련 검색을 계속 해보면  EVP 관련 함수로 암호화 함수가 있다.

EVP 무슨약자인지는 찾지 못했고  "하이레벨 함수들" :  http://www.openssl.org/docs/crypto/evp.html

fs/openssl-1.0.1e/test/evp*.c 보면

EVP_CIPHER_CTX_init() , EVP_EncryptUpdate() , EVP_EncryptFinal()  이용해서 암호화 알고리즘을 적용 하는 예제가 있음 

 

 

 

 

 

 

:
Posted by mastar

http://suite.tistory.com 2013.06 fs

 

그동안 인코딩 관련해서 base64, urlencode, md5 나 경험하다가 

 

암호화 Algorithm (알고리즘? 알고리듬?) 개발은 아니고 

openssl 라이브러리를 사용해보기 위해  학습해 보았다.

구글링을 문서가 참 많은데 쭉~해오던게 아니니 생소한 용어를 많이 봄.

 그냥 개인적으로 양파 까듯이 개념 정리해봄(블로그/구글링 웹문서 참고)

 

1.  대칭형 암복호화 (AES,DES,SEED... 방식)

     암호화/복호화시 key가 동일한 형태  


 

2. 비대칭형 암복호화 (RSA...방식)

    암호화/복호화시 서로 다른 key를 사용한 형태

 

3. RSA (Ron Rivest, Adi Shamir,Leonard Adleman ) 1977년 만든 3사람 이름 약자

     소수를 이용하여 만든 Algorithm 공개되어 있지만  취약성이 아주 많이 없어 아주 많이 사용됨

      설명은 아래 링크 참고 :

http://kin.naver.com/qna/detail.nhn?d1id=11&dirId=11080102&docId=49010517&qb=cnNhIOqzteqwnCDtgqQg7JWU7Zi4IOuwqeyLnQ==&enc=utf8&section=kin&rank=2&search_sort=0&spq=0

 

4. DES(Data Encryption Standard)

    미국에서 예전에 표준으로 쓰던 암호화로 현재는 AES로 대체되어 사용 안한다고 함

 

5. AES (Advanced Encryption Standard)    1997년 9월 공모 2001년12월부터 AES 표준화 완료

   미국에서 DES 대체 방식으로 공모함 

   그중에 벨기에 수학자(Daemen과 Rijndael)이 만든  Rijndael 이 채택되어 구현됨

   * Rijndael 정확한 발음 모르겠음 (레인달, 라인댈,라인달...)

 

   KEY는 128bit, 192bit, 256bit 사용 가능하고 이론적으로는 key 길이는 무제한 이라고함

    KEY크기가 128bit(16byte) 면 Algorithm에 따라 라운드?를 9회 , 192bit(24byte) 11회 , 256bit(32byte) 13회 한다고하니

    키가 길면 좀더 암호화가 되고 시간?도 좀더 걸리는것 으로 예상됨    

 

6. SEED , ARIA

    한국에서 만든 암호화 암고리듬 , ARIA경우 우리나라 공공기관 및 산하기관 거의 표준으로 들어가야 하는데

   최소 한 1년정도 검증기간이 소요예상(카더라통신) ,  프로젝트 상황에 따라 국내 상용제품을 구매가 나을 듯

 

7. 블럭암호화

    AES 알아 보다 보면 블럭암호화가 나오고 ECB , CBC... 모드가 나온다.

    블럭암호화: 임의의 평문을 암호화하기 위해서 일정한 길이로 나눠서 하는거 

    ex)  기본 데이터 블럭은 16byte

 

   ECB (Electric CodeBook mode)  : 모든 글들이 비추천 사용하지 말라는 모드임 

   16byte 블럭단위가 동일키로 암호화 하는구조

    -> 평문이 같다면 암호화 블럭도 일정해진다.

    * 스트림 암호화 방식도 있다 1byte씩

 

 

    CBC(Cipher Block Chaining mode)  : 모든 글들이 권장모드 , 적극 사용 하라는 모드임

    ECB와 달리 IV를 활용하여 처음블럭이 다음 암호화 블럭에 영향을준다.
   -> 평문이 같아도 암호화 블럭이 달라진다.

   ECB vs CBC 비교 좋은 링크 : http://blog.naver.com/PostView.nhn?blogId=taketime62&logNo=90043063571 

   이외 좀 더 있다 (CFB,OFB,CTR)

 

8. IV (initialization vector) : 초기화백터?

   CBC 모드 알아 보다 보면 16byte 크기가 IV가 있다

   KEY와는 다르고 CBC 모드에서 체인형식으로 앞블럭 뒤에 블럭 영향을 주도록 하는것 같다.

   IV값은 처음 시작할때 값과 암호화후 값을 보면 달라진다.

 

  주의할점은 IV 값을 복호화시에 반드시 최초값과 동일하게 해야함

   ex) IV 값을 0으로 암호화 시작했다면 , 복호화시에 IV 값을 0으로 해야한다.

  -> 어떻게 보면 기본 key 값에 또 하나의 2중 key 값이라고도 할수 있다고 개인적으로 생각

 

9. 패딩 (padding)

   블럭단위로 암호화시 분명 소스 데이타가 블럭길이가 딱 맞지 않을 수 있다.

   그걸경우 마지막 블럭도 단위에 맞게 패딩(추가Byte)을 해서 블럭을 맞게 해준다.

   openssl - AES_cbc_encrypt() 에서 패딩도 해주면 좋았을텐데 안해줘서

   구글링해서 좋은 글을 찾았다.

   http://wiki.dgoon.net/doku.php?id=ssl:pkcs_5

   패딩글을 보다보면 PKCS5 PKCS7 나온다.  

 

10. 메시지 다이제스트(Message Digest)

   원문에서 일정한 길이로 문자열을 변환해주는거(해쉬함수) 

   복호화는 없다고 봐야하는데~ MD5 경우 텍스트경우 좀 됨 (인터넷에 변환사이트 많음)

   보통 사용자 암호저장시 활용

   MD5 , SHA 요즘은 MD5 보완취약하다고 SHA-1 이상 방식 권장 한다고함  

 

11. KMS(Key Management Server)

   KMS 용어 참많다!  암호화에서는 full name 그대로 암호화 key를  관리하는 서버

 

12. openssl (http://www.openssl.org/)

   오픈소스로 여러가지 암호화(인코딩)/복호화(디코딩) Algorithm을 착한분들이  c 라이브로로 만들어줌

   다음 포스트에 openssl - libcrypto.a 활용한

   AES  256 CBC모드 함수 AES_cbc_encrypt()  샘플

-> http://suite.tistory.com/entry/AES-암호화-crypto-cbc-모드-샘플-by-openssl


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

* 관련해서 많이본 포스팅  작성자분에게 감사합니다.  (펌글이라면 출처를 넣어주는 센스가...)

http://www.parkjonghyuk.net/lecture/modernCrypto/lecturenote/chap04.pdf 

http://blog.daum.net/thermidor/8933157

http://linuxforge.tistory.com/191

http://www.cyworld.com/duetys/14268419

https://www.google.co.kr/search?newwindow=1&noj=1&q=PKCS5Padding&spell=1&sa=X&ei=0EOrUervBYqXkQX87IHwBw&ved=0CCoQBSgA&biw=1440&bih=766

http://thenine.egloos.com/321704

http://www.di-mgt.com.au/cryptopad.html

http://blog.naver.com/PostView.nhn?blogId=hyoguri81&logNo=150098915801

http://blog.naver.com/PostView.nhn?blogId=taketime62&logNo=90043063571 

http://wiki.dgoon.net/doku.php?id=ssl:pkcs_5

http://www.eglobalsys.co.kr/sub2/06.php

http://blog.naver.com/imchan123?Redirect=Log&logNo=10168165622

http://kin.naver.com/qna/detail.nhn?d1id=11&dirId=11080102&docId=49010517&qb=cnNhIOqzteqwnCDtgqQg7JWU7Zi4IOuwqeyLnQ==&enc=utf8&section=kin&rank=2&search_sort=0&spq=0

http://blog.naver.com/typeofb?Redirect=Log&logNo=166253556

http://andstory.com/zb41/zboard.php?id=tip_board&page=18&sn1=&divpage=1&sn=off&ss=on&sc=on&select_arrange=headnum&desc=desc&no=490

 

 

 

:
Posted by mastar

http://suite.tistory.com 2011.10

static 한 실행파일만 gdb로 디버깅해보다가 
dynamic 실행시 디버깅 방법 구글링좀하고 정리해둠~~
(데몬형태로 so 파일을 활용한 프로그램이  있을경우 디버깅  방법)

그냥 단순 예제로 tail 일경우 실제로는 디버깅할 프로세스명 사용!!!

ex)  특정 로그를 볼때 자주쓰는 tail -f 파일명.log 해두고

$]tail -f   Server.log

먼저 프로세스 번호 찾고
$) ps -ef |grep tail
18588 18560  0 17:20 pts/3    00:00:00 tail -f Server.log
19983 17905  0 18:44 pts/1    00:00:00 grep tail

gdb 실행후 실행프로세 디버깅 시작(attach)
$)gdb  tail
$)attach 18588
또는 한방에 $) gdb tail 18588

아래와같이 참조된 so 가 나오고
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
gdb tail 18588
GNU gdb Red Hat Linux (6.3.0.0-1.159.el4rh)
Copyright 2004 Free Software Foundation, Inc.
to program: /usr/bin/tail, process 18588
Reading symbols from /lib/tls/i686/nosegneg/libm.so.6...(no debugging symbols found)...done.
Loaded symbols for /lib/tls/i686/nosegneg/libm.so.6
Reading symbols from /lib/tls/i686/nosegneg/librt.so.1...(no debugging symbols found)...done.
Loaded symbols for /lib/tls/i686/nosegneg/librt.so.1

...............
Loaded symbols for /lib/tls/i686/nosegneg/libpthread.so.0
0x009af7a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 (gdb) b write
Breakpoint 1 at 0xb9c6b0

(gdb) continue

중지하고 다시 설정 할려면

(gdb) ctrl + c 하고 
source.cpp 에 77라인 브레이크 포인트 걸때 
(gdb)  b source.cpp:77
(gdb) continue
다음 n , s , p 등.. 디버깅 수행

뭐 이렇게하면 tail은 단순예이고 실제 개발한 so 파일이나  유지보수를 위해 실행하면서 소스 분석시 활용 가능함


 

 

:
Posted by mastar

http://suite.tistory.com/  fs 2010 01 

가. 도미노 6.5 버전대에 C++ 로 툴킷이 없는건지 컴파일을 못한건지해서  --;
아마 C++ 로 했다면 일반 DIIOP 방식과 비슷해서 개발은 양호할것으로 생각됨~~~

어찌되었든 C 버전으로  IBM사이트에서 무료로 제공해주는 툴킷(C10QYEN.tar.Z)에있는 샘플로 테스트 해보았다.

일반 필드 출력 , 내용출력(mime,등) ,
첨부파일 다운로드?(로컬에저장)  (<- 이건 툴킷에 샘플이 없어서 중국어느 사이트 참고
                                                참고 중국사이트 : http://topic.csdn.net/t/20040609/10/3076169.html

나. 도미노가 설치된 서버에서  수정한 툴킷 샘플은

/notesapi/samples/misc/nsf_dump

수정 예제 및 Makefile ( solrais gcc version ) :

Makefile

                                                                  

nsf_dump.c

 
                                                             
주요 함수 사용함수는 NSFSearch , NSFItemScan , NSFDbInfoParse , NSFNoteExtractFile ( 파일 다운로드 )  


다. UniversalID  - UNID  가져오기

C sample

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

sprintf(UNID,"%08x%08x%08x%08x",SearchMatch.OriginatorID.File.Innards[1],SearchMatch.OriginatorID.File.Innards[0],
                        SearchMatch.OriginatorID.Note.Innards[1],SearchMatch.OriginatorID.Note.Innards[0]);

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C++ sample
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DWORD a=unid->File.Innards[0];
   DWORD b=unid->File.Innards[1];
   //printf("aaaa1:%x," , a);
   //printf("aaaa2:%x\n" , b);

   cout.width(8);
   cout.fill('0');
   cout <<  hex <<b ;
   cout.width(8);
   cout.fill('0');
   cout<< hex<<toupper(a);

   a=unid->Note.Innards[0];
   b=unid->Note.Innards[1];
 
   cout <<  hex <<b;
   cout.width(8);
   cout.fill('0');
   cout<< hex<<toupper(a);

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


라.  도미노 연계시에는

DIIOP(JAVA) > C++ API (함수prefix LN*)  > C API (함수prefix NSF*)

좋아보임 (C API로 세그먼트 뽈트 에러나면 도미노 죽어버림 ~.~)

아래 참고 C, C++ 차이 링크 원본 : 
http://lotusdesk.blogspot.com/2009/11/differences-between-lotus-notes-c-api.html


Differences between Lotus Notes C API and C++ API

We always have few options if we need to do with Lotus Notes something externally. Here I'll try to provide a brief comparison chart of Lotus Notes CAPI and CppAPI. I hope this brochure can help to do the right choice before going deep into the water.

 

Lotus Notes CAPI
Lotus Notes CppAPI
Complex code, requires high attention during development because it works with raw memory pointers. So without experience it's very easy to produce memory leaks and access violations.
Simple code, it's very similar to Lotus Script and Java APIs.
Procedural code.
Object oriented code.
Notes uses it internally, so no dependency files required to install.
CppAPI requires lcppnXX.dll, there XX is a version of CppAPI. While this dll has versioning info most functionality is compatible across Lotus Notes versions. So lcppn70.dll is working with Lotus Notes 6.5 and Lotus Notes 8.5.1 Standard.
Can be coded anything so it can work much like it was a built-in feature of Lotus Notes.
There are limitations introduced by CppAPI implementation. It's obvious because CppAPI built on CAPI. In most cases it's the same limitations as in LotusScript or Java API. So if you can't do something in LotusScript and you like to move to a lower level than CppAPI is not your option. A good example of such limitations is a memo with attachment. While it's only few lines of code using CppAPI, this memo doesn't look good in Notes because there is no icon thumbnail, just a gray rectangle. With CAPI there will be 300-400 lines of code to add an attachment and to represent it as an icon inside of memo body. It's complex, but memo will look like the one created in Lotus Notes by a real user.
Strings represented in form of special LN Multibyte string (LMBCS). While in the code it looks like a normal ANSI string of type "char *" it can contain zeros inside and encoded non ANSI symbols. It's very easy to miss a large part of text and break international symbols if you apply standard C functions like strcat or strcpy. I'll write in the next post how to work with Lotus strings in CAPI to preserve international symbols and handle zeros in the middle of the string.
LNString class handles lotus strings just perfect. It has methods for string concatenation, searches, substring extraction, etc. It can return a pointer to the platform one byte character set encoding of the string. However it's still better to convert LMBCS to Unicode if you need to pass it outside of Lotus, and it's missing in CppAPI.

Here is a sample code of the same functionality in Lotus CAPI and CppAPI. The code opens Lotus database.

void CppApiCode()
{
 LNNotesSession session;
 session.Init();
 LNString databasePath = "special\\testdb.nsf";
 LNString serverPath;
 LNDatabase docDB;
 session.GetDatabase(databasePath, &docDB, serverPath);
 // Open the database.
 docDB.Open();
 ...
 docDB.Close();
}

void CApiCode()
{
 STATUS error = NotesInitExtended();
 DBHANDLE hDB = 0;
 char szFileName[] = "special\\testdb.nsf";
 char szServerName[] = "";
 char szDbPath[MAXPATH+1];
 error = OSPathNetConstruct(0, szServerName, szFileName, szDbPath);
 // Open the database.
 error = NSFDbOpen(szDbPath, &hDB);
 ...
 NSFDbClose(hDB);
}



 
:
Posted by mastar

 2008 08 fs http://suite.tistory.com/

strcpy ( str , "" )  하고
strncpy(str,src,3) 해보니 안짤려진다~~

그래서 memset()으로 초기화하고  하니 잘된다~  

이제까지 strcpy(str,"") 하면 str에 전체가 '\0' 되는줄 알았다!  ~.~

첫배열에만 '\0' 이 들어가는거였음~~~ 

 

:
Posted by mastar

2008 08 fs~~   http://suite.tistory.com/
지역변수 사용후 스텍정리를 하다가 죽어서? 나오는에러 같다~ 변수 이름까지 잘찍어준다




코딩 에러 상황

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  char tmp_s[2];
  strcpy(lenth_2data,"12");
  strcpy(tmp_s,lenth_2data);//<- 여기서죽는다 두글자하고 + '\0' 만큼 하나더 늘려준다
  tmp_s[1]='\0';
  num=atoi(tmp_s);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
======>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  char tmp_s[3]; //
  strcpy(tmp_s,lenth_2data);
  tmp_s[1]='\0';
  num=atoi(tmp_s);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

변수 범위를 잘 확인하자~~

뭐이런 예말고 다른 상황에서도 잘 확인~

넘 기본이군~~~

 

:
Posted by mastar

by fs 2008 07 16

OS : HP 11.23

컴파일이  아래와 같은 메시지 제거는 환경 언어셋중 LC_ALL값을 넣어줘서 해결

"ld: One or more of your selected locales are not available. Continuing processing using the "C" locale."

before

#>locale
LANG=ko_KR.eucKR
LC_CTYPE="ko_KR.eucKR"
LC_COLLATE="ko_KR.eucKR"
LC_MONETARY="ko_KR.eucKR"
LC_NUMERIC="ko_KR.eucKR"
LC_TIME="ko_KR.eucKR"
LC_MESSAGES="ko_KR.eucKR"
LC_ALL=

after

#>export LC_ALL=ko_KR.eucKR
#>locale
LANG=ko_KR.eucKR
LC_CTYPE="ko_KR.eucKR"
LC_COLLATE="ko_KR.eucKR"
LC_MONETARY="ko_KR.eucKR"
LC_NUMERIC="ko_KR.eucKR"
LC_TIME="ko_KR.eucKR"
LC_MESSAGES="ko_KR.eucKR"
LC_ALL=ko_KR.eucKR

 

:
Posted by mastar

http://suite.tistory.com/

 2007 05 fs


서비스 등록 프로그램 중 중지 했지만 중지 되지 않고 서비스에서도 중지중이고  제거 되지 않을 경우

아래와같이 주먹구구식으로  프로세스  죽이는 소스 를 넣는다.

~~~~~~~~~~~~~~~~~~~~~~~

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

void MySetStatus_Pending(DWORD dwState, DWORD dwAccept)
{
 SERVICE_STATUS ss;

 ss.dwServiceType=SERVICE_WIN32_OWN_PROCESS;
 
    ss.dwCurrentState=dwState;
    ss.dwControlsAccepted=dwAccept;

 ss.dwWin32ExitCode=0;
 ss.dwServiceSpecificExitCode=0;
 ss.dwCheckPoint=0;
 ss.dwWaitHint=0;

 // 현재 상태를 보관해 둔다.
 g_NowState=dwState;
 SetServiceStatus(g_hSrv,&ss);
}

~~~~~~~~~~~~~~~~~~~~~~~

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


 case SERVICE_CONTROL_STOP:
   SC_HANDLE hScm, hSrv;
   SERVICE_STATUS ss;
   MySetStatus_Pending( SERVICE_CONTROL_STOP, 0);
   // SCM을 연다
   hScm=OpenSCManager(NULL,NULL, SC_MANAGER_CREATE_SERVICE );
   hSrv = OpenService( hScm, "SERVICE_NAME", SERVICE_ALL_ACCESS );
   QueryServiceStatus(hSrv,&ss);
   if (ss.dwCurrentState != SERVICE_STOPPED) {
      //프로세스 종료
     ControlService(hSrv,SERVICE_CONTROL_STOP,&ss);

     //또는 SERVICE_STOP_PENDING값을 이용하여 죽을때가지 기다려본다.
     Sleep(2000);

       

   }
 break;


~~~~~~~~~~~~~~~~~~~~~~~

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~



 

:
Posted by mastar

http://suite.tistory.com/  fs  2006 10 19


2004년 대학교 졸업  급조 논문? 프로그램
오라클 디비 검색과 (UDP이용)  파일전송 (TCP이용) 과 WIPI 모바일 소켓 연동 까지 하였다.


소스는 역시 학교 때 한거라 지저분 하지만 참고용으로 ^^;


OS: windows, wipi(Emulator)

언어: VC++ 6.0 ,Java(wipi)

DB: Oracle

사용자 삽입 이미지
사용자 삽입 이미지


 

 

 

 

 

 
 
 

:
Posted by mastar