2016 암호여름학교 NIMS 
한참 재밌게 듣다가 갑자기 놓침....

Provable Security of Public-Key Cryptography

Aaram Yun, School of ECE, UNIST

Summary

  • '증명가능한 안전성', 즉 provable security는 80년대 중반에 Goldwasser와 Micali가 계산복잡도 이론에 근거해서 암호화 방식의 안전성을 엄밀하게 정의하고 이를 환원 증명을 통해 증명한 이후로 암호학적 설계에서 중요한 패러다임으로 자리 잡았고, 오늘날은 사실상 공개키 암호학의 거의 전 분야에서 요구되고 있다. 본 강의에서는 구체적인 예를 통해 증명가능한 안전성에 관해 설명하고자 한다. 특히, IND-CCA 안전성을 만족하는 최초의 효율적인 암호화 방식인 Cramer-Shoup의 안전성 증명을 자세히 살펴보도록 한다.

Provable Security?

A bit of History...

  • 1976 : Diffie & Hellman, "New direction in cryptography"
  • 1982 : Goldwasser & Micali, "Probabilistic encryption and how to play mental poker, keeping secret all partial information", STOC 1982
    • Turing award for 2012

Provable security

Goldwasser & Micali

Why proof?

  • Else, how can we be sure nobody learned anyting from what they have eavesdropped?
  • or, how do you know that nothing happened?

Unconditionally?

  • Bad new: currently, we don't know how to design a cryptosystem with proven security
  • Because, if P=NP, then you can break

P and NP

Class P

  • A problem is in class P: if it can be solved efficiently(in polynomial time)
  • EX : Eulerian path problem
  • "Given a graph G, is there an Eulerian path in this graph?"
  • Eulerian path itself is the witness

Class NP

  • A problem is in class NP : if given an answer, checking it can be done efficiently
  • EX : Hamiltonian path problem
  • "Given a graph G, is there a Hamiltonian path in this graph?"
  • Hamiltonian path itself is the witness
  • 정답을 확인하는 것은 쉽지만 정답을 찾는 건 어렵다.
  • Another Example : "Given a bitstring c and a public key pk, is this c an encryption of some message with respect to the public key pk?"
  • That is, do we have c = Encpk(m) for some message m?
  • what can be the witness?

P vs NP Problem

  • We have P =< NP. Do we have NP = P? or is there some problem in NP which is outside of P?
  • Most people believe P != NP, but very hard to prove
  • If NP = P, you can solve any NP problems efficiently
  • You can answer questions like "Do we have c Encpk(m) for some messages m?"
  • Big Deal?

Unconditional security

  • So, P = NP --> such cryptosystem will not be secure
  • Then, provably secure cryptosystem -> prrof of P = NP
  • This is far beyond cryptography

Reduction

Use reduction between problems

  • Given algorithm A for solving problem a, design algorithm B for solving b, which uses A as a subroutine
  • Later, solving a -> solving b
  • On the other hand, infeasible to solve b -> infeasible to solve a

Reductions everywhere

Reduction became the core methodology in complexity theory

  • In a sense, bypassing P vs NP problem
  • classifying between problems

Reduction and P.S.

  • X : difficult mathematical problem
  • E : cryptosystem
  • R : polytime reduction for solving X, using an
  • E can be attacked efficiently -> X can be solved efficiently
  • Contrapositive : X cannot be solved efficiently -> E cannot be attacked efficienty
  • The trust in the hardness of X is transferred into the trust in the security of E

More History

  • Middle 80s - Early 90s : ad-hoc crypto & provable security went in parallel
  • Random Oracle Model : to design practical & somewhat provable schemes
  • Bellare & Rogaway : "Random Oracles are Practicals", 1993
  • 2000 - : trying to do things in the Standard model

Case study : Cramer-Shoup encryption

Notion of PKE

Provable security of PKE

  • 3-step recipe for provable security
  • Step 1 : you need to define what you are making
    • Step 1-1 : you need to describe its syntax, or, correctness
    • Step 1-2 : you need to describe its security properties
  • Step 2 : describe a concrete scheme realizing above notion
  • Step 3 : give a reduction proof

Public-key encryption

Consists of 3 Polynomial algorithms( Gen, Enc, Dec)

  • (pk, sk) <- Gen(1^lambda) : given security para lambda, Gen outputs public key & security key pair (pk, sk)
  • c <- Encpk(m) : given a public key pk and a plaintext m, Enc outputs corresopnding ciphertext c
  • Decsk(c) outputs a message, or it may fail to decrypt

Syntax of PKE

  • The algorithm should satisfy the following:
  • for any lambda, if key pair (pk, sk) is generated by (pk, sk) <- Gen(1^lambda), then for any plaintext

IND-CCA encryption

  • Cramer-Shoup "First practical IND-CCA public key encryption scheme in the standard model"

Semantic Security

Intuitive security we want for an encryption

  • "Even if you happen to know c, it won't help you at all in learning anything more about the plaintext m"
  • c doesn't leak even one bit of information about m
  • This is called semantic security
  • Satisfying definition, but hard to use

Indistinguishability

  • I'll give you a ciphertext c. This is either encryption of m0, or m1. Guess which is the case
  • By default, you can win this game with probability 12

Similar to semantic security, or, a special case of semantic security

  • You already know that the plaintext is m0, or, m1

Semantic security VS IND

  • Clearly, if your encryption scheme satisfies semantic security, then it also satifies IND
  • Importantly, the other direction is also true
  • 그래서 보편적으로 IND를 암호화 다룰 때 더 많이 씀

IND game

  • A : polytime adverary
  • IND GAME
  • (pk, sk) <- Gen(1^lambda)
  • (m0'm1', state) <- A('find', pk)
  • b <- {0, 1}; c' <- Encpk(mb')
  • b' <- A('guess', c', state) (not allowed to query c')
  • A wins IND game if b = b'

Chosen ciphertext attack

Chosen plaintext attack

  • The attacker's ability to create a ciphertext for any plaintext chosen by the attacker
  • Obvious in PKE

Chosen ciphertext attack

  • The attacker's ability to obtain decryption of any ciphertext chosen by the attacker
  • IND-CCA : even against such powerful attacker, any ciphertext which is untouched by the attacker is still IND-secure

IND-CCA Justification?

Security assumption

Diffie-Hellman

  • G : a group of prime order p
  • g (- G : uniform random
  • Assume discrete logarithm is hard on G : given g^a
  • If you know g, g^a, and b (- Zp, then easy to compute gabgab

Decisioin Diffie-Hellman

DDH Problem

DDH assumption : alternatively

DDH game

  • b <- {0, 1}
  • If b = 0, sample (g1, g2, u1, u2) <- D
  • Else, sample (g1, g2, u1, u2) <- R
  • b' <- A(g1, g2, u1, u2)
  • b = b'

Collision-resistant hashing

  • one more ingredient : hash function
  • A hash function H maps elements in a large domain to a small, fixed size codomain
  • Naturally, there should be lots of collisions : a pair (x, y) where H(x) = H(y) but xy
  • H is collision-resistent, if it is computationally hard to actually find a collision
  • 계산 자원에 제약이 주어지는 상황에서는 찾아내는 것이 불가능

Key generation

  • Choose G with prime order p according to security parameter
  • Choose g1g2G : uniform random
  • Choose x1x2y1y2zZp: uniform random
  • cg1x1g2x2dg1y1g2y2hg1z

Encryption & Decryption

  • (사정상 생략)

IND-CPA security of Cramer-Shoup

IND-CAP security

  • Cramer-Shoup is IND-CPA, if DDH assumption holds

IND-CPA reduction proof

Basic idea

  • B is DDH solver, so it receives a tuple tg1g2u1u2
  • B wants to find out if this tuple is a DDH tuple(from D), or a random tuple (from R)
  • B simulates the IND-CPA game environment of A

How to determine t using A?

  • B's simulation should at
  • B will use this tuple t to create challenge ciphertext c for A
  • cu1u2u1zmbu1x1y1au2x1y1awhereaHu1u2u1z
  • If t is from D, then c is the same as correctly created
  • On the other hand, if t is from R, then c is a fake encryption for mb
  • cu1u2u1zmbu1x1y1au2x1y1a
  • claim : from A' is point of view, u1z is uniform random
  • If so, u1zmb is also uniform random : it can be anything in G equally likely : no matter what b is
  • In that case, A can win the fake IND-CPA game with prob. 1/2
  • cu1g1ru2g2rvu1x1y1au2x1y1a
  • (이하 생략. PPT 참조 바람.)

Bypassing the problem

  • B will simulate IND-CPA game, but generating a fake pk
  • Choose x1x2y1y2z1z2Zp : uniform random
  • compute cg1x1g2x2dg1y1g2y2

  • Claim : this modification is completely invisible to A

Reassessing the situation

  • B will use tuple t to create challenge ciphertext c for A
  • cu1u2u1z1u2z2mbu1x1y1au2x1y1awhereaHu1u2u1z1u2z2

Uniform randomness

Going to IND-CCA


""솔직히 너무 어려워서 잘 이해를 못하고 받아 적기만...."" 

Post-Quantum Public-key Cryptography

IT requires Public-key Cryptography

  • 전자상거래의 증가

Factorization Progress

Inter Factorization Problem (IFP)

  • Given a composite n = pq, find p and q
  • 소인수 분해의 이산대수 문제
  • 분석 기술이 나날이 발전중

DLP Progress in F_p^n

Discrete Logarithm Problem

  • Given g^x in

ECDLP Progress

Elliptic Curve DLP

  • Given xP in E(F_q), compute x.

The quantum computer threat

Shor Algorithm 1997

  • Polynomial-Time algorithm for Prime Factorization and Descrete Logarithm on quantum computer
  • RSA and ElGamal insecure

Quantum computer realistic?

  • NSA seeks to build quantum computer that could crack most types of encryption
  • Researchers use silicon to push quantum computing toward reality

만약 양자컴퓨터를 만들어도 발표하지 않고 사용할 가능성이 높기 때문에 위험

Target Environment

Post-quantum cryptography for small devices

  • identity and adapt the most suitable PQ candidates to the requirements of constrained devices and to produce efficient and physically secure implementations *

PQ-Crypto for internet

  • internet severs are subject to tremendous performance pressures
  • goal is to intergrate high-security PQ-crypto into internet

PQ-Crypto for Cloud

NSA Suite B Cryptography

NSA announced that it is moving towards quantum-resistant algorithm

  • Suite B is a family of cryptography......

Public key Cryptography

Quantum Cryptography

  • Quantum key distribution(QKD)
  • QKD is still vulnerable to a man-in-the-middle attack
  • so far lacks the functionality of digital signatures
  • 모든 키분배는 중간자 공격에 안전하지 않다.
  • 양자 암호로는 인증까지는 할 수 없다. 그래서 공개키 암호와 함께 사용

Post-Quantum Problems

  • Solving non-linear equation systems over finite fields
  • Bounded distance decoding over finite fields
  • Short and close lattice vectors
  • Breaking cryptography hash functions
  • Quantum key exchange
  • 찝찝한 부분은 양자 컴퓨터에 안전하다고 증명되어 있지는 않다.
  • 다만, 알려져있는 양자 알고리즘에 적용할 수 없는 알고리즘을 사용한 암호

Quantum Algorithms

Grover algorithm brings faster simultaneous search in data

  • some security loss in symmetric crypto
  • some security loss in hash functions

Polynomial-time quantum algorithm for

  • factoring .....
  • 생략

Quantum algorithms for Lattice-based crypto

SOLILOQUY, a lattice-based primitive designed at CESG in2016

  • the security of SOLILOQUY is based on two well known hard problems
  • closed vector problem
  • principal ideal problem

Multivariate Quadratic-based PQ-Crypto

Retrospective of MQ-PKC

  • Claude E. Shannon
  • Breaking a good cipher should requires as much work as solving a system of simultaneous equation in a large number of unknowns of a complex type

  • After the NESSIE consortium proposed SFLASH to be standardized. -> 2010 년도에 깨짐

MQ-Encryption

Multivariate public key cryptosystems

  • Cryptosystems, whose public keys are a set of multivariate
  • the public key is given as :

    • G(X1, ... , Xn) = (G1(X1, ... , Xn), ... , Gm(X1, ... , Xn))
  • We use the finite field k = GF[2]/(x^2 + x+ 1) with 2^2 elements

  • (more)

Soving Polynomial System (SPS) Problem

  • given a system P = P1, ... , Pm of m nonlinear polynomial equations
  • ....

Destructive Aspect of MQ-Problem

  • 안좋은 면 : MQ를 이용해서 암호화 알고리즘을 설계하는 데 다른 암호 알고리즘을 깰 수도 있다.
  • AES 같은 걸 깰 수 있음
  • 관계식에서 아는 것과 모르는 것을 구분해 낼 수 있으면 그게 다변수 방적식

Attacks on AES

  • 2^8에서 시도를 하면 3986개의 변수를 갖는 시스템을 풀면 AES 깰 수 있다.
  • 카탄과 같은 경량 암호들도 다변수 시스템으로 나타낼 수 있기 때문에 공격 가능

Constructive Aspect of SPSP

ASA(Affine-Substitution-Affine) Structure

  • trapdoor S have been hidden in secret affine layer
  • AES-128 10 rounds with 19 layers

SASAS Structure

ASASA Structure

  • truly random polynomial
  • large public key size => 연산이 계속 늘어나면 degree가 점점 늘어남

MQ-PKCs

MQ-PKCs can be divided into the following two types

  • MI-Scheme



동형암호

암호의 분류

  • 1세대 암호 : 패스워드 (인증기술)
  • 2세대 암호 : 대칭키 암호 (데이터 암호화)
  • 3세대 암호 : 공개키 암호
  • 4세대 암호 : 동형 암호

미래 컴퓨팅 환경

우리가 원하는 완벽한 하인

  • 내가 하려는 일을 빠르게 대신 수행
  • 비밀을 알지 못한다.

사례1 : 개인 클라우드

  • 스토리지 클라우드 (드랍박스, 구글 드라이브, NAS 등)
  • 계산 클라우드 : DNA 계산, 헬스케어, 개인성향분석을 통한 추천

사례2 : 다수 사용자 통계분석

  • 개인정보기반 마케팅 (구글, 페이스북, 네이버 등)
  • 정부 데이터

4세대 암호

4세대 암호 : 암호화된 데이터를 복호화 없이 연산하는 암호

  • 탐색가능암호, DB암호 등
  • computing on encrypted data, secure multiparty computation

동형암호(Fully Homomorphic encryption) : 2009 Gentry

  • MIT가 선정한 2011년 10대 미래 유망 기술

개인정보기반 광고 시장

  • facebook, twitter 등의 성장
  • 구글 : gmail 등 구글의 개인정보를 통합관리
  • 합법적인가? 안전한가?

Privacy Homomorphic

10 Emerging Technologies(MIT Technical Review 2011)

  • Gentry's system

동형암호 설계 방법

Find an isomorphism between 주인 and 하인

  • 주인쪽 연산을 하인도 동일하게 수행
  • Enc : P -> C
  • f    f'
    
  • Enc : P -> C

문제 : 기지평문공격 (known text attack)

  • y = E(x)인 (x, y)를 알면 y2 의 평문은?
  • DEx2x2, but Ex2Ex2
  • Noisy Isomorphism (C가 P보다 월등히 크다)

Pros and Cons

장점

  • 컴퓨터에서 데이터의 모든 연산은 and, or, not의 논리 게이트로 연산
  • 암호화된 상태로 and, or, not 연산이 가능하면 컴퓨터로 하는 모든 연산이 가능
  • 해커의 데이터 유출 원천 봉쇄

단점

  • 암호문 확장 : 10-100 K배 -> 0.1-1배 (대칭키 방식)
  • 암복호화 속도 : 수십ms (AES : 1us, RAS : 1ms) -> 이제는 해결됨. 빨라짐
  • 암호문 연산 : 곱셈 수백ms
  • 응용연산 종류에 따른 속도의 차이가 큼 -> 개별적 최적화

법과 항등식

a-b가 n의 배수 <-> a = b (mod n)

  • 예 : 5 = 2 (mod 3)

a=b(mod n) 이고, c=d(mod n) 이면

  • a+c = b+d (mod n)
  • a-c = b-d (mod n)
  • ac = bd (mod n)

문제 : 1234*(56-78) 을 32로 나눈 나머지는?

  • (1233+1)((54+2)-(78) ....

완전동형암호

RAD PH

  • 비밀키 : 큰 두 개의 소수 p, q
  • 공개키 : n = pq
  • 암호화 : E(m) = (m mod p, m mod q)
  • 복호화 : 중국인의 나머지 정리
  • E(m1) + E(m2) = (m1 mod p, m1 mod q) + (m2 mod p, m2 mod q)
  •         = (m1 + m2 mod p, m1+m2 mod q) = E(m1 + m2)
    
  • 안전한가? Enc : P->C

재부팅 Bootstrapping

  • 입력 : 노후화된 암호문, 암호화된 비밀키
  • 출력 : 신규 암호문
  • 과정 : 곱을 반복하여 노이즈가 커진 암호문을 노이즈가 작은 암호문으로 변경

동형암호

DGVH

  • 비밀키 : a large prime p
  • 연산키 :

Hard Problem and Security

AGCD Problem

  • given several noisy multiples of p, find p.
  • e.g, find p given x0 = pq0 + r0, x1 = pq1 + r1 with ri << p

how to solve?

  • brute force for noise r or secret p
  • Use continue fraction
  • use lattice : orthogonal lattice attack and LLL

AGCD is provably hard?

SVP is NP-complete, but only in the worst case

(Ajtai96) SIS is as secure as the uSVP(worst c.)

  • find a small integer solution of a system of integer equations

(Regev04) LWE is as secure as GapSVP

  • m eqns with n variables over Zp is easy to solve
  • what if the answers have noise? -> NP complete
  • self-reducible (worst case = average case)

(C.-Stehle 15) AGCD is as secure as LWE

동형암호의 응용

예제1 : 생체인증

생체인증 시장 및 문제점

  • 신한은행, 손바닥 정맥 인증 도입, 은행권 생체 본인 인증 본격화
  • 생체인증 시장 규모 성장중
  • 끊이지 않는 개인정보 유출 사고
  • 생체정보는 유출 시 대체 불가능

생체인증 기술 개발

  • 생체 정보를 보호하는 동형암호기반 생체인증 기술
  • 인증시간 < 0.1초?
  • 결과가 맞다 틀리다의 암호문이 나옴. 그래서 풀어주는 절차 필요
  • 사용자의 위변조 방지를 위해 MAC 기술 적용

예제 2 : DNA 분석

DNA 분석/정밀의료와 암호화

  • 개인의 유전정보를 이용한 정밀의료 새로운 보건의료 패러다임
  • 미국 : 정밀의료 이니셔티브(PMI : Precise Medical Initiative) 2016 예산 2억 1500만 달러
  • 문제는 유전정보의 보호 기술

DNA 맞춤의학

공공 유전자 변이 DB들로부터 DNA 바이오마커 수집

TCGA 유방암 데이터를 이용하여 유방암 특이적 질병패널 최종선정

  • 유방암 질병패널에 기반한 질병감수성 예측모델 추측

DNA Privacy

스트레인저 비전 (조각가, 2012 뉴욕)

  • DNA 분석 (공공장소에서 주운 머리카락)
  • 얼굴 만드는 소프트웨어 이용
  • 3d 프린터

DNA : 궁극의 프라이버시

  • 개인의 DNA 정보 수집/악용

예제3 : 암호화된 헬스케어

  • 건강진단 <--> 생체정보 (심박/활동량)

개인정보 헬스케어

  • 예시 : 서인남성이 심장마비 걸릴 확률에서 변수로 쓰이는 헬스 정보는 나이(a), 키(ht), 몸무게(wt), 수축기 혈압 (sys), 이완기 혈압 (dia), 콜레스테롤 수치(chol) 이다. P(x) = e^x / (e^x-1)
  • 실수동형암호의 필요성. 동치 계산을 해야 한다. -> 복소수 동형암호화

Smart Car

Cyber Physical System(CPS)

  • 스마트홈에서 센서들이 인터넷에 연결되고 이 정보들과 사용자 명령이 합쳐서 일종의 컨트롤러에 전달되면 이것들이 계산되어 집행됨
  • 계산 속도의 문제로 암호화 하지 않은 상태로 사용 중
  • 정보조작, 원격조종, 위치정보 공개 등 많은 보안위협 산재
  • Floating point HE(실수동형암호)를 통해 새로운 스마트카 제어 모델 설계

What is the next?

동형암호 vs 함수암호

  • 현재 추세는 동형암호보다는 함수암호에 더 비중
  • 그러나 조금 시각을 달리보면 동형 암호도
  • 동형암호 : Enc(M1), ... , Enc(Mn) -> Enc(f(M1, M2, ..., Mn)) 모든 f
  • 함수암호 : Enc(M1), ... , Enc(Mn) -> f(M1, M2, ... , Mn) 특정한 f

함수 암호의 응용

  • 생체인식 : ENC_k(M1), ENC_k(M2) -> M1 = M2 인지 판별
  • 프로그램 난독화 (Obfuscation) : 안전성 증명 -> 존재하는지 아닌지 불확실
  • 암호화된 데이터에서 필요 정보 추출 (데이터마다 암호화시 지정)

양자컴퓨터 시대에도 안전!

(PQ) 양자 컴퓨터

양자컴퓨터

pros

  • 인수분해와 이산로그를 다항식 시간에 계산
  • 검색도 O(sqrt n) 시간에 해결 (groover algorithm)

cons

  • NP-hard 문제는 다항식 시간에 계산 안됨
  • 다룰 수 있는 q bit를 늘리는 것이 매우 어려움 (현재 수십)

일반적인 예상

  • 수십년 이후에나 개발 가능할 듯

Post-Quantum Crypto

NSA Suite B Cryptography (2015 8 19)

  • Qunatum Resistant Algorithm 으로 이동 계획 발표
  • Suite B에 있는 타원곡선 암호 사용 자제 권고

Post-Quantum Crypto (based on NP-Hard Problem)

  • 격자 : SVP and CVP in Integral Lattices of high dim
  • 다변수 다항식 : solve multivariate Quandratic eqns
  • 코드 : Decode of General Linear Codes
  • 해쉬기반

NIST 공모

  • 양자 암호에 안전한 공개키 암호 알고리즘
  • 전자 서명
  • 키 교환 프로토콜
  • 다수의 알고리즘을 채택할 것으로 기대
  • 공개적으로 투명한 평가를 중시할 예정

cs 쪽에서는 lattice 가 익숙하지만 대수적은 불편 저 두 개를 결합한 이론은 이제 막 연구 시작


https://youtu.be/BylWT5gsgfM



2016 암호여름학교 시간에 서울대학교 천정희(?) 교수님께서 좋은 영상을 소개해 주셨다.


암호화를 쉽게 잘 설명해 놓은 영상

2016 암호여름학교 - 난수발생기 강의

차례

  • 난수발생기 개요
  • 난수발생기 구조
  • 표준 난수 발생기
  • 난수 발생기의 안전성 분석
  • 안전성 평가 기법과 안전한 활용

난수발생기 개요

난수발생기란?

난수발생기(RBG : Random Bit Generator) 기능

  • 암호시스템에 필요한 난수 제공
  • 이상적으로는 동전 던지기의 결과를 기대
  • 암호시스템과 암호 모듈의 운용에 필수적인 요소

요구되는 성질

  • 예측 불가능성
  • ()
  • () 

난수발생기와 보안 시스템

난수발생기의 용도

  • 비밀키 암호에 사용되는 암호키 생성
  • 공개키 암호의 파라미터 생성
  • 기타 : nonce, salt 등

현대 암호의 안전성

  • 보안시스템의 암호기능에서 난수 발생기의 사용은 필수
  • 암호의 안전성 확보는 완벽한 난수 발생기 사용을 전제로 가능

난수발생기의 용도(1) 암호키

암호키의 생성

  • 블록 암호의 암호키
  • RSA 공개키 암호의 소수 생성

난수발생기의 용도(2) Salt

사용자 인증(로그인)용 패스워드의 저장

  • 패스워드는 암호화된 형태로 시스템에 저장되어야 함
  • 암호화 방식
    • 해쉬함수를 이용하는 방법
    • 비밀키 암호로 암호화하는 방법

난수발생기의 용도(3) Bit Commitment

원거리의 Alice와 Bob이 동전던지기 게임을 할 수 있을까?

  • Alice : 난수 R1, R2 생성
  • Alice : 동전을 던진 결과 a
  • Alice : 해쉬값 H(R1,R2,a)와 R2를 Bob에게 전달
  • Bob은 Alice의 동전 던진 결과를 b로 예측하여 공개
  • Alice는 a를 공개하고, 증거자료로 R1, R2를 전송
  • 해쉬값을 계산하여 결과를 검증

난수발생기 관련 용어들

의사난수 발생기(PRNG, DRNG)

  • PRNG : Pseudo Random Number Generator
  • 일정한 알고리즘에 따라 초기값(seed)로 부터 난수를 생성
  • 알고리즘과 초기값이 모든 출력을 결정

진난수 발생기(TRNG)

  • TRNG : True Random Number Generator
  • 물리적 잡음을 기반으로 난수를 생성하는 장치

기타용어

  • DRNG : Determenistic RNG
  • DRBG : Deterministic Random Bit Gengerator

난수발생기 종류

TRNG, PRNG의 기본구조를 기반으로 다양한 조합이 가능

  • 디지털화(Conversion to binary), 난수생성 알고리즘(Determenistic Algorithm)

난수발생기의 구현

하드웨어 난수발생기

  • 하드웨어 장치에서 발생되는 잡음원을 이용한 난수 생성
  • 잡음원의 편향된 성질을 보정하는 과정이 필요
  • 잡음원(엔트로피 소스) : 열잡음원, 링오실레이터, 빔스플릿터 등

소프트웨어 난수발생기

  • 외부의 잡음원 공급을 전제로 결정론적 알고리즘을 사용
  • 잡음원 : OS 잡음(마우스 포인터 위치, 프로세스 id 등), 사용자 입력 등

난수발생기의 중요성

난수발생기의 중요성

  • 암호시스템의 안전성은 이상적인 난수발생기를 사용해야 보장할 수 있음
  • 암호학적 안전성 증명 모델도 완벽한 난수발생기의 사용을 전제로 함
  • 난수발생기의 취약성은 보안 매개변수의 안전성을 약화시킴

암호의 안전성과 난수(1)

Caesar Cipher

  • 평문(P), 암호문 (C), 암호키(K)의 관계
  • \(C = Ek(M) = M+k mod 26)
  • 암호키의 종류(26가지)가 너무 적어 안전하지 않음

단순치환 암호

  • 암호키(=치환표) : A~Z를 무작위로 섞는 방법
  • 암호키의 종류는 26!=410262641026로 충분히 큼
  • 출력되는 암호문에 평문 정보가 노출됨

안전한 암호화의 조건

  • 암호문읜 난수와 구별할 수 없어야 한다. (평문을 추측할 수 있는 정보를 제공하지 않아야 한다.)
  • 암호키는 공격자가 예측할 수 없어야 한다. (키 공간이 충분히 크고, 랜덤하게 선택되어, 공격자가 사용된 키를 맞출 확률이 낮아야 한다.)

난수발생기 구조

난수 생성 이론

Deterministic Extractor

  • 결정론적 알고리즘 만으로는 엔트로피 소스로부터 좋은 난수를 얻을 수 없다.
  • Extractor 알고리즘을 고정할 때, 주어진 입력 엔트로피가 우수하지만 출력이 균등분포에 근접하지 않는 예가 항상 존재한다.

Seeded Extractor

  • Seed의 선택에 따라 extractor가 달라지도록 설계하면 균등분포에 근접한 출력을 얻는다.
  • 단, seed의 선택을 잘 해야 한다.
  • Ext(X;S) ~= (Uniform, S)

OS 난수발생기 구조

3단계 구조 : 엔트로피 수집, 시드 생성, 난수생성 알고리즘

  • 엔트로피 수집 : 잡음원으로부터 엔트로피 수집, 시스템 의존적
  • 시드 생성 : 시드(PRNG의 입력) 생성
  • 의사난수 생성 알고리즘 : 표준화된 암호 알고리즘

LRNG 구조

  • 커널 모드에서 수집된 엔트로피를 pool로 관리하여 출력
  • Blocking Model(/dev/random)와 non-Blocking Model(/dev/urandom) 모드
  • 디바이스로 마운트되어 작동
  • 하드웨어 등의 환경에 따라 달라질 수 있다.

WRNG 구조 (윈도우 난수 발생기)

  • 유저모드의 인스턴스로 생성되어 동작 (여러 WRNG 공존)
  • 엔트로피 관리가 없어 Blocking Model은 제공하지 않음

표준 난수발생기

ISO/IEC 표준 모델
  • ISO/IEC 18031 표준문서에 정의된 난수 발생기

미국의 NIST 모델

  • SP800-90A 의 난수발생기 모델 : DRBG

독일의 BSI 모델

  • AIS.31

한국 KCMVP의 난수발생기

암호모듈 검증제도의 알고리즘

  • Hash_DRBG : sha224/256/384/512
  • HMAC_DRBG : HMAC(sha224/~~)
  • CTR_DRBG : ARIA128/192/256, LEA128/192/256

난수 발생기의 안전성 분석

난수발생기의 안전성

Backtracking resistence

Prediction resistence

  • 공격자가 현재의 상태정보를 알 수 있을 때
  • 이전 정보를 보호하는 것 (업데이트 알고리즘을 잘 만들기)
  • 향후 출력을 보호하는 것 (다음 단계로 넘어갈 때 엔트로피 소스 넣기)

엔트로피 수집의 취약성

엔트로피 수집 단계의 취약성

  • 충분한 엔트로피를 수집하지 못하면 난수의 출력이 예측 가능함
  • 대부분의 취약성은 엔트로피 수집단계에서 발생함
  • 시스템에서 활용 가능한 잡음원이 충분히 확보되어야 함

비트코인 지갑의 취약성

  • 시스템 난수발생기의 취약성으로 전자지갑 탈취
  • 비트코잉ㄴ 공개키 암호의 안전성에 치명적 손상 유발

모바일 환경에서의 엔트로피

  • 키보드, 마우스 등의 가용 잡음원 부족
  • 충분한 엔트로피의 소스를 확보해야 함

엔트로피 수집 - Windows

윈도우 환경에서의 엔트로피 소스

  • GetCurrentProcessID()
  • GetCurrentThreadID()
  • GetLocalTime()
  • GetDiskFreeSpace()
  • GetComputerName()
  • GetUserName()
  • .....이 외에도 많이있지만 쓸만한 게 별로 없다

리눅스 환경에서의 엔트로피 소스(LPRNG가 사용하는 엔트로피 종류)

  • ~~~

시드 생성 단계의 취약성

엔트로피 축적/시드 생성 단계에서의 취약성

  • ios 난수 발생기 취약점
  • 안드로이드 난수발생기 취약점

난수생성의 알고리즘의 취약성

의사난수생성 알고리즘의 취약성

  • 알고리즘의 취약성 우려제기
  • 미국의 NIST의 난수발생 알고리즘 표준
    • 백도어 심어 놓음 -> 스노든의 폭로
  • 2014 ISO 회의에서 표준 철회

Dual_EC_DRBG란?

  • 타원곡선 이산대수 문제 기반 의사난수발생기
  • 미국 ANSI 표준, ISO
  • NIST가 권장 파라미터를 제공

암호 전문가가 Dual_EC_DRBG의 취약성 지적

  • P = eQ
  • rP : Seed, rQ : Output
  • 그런데 NSA가 e를 알고 있다는 의혹 제기
  • e를 알고 있다면 새로운 난수를 계속 알 수 있음
  • 하지만 의혹을 증명할 수는 없다.

안전성 평가 기법과 안전한 활용

난수발생기의 안전성 평가

안전성 평가의 중요성

  • 난수 발생기의 취약성은 암호시스템 전체로 전파
  • 특히 예측 가능한 출력이 발생하면 치명적

평가의 어려움

  • 현실적으로 이상적인 난수에 도달할 수 없음
  • 충분히 이상적인 난수에 근접함을 입증해야 함
  • 개발자, 시험기관, 검증기관 모두에게 어려운 문제

난수발생기 평가 기준

난수발생기 평가 방법

  • 수집되는 엔트로피의 건전성 평가
  • 출력난수의 통계적 랜덤성 평가

난수발생기 평가 기준

  • ISO/IEC 19790/24759

통계적 난수성 검정의 한계

  • 통계적 난수성 검정은 편리한 도구이나 암호학적 안전성을 보장하지는 않는다.

엔트로피 개요

엔트로피 개념

  • 데이터가 가진 실제 정보량을 정량적으로 측정한 값
  • 엔트로피가 높다는 건 확률은 낮다고 얘기할 수 있음
  • random variable의 확률분포가 엔트로피를 결정

엔트로피 종류

  • 샤논(shannon) 엔트로피 : 가지고 있는 정보량의 기대값
  • 민(Min) 엔트로피 : 확률 멕시멈의 정보량

요약

보안시스템의 안전성과 난수발생기

  • 현대암호의 안전성은 난수발생기에 의존함
  • 암호키와 보안매개변수 생성에 사용되는 난수발생기의 안전성이 확보되어야 함

난수발생기 평가의 어려움

  • 암호 알고리즘의 경우 테스트 벡터의 확인으로 안전성을 확인하는 KAT(Known Answer Test)가 가능함
  • (작성중)


error LNK2019 발생


최악의 링크 에러....


이에 대한 내용은 정리를 너무나 잘해 놓으신 분이 계셔서 그 글로 대체한다.



http://sadiles.blog.me/10072075057


컴파일 에러는 너무나 사람을 지치게 한다. 기껏 코딩해 놨더니 왜 컴파일이 안돼...


이번에 나온 오류는 


error C2220: warning treated as error - no 'object' file generated    요놈이다.


MSDN 참고 링크 

https://msdn.microsoft.com/ko-kr/library/ksk5k0ta(v=vs.120).aspx


컴파일러 오류 C2220

Visual Studio 2013
경고가 오류로 처리되어 생성된 개체 파일이 없습니다.

/WX는 컴파일러가 모든 경고를 오류로 처리하도록 합니다. 오류가 발생했기 때문에, 개체나 실행 파일이 생성되지 않았습니다.

오류는 /WX 플래그가 설정될 때에만 나타나고 경고는 컴파일하는 동안에 발생 합니다. 이 오류를 해결 하려면, 프로젝트의 모든 경고를 제거 해야 합니다.

해결하려면, 다음 방법 중 하나를 사용합니다

  • 프로젝트에서 경고를 발생 시키는 문제를 해결 합니다.

  • 낮은 경고 수준에서 컴파일합니다 — 예를 들어 /W3 를 사용합니다 (/W4대신).

  • 경고 pragma를 사용하여 사용 안 함 또는 특정 경고를 표시 합니다.

  • 컴파일 하기 위해 /WX 사용하지 않습니다.

MSDN 왈 이렇다고 한다.


그니깐 warning을 error로 취급하고 있다는 것.



해결방안은 두 가지가 있다.


1. 뭔지도 모르지만 그냥 warning을 무시.


프로젝트 우클릭 후 Properties에 들어가자.

Project Settings - Configuration Properties - C/C++ - General - Treat Warnings as Errors 항목이

ALL로 되어 있다면 No로 바꾼다.


해결.



2. warning 이 왜 뜨는지 확인하고 이를 해결.


이 때 확인해야할 부분은 어떤 warning이 error로 취급받고 있냐는 것이다.

output이나 error list에서 warning부분을 살펴보면 발견할 수 있다.


본인의 에러는 아래와 같았다.


warning C4819: The file contains a character that cannot be represented in the current code page (949). Save the file in Unicode format to prevent data loss


인코딩에러....라는 뜻이다. 

해당 파일의 인코딩을 unicode - codepage 1200로 바꿔주면 문제해결.


visual studio에서 인코딩을 바꾸려면 FILE-Advanced save option 를 클릭하면 원하는 인코딩을 선택할 수 있다.


혹은 


#pragma warning ( disable : warning번호)  

를 헤더파일에 입력해 주면 된다. 본인의 경우 #pragma warning ( disable : 4819) 
















'개발 > C and C++' 카테고리의 다른 글

error LNK2019 발생  (0) 2016.06.16
C/C++ 에서 clock() 함수를 이용하여 수행시간 측정하기  (0) 2016.06.16

C/C++ 에서 clock() 함수를 이용하여 수행시간 측정하기에는 여러가지 방법이 있겠지만

본인이 가장 선호하고, 가장 간편한 방법을 소개한다.


자료구조 전공시간에 전공 도서에서 함수의 수행 시간 측정하는 코드를 처음 접하였다.

(아마도 호로비치 자료구조 책일듯?)


boolean operation을 수행하는 두 라이브러리의 속도를 비교하기 위해서 수행시간 측정을 하게 되었다. 



먼저 clock 함수에 대해 알아보자. 

아래는 C++ 레퍼런스 사이트에서 가져온 내용이다. (링크 참고 : http://www.cplusplus.com/reference/ctime/clock/ )


function

<ctime>

clock

clock_t clock (void);
Clock program
Returns the processor time consumed by the program.

The value returned is expressed in clock ticks, which are units of time of a constant but system-specific length (with a relation of CLOCKS_PER_SEC clock ticks per second).

The epoch used as reference by clock varies between systems, but it is related to the program execution (generally its launch). To calculate the actual processing time of a program, the value returned by clock shall be compared to a value returned by a previous call to the same function.

Parameters

none

Return Value

The number of clock ticks elapsed since an epoch related to the particular program execution.

On failure, the function returns a value of -1.

clock_t is a type defined in <ctime> as an alias of a fundamental arithmetic type.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* clock example: frequency of primes */
#include <stdio.h>      /* printf */
#include <time.h>       /* clock_t, clock, CLOCKS_PER_SEC */
#include <math.h>       /* sqrt */

int frequency_of_primes (int n) {
  int i,j;
  int freq=n-1;
  for (i=2; i<=n; ++i) for (j=sqrt(i);j>1;--j) if (i%j==0) {--freq; break;}
  return freq;
}

int main ()
{
  clock_t t;
  int f;
  t = clock();
  printf ("Calculating...\n");
  f = frequency_of_primes (99999);
  printf ("The number of primes lower than 100,000 is: %d\n",f);
  t = clock() - t;
  printf ("It took me %d clicks (%f seconds).\n",t,((float)t)/CLOCKS_PER_SEC);
  return 0;
}


Output:

Calculating...
The number of primes lower than 100,000 is: 9592
It took me 143 clicks (0.143000 seconds).




간략히 정리해보면, clock 함수는 time.h(c++에서는 ctime) 헤더 파일에 들어있다.


clock_t clock(void); 의 형태로 선언되어 있으며, 그 내부가 궁금한 분은 직접 찾아보기 바란다.

(참고로 Visual studio에서 F12키를 통해 내부 선언으로 찾아갈 수 있다.)


여기서 반환형인 clock_t는 


typedef long clock_t; 


와 같이 선언되어 있는데, 그냥 long이라고 생각하면 된다.


사용법은 위의 예제와 같다. 

측정시작한는 부분에 clock()을 변수에 저장한 뒤, 끝날 때 시간을 빼고 CLOCKS_PER_SEC으로 나눠주면 된다.

즉,

  t = clock();   // 측정 시작
  /* 측정할 함수,코드가 들어갈 자리 */

  t = clock() - t;
  printf ("It took me %d clicks (%f seconds).\n",t,((float)t)/CLOCKS_PER_SEC);


와 같이 사용하면 된다.






qt, vtk 모두 최신버전으로 개발을 진행하려 하였으나, 

이전에 개발했던 프로그램이 Qt4 버전과 VTK 5.10 을 사용하여서 문법 및 라이브러리 호환성 때문에 버전을 내리기로 결정하였다.

vtk5 버전에만 있는 QVTK.lib 라는 라이브러리(이후 버전에서는 다른 이름의 여러 라이브러리로 나뉨) 문제와 qt4와 5 버전의 함수명 변화 등 때문이다.


구입해준 visual studio 라이센스가 2013 버전이기 때문에 해당 버전을 사용해야만 한다.

그런데 아쉽게도 qt 공식 홈페이지에서 제공하는 qt 4.x 버전은 visual studio 2012 (msvc2012)까지만 지원한다.

따라서 직접 빌드를 해야하는데, 이 방법은 시간이 너무 오래걸려서 박사님께 pre-compiled 된 qt 4.8버전을 구하였다.


이 후 방법은 전에 올린 설정 방법과 유사하므로 생략한다.





전문 복사해옴

출처 : http://neodelicious.tistory.com/232



Autotools보다 cMake가 얼마나 좋을까?
CMake는 Linux 외에 다른 OS에서도 범용적으로 build 환경을 제공한다는 점에서 분명히 장점이 있을 것 같다.

그런데 아직 CMake를 많이 안 써봐서 모르겠지만,
Autotools 에서는 기본값으로 되어 있는 'build command 보이기' 나 '-g 옵션을 추가' 등이
CMake에는 기본값으로 되어 있지 않은 등 분명 사용함에 있어서 차이가 있어 보인다.

KDE의 CMake 선정을 비롯한 사례로 볼 때 아마도 아직 내가 모를 뿐,
CMake에서도 Autotools의 기능을 대부분 지원하지 않을까 싶다.

아무튼 개인적으로 CMake의 소위 build template을 만들면서 공부한 것을 정리해서 올린다. 

아래 링크에서 source code를 download 할 수 있으며, 이하 글은 이 source code를 설명한다.

http://www.neodelicious.com/repos/cmake_example.tar.bz2


Assumption
1. Linux 환경을 기준으로 설명하며, '$'는 Linux Shell Prompt 를 의미함
2. 각 module 별로 CMakeLists.txt 파일을 생성하지 않고, (top directory)/CMakeLists.txt 에 모두 기술함을 기본으로 함
  2.1 원하면 (top directory)/CMakeLists.txt 파일에서 하위 directory 별로 CMakeLists.txt 파일로 분리하고 상위 directory의 CMakeLists.txt 에서 add_subdirectory 명령어를 통해 재귀적으로 호출할 수 있음
3. Top directory가 아닌 build directory에 build metadata를 생성하는 것을 기본(희망)으로 함
  3.1 Top directory에서 'cmake .'를 실행하면 top directory에 build metadata를 생성함

Reference
1. http://www.cmake.org/cmake/help/documentation.html
  1.1 http://www.cmake.org/cmake/help/cmake_tutorial.html
  1.2 http://www.cmake.org/cmake/help/cmake-2-8-docs.html


Note

1. 한 번 cmake build 하면 CMakeCache.txt 파일에 cmake build 결과의 설정값이 저장되는데, 이를 삭제하지 않고 CMakeLists.txt 파일을 수정하고 cmake build 하면 반영되지 않으니 주의해야 함


Preparation

1. $ tar xvjf cmake_example.tar.bz2
2. $ cd make_example


Build

1. Method 0 - CMakeLists.txt의 default 옵션으로 cmake build 하고, make 까지 진행하는 shell script를 이용 할 때
  1.1 $ ./start_build.sh
2. Method 1 - CMakeLists.txt의 default 옵션으로 cmake build르 직접 할 때
  2.1 $ mkdir build ; cd build
  2.2 $ cmake ..
  2.3 $ make
3. Method 2 - interactive 방식(wizard mode)으로 CMakeLists.txt의 옵션을 변경하여 make build 할 때
  3.1 $ mkdir build ; cd build
  3.2 $ cmake -i ..
  3.3 make
4. Method 3 - Curses Interface 로 CMakeLists.txt의 옵션을 변경하여 cmake build 할 때
  4.1 $ mkdir build ; cd build
  4.2 $ ccmake ..
  4.3 $ make


Run

1. build directory에 실행파일 example과 shared library인 libshow.so 파일이 있음
2. build directory에서 아래를 실행함
  2.1 $ ./example


CMakeLists.txt 파일 설명

# project
1. cmake_minimum_required (VERSION 2.6)
  1.1 cmake의 최소 버전을 명시함, 없으면 경고 메시지가 출력됨
2. project (cmake_example)
  2.1 새 project의 이름을 명시함
# user selectable variables
1. option (ENABLE_SHARED "Select OFF to build libararies as static" ON)
   option (DEBUG "Select ON to define DEBUG" ON)
   option (DEBUG2 "Select ON to define DEBUG2" ON)
  1.1 사용자가 선택할 수 있는 옵션에 대해서 이름, 설명, 기본값 순으로 설정함
2. message ("ENABLE_SHARED - ${ENABLE_SHARED}")
   message ("DEBUG - ${DEBUG}")
   message ("DEBUG2 - ${DEBUG2}")
  2.1 사용자 편의를 위한 화면 출력용으로 사용자가 선택한 값을 화면에 출력함
# dependency check
1. include (FindPkgConfig)
2. pkg_check_modules (pkgs x11>= 1.2.2 xrender)
  2.1 pkg-config tool을 이용해서 system의 library 정보를 확인할 수 있음
  2.2 아래와 같이 REQUIRED 옵션을 추가하여 조건에 부합하지 않으면 cmake build를 중단할 수 있음
    2.2.1 pkg_check_module (pkgs REQUIRED x11>=1.2.2 xrender)
3. foreach (flag ${pkg_CFLAGS})
     set (EXTRA_LIBS ${EXTRA_LIBS} ${flag})
   endforeach (flag)
   foreach (flag ${pkg_LDFLAGS})
     set (EXTRA_LIBS ${EXTRA_LIBS} ${flag})
   endforeach (flag)
 3.1 위의 pkg-config를 통해 얻은 CFLAGS, LDFLAGS 정보를 cmake 변수에 저장함
#global CMake variables
1. if (ENABLE_SHARED)
     set (BUILD_SHARED_LIBS true)
   endif (ENABLE_SHARED)
  1.1 명시적으로 static 혹은 shared 등을 명시하지 않은 add_library 명령에 대해서 기본 값인 static이 아닌 shared로 library를 build 하도록 설정함
  1.2. 이때 if 를 통해 위의 option에서 설정항 사용자의 선택에 따라 static일 경우 적용하지 않도록 함
2. set (CMAKE_VERBOSE_MAKEFILE ture)
  2.1 make build 할 때 build command를 화면에 출력하도록 함
3. set (CMAKE_BUILDTYPE debug)
  3.1 build 옵션에 -g를 포함하도록 함
4. set (CMAKE_INSTALL_PREFIX /usr)
  4.1 make install 을 통해 설치할 directory의 기준 path를 기본값이 아닌 /usr로 설정함
# global build variables
1. include_directories ("${PROJECT_SOURCE_DIR}/include")
  1.1 make build -I 로 설정하여 header file 을 찾을 path를 추가함
  1.2 PROJECT 는 최근 project 명을 대신하며, PROJECT_SOURCE_DIR 대신 여기서는 cmake_example_SOURCE_DIR 을 사용해도 됨
  1.3 PROJECT_BINARY_DIR 변수도 있는데, 이는 cmake를 실행한 path로서 여기에서는 build directory path임
# variables to the configuration file
1. configure_file ("${PROJECT_SOURCE_DIR}/include/config.h.in" "${PROJECT_SOURCE_DIR}/include/config.h")
  1.1 Source code에서 참조할 값을 반영한 config.h 파일을 config.h.in 파일을 수정해서 생성함
# build library
1. add_library (show lib/show.c)
  1.1 libshow.so 파일을 build 함
# build source
1. add_executable (example src/main.c)
  1.1 실행 파일 example 파일을 build 함
2. target_link_libraries (example show ${EXTRA_LIBS})
  2.1 실행 파일에 link할 library를 명시함
  2.2 이때 위에서 pkg-config를 통해 찾은 system 상의 library 정보를 추가함
# install
1. install (TARGETS show DESTINATION lib)
   install (TARGETS example DESTINATION bin)
   install (FILES ${PROJECT_SOURCE_DIR}/include/show.h DESTINATION include)
  1.1 기본적으로 make install을 위한 install target이 Makefile에 기술되지 않음
  1.2 위의 CMAKE_INSTALL_PREFIX 변수를 기준으로 make install에서 복사할 실행 파일, library 파일, header 파일을 명시함

include/config.h.in 파일 설명
1. #define ENABLE_SHARED "@ENABLE_SHARED@"
  1.1 cmake 내 EANBLE_SHARED 변수를 설정하면 @ENABLE_SHARED@ 값을 ON으로 변경하고, 비설정시 OFF로 설정함
2. #cmakedefine DEBUG
  2.1 cmake 내 DEBUG 변수를 설정하면 #define DEBUG를 설정하고, 비설정시 #undef DEBUG를 설정함
3. #cmakedefine01 DEBUG2
  3.1 cmake 내 DEBUG2 변수를 설정하면 #define DEBUG2 1를 설정하고, 비설정싱 #define DEBUG2 0를 설정함

+ Recent posts