Develop Note

X.509 인증서 파일을 문자열 값으로 변환하는 방법 본문

개발 (Ko)/Note

X.509 인증서 파일을 문자열 값으로 변환하는 방법

Chalsu 2022. 11. 24. 09:29

이 글에서 소개하는 내용은 Git Bash 또는 리눅스 환경에서 사용 가능하다.

 

개요

X.509 인증서 기반으로 장치를 클라우드에 연동하는 경우 C SDK를 사용할 때 인증서를 변수 값으로 코드에 포함시켜야 한다.

이 때 변수 형태는 다음과 같다.

uint8_t mqtt_root_ca[] =
"-----BEGIN CERTIFICATE-----\\r\\n"
"...\\r\\n"
"-----END CERTIFICATE-----\\r\\n";

인증서 파일을 열어보면 큰 따옴표와 \r\n을 포함하지 않기 때문에 이 부분에 대한 수정이 필요하다.

VS Code 등의 에디터로 일괄 편집 기능을 사용해 직접 작업해도 되지만, 보다 간단한 작업을 위해 아래 방법들을 사용할 수 있다.

  • 쉘 스크립트 사용
  • sed 사용

관련 내용은 아래 링크에서 참조했다.

 

기존 문서에서는 쉘 스크립트 사용하는 내용이 소개되어 있었는데, 문서가 업데이트 되면서 sed로 변경된 것으로 보인다.

 

참조: https://learn.microsoft.com/ko-kr/azure/iot-dps/tutorial-custom-hsm-enrollment-group-x509?tabs=windows&pivots=programming-language-ansi-c#configure-the-custom-hsm-stub-code

 

쉘 스크립트 사용

Vim으로 스크립트 파일(.sh)을 작성한다.

인증서 변환 스크립트 작성

$ vi convert_cert.sh

input=$1
bContinue=true
prev=
while $bContinue; do
    if read -r next; then
      if [ -n "$prev" ]; then
        echo "\\"$prev\\\\n\\""
      fi
      prev=$next
    else
      echo "\\"$prev\\";"
      bContinue=false
    fi
done < "$input"

 

스크립트 실행

스크립트에 실행 권한을 부여하고, 파라미터로 파일 경로를 주어 실행한다.

$ chmod +x convert_cert.sh
$ ./convert_cert.sh <Certificate path>

 

sed 커맨드 사용

sed는 특정 패턴을 사용하여 텍스트 값을 원하는 형태로 변환할 수 있게 도와주는 커맨드이다.

man 페이지에서 자세한 사용 방법을 확인할 수 있다.

NAME
       sed - stream editor for filtering and transforming text

SYNOPSIS
       sed [OPTION]... {script-only-if-no-other-script} [input-file]...

DESCRIPTION
       Sed  is a stream editor.  A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline).  While in some ways similar
       to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient.  But it is sed's ability
       to filter text in a pipeline which particularly distinguishes it from other types of editors.
...

다음 커맨드를 사용해 인증서를 변수 값으로 변환한다.

sed -e 's/^/"/;$ !s/$/\\\\n"/;;$ s/$/"/' AmazonRootCA1.pem

Comments