레이블이 google storage api인 게시물을 표시합니다. 모든 게시물 표시
레이블이 google storage api인 게시물을 표시합니다. 모든 게시물 표시

2014년 12월 2일 화요일

Google Storage API in Erlang


Erlang용 Native SDK가 없기 때문에,

직접 rest api를 만들어서 OAuth2에서 token을 받고, 
(  https://developers.google.com/accounts/docs/OAuth2ServiceAccount  )
그 token으로 API를 호출해야 한다. 


이 과정에서 시행착오가 있을 수 있는 부분이 몇가지 있다.

developer console에서 받은 p12 파일을 먼저 컨버팅해야 한다.


openssl pkcs12 -in some.p12 -out some.crt.pem -clcerts -nokeys

openssl pkcs12 -in some.p12 -out some.key.pem -nocerts -nodes

Certificate과 Key가 함께 있기 때문에, 일단 분리하고,


openssl rsa -in some.key.pem -out some.key2.pem


some.key2.pem이 RSA Private Key가 담긴 파일이 된다. 아래 코드는 이 파일을 RSA Private Key로 변환하는 코드이다.

get_private_key() ->
    FileName = m_config:get(gce_key_pem_file,"priv/google/some.key2.pem"),
    { ok , F } = file:read_file(FileName),
    PrivateKeyEntry = public_key:pem_decode(F),
    PrivateKeyEntry1=hd(PrivateKeyEntry),
    PrivateKey = public_key:pem_entry_decode(PrivateKeyEntry1),
    #'RSAPrivateKey'{publicExponent=Exponent
                    ,modulus=Modulus
                    ,privateExponent=PrivateExponent} = PrivateKey,
    [Exponent, Modulus, PrivateExponent].



그리고, JWT header, JWT Claim Set을 적절히 잘 만들고, 요 키로 sign을 해야 한다.




ToEncrypt = << (jwt_header())/binary , $. , (jwt_claim_set())/binary  >>,
S=base64url:encode(crypto:sign(rsa,'sha256',ToEncrypt,get_private_key())),
<< <<"grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=">>/binary , ToEncrypt/binary , $. , S/binary >>. 


완성된 full source

m_oauth2.erl
https://gist.github.com/wdshin/2eb6998913b3b95454bc

m_google_storage.erl
https://gist.github.com/wdshin/54896699bf1f5aed926e