Last active
January 18, 2019 03:20
-
-
Save emiling/7962e33aeee44f7b757f6d230b453e9a to your computer and use it in GitHub Desktop.
get_info by java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.crypto.Mac; | |
import javax.crypto.spec.SecretKeySpec; | |
//HMAC 인코딩 및 Hex로 변환하는 함수 정의 | |
public class Encryptor { | |
private static final String HMAC_SHA512 = "HmacSHA512"; | |
public static String getHmacSha512(String key, String data) { | |
Mac sha512_HMAC; | |
String result = null; | |
try { | |
byte[] byteKey = key.getBytes("UTF-8"); | |
sha512_HMAC = Mac.getInstance(HMAC_SHA512); | |
SecretKeySpec keySpec = new SecretKeySpec(byteKey, HMAC_SHA512); | |
sha512_HMAC.init(keySpec); | |
byte[] macData = sha512_HMAC.doFinal(data.getBytes("UTF-8")); | |
result = bytesToHex(macData); | |
} | |
catch(Exception e) { | |
e.printStackTrace(); | |
} | |
return result; | |
} | |
public static String bytesToHex(byte[] bytes) { | |
final char[] hexArray = "0123456789ABCDEF".toCharArray(); | |
char[] hexChars = new char[bytes.length * 2]; | |
for ( int j = 0; j < bytes.length; j++ ) { | |
int v = bytes[j] & 0xFF; | |
hexChars[j * 2] = hexArray[v >>> 4]; | |
hexChars[j * 2 + 1] = hexArray[v & 0x0F]; | |
} | |
return new String(hexChars); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.commons.codec.binary.Base64; | |
import org.apache.http.HttpEntity; | |
import org.apache.http.HttpResponse; | |
import org.apache.http.client.methods.HttpPost; | |
import org.apache.http.impl.client.CloseableHttpClient; | |
import org.apache.http.impl.client.HttpClients; | |
import org.apache.http.util.EntityUtils; | |
import org.json.JSONObject; | |
import java.net.URL; | |
import java.nio.charset.Charset; | |
public class Getinfo { | |
private static final String balance_url = "https://api.coinone.co.kr/v2/account/balance/"; | |
private static final String HMAC_SHA512_ALGORITHM = "HmacSHA512"; | |
public static byte[] str_to_byte(String str){ | |
byte[] ret_byte = str.getBytes(Charset.forName("UTF-8")); | |
return ret_byte; | |
} | |
public static String get_info() throws Exception{ | |
//논스값 := system class에서 1970년 1월 1일 0시 0분 0초로부터 경과한 시간을 초로 | |
long nonce = System.currentTimeMillis(); | |
//URL 객체로부터 balance_url | |
URL url = new URL(balance_url); | |
//ACCESS_TOKEN이랑 SECRETE_KEY 선언 | |
//final로 빼도 될 듯 | |
String ACCESS_TOKEN = ""; | |
String SECRET_KEY = ""; | |
//아래 주석처리 한 부분은 payload json 처리 후 base64 인코딩 하는 코드 | |
//python에서 base64 인코딩 한 byte hex값과 일치! | |
//split 한 이유는 인코딩 과정에서 json 콜론 사이의 띄어쓰기 맞춰 주려고 | |
//작동 잘 되지만 모듈화 과정에서 버린 코드 | |
/* | |
JSONObject payload = new JSONObject(); | |
payload.put("access_token", ACCESS_TOKEN); | |
payload.put("nonce", Long.toString(nonce)); | |
String[] str_payload1 = payload.toString().split(":"); | |
String str_1 = str_payload1[0]+": "+str_payload1[1]+": "+str_payload1[2]; | |
//System.out.println(str_1); | |
String[] str_payload2 = str_1.split(","); | |
String str_2 = str_payload2[0]+", "+str_payload2[1]; | |
//System.out.println(str_2); | |
//String str_payload = payload.toString(); | |
//byte array로 payload 인코딩 완료 | |
//byte[] encoded_payload = Base64.getEncoder().encode(temp_payload); | |
byte[] temp_payload = str_to_byte(str_2); | |
*/ | |
//hmac_sha512를 이용한 무결성 검사 및 hex값 변환 | |
//Encrypt class로 따로 빼놓음 | |
//마찬가지로 작동 잘 되지만 모듈화 과정에서 버린 코드 | |
/* | |
Mac signature = null; | |
signature = Mac.getInstance(HMAC_SHA512_ALGORITHM); | |
SecretKeySpec signingKey = new SecretKeySpec(str_to_byte(SECRET_KEY.toUpperCase()), HMAC_SHA512_ALGORITHM); | |
signature.init(signingKey); | |
byte[] temp_signature = signature.doFinal(encoded_payload); | |
String hex_signature = new String(Hex.encodeHex(temp_signature)); | |
System.out.println(hex_signature); | |
*/ | |
//!실제 코드는 여기부터 시작! | |
//우선 java에는 object type이 없으므로 json 형식으로 payload 작성 | |
//여기서 말하는 params가 coinone api에서의 payload | |
JSONObject params = new JSONObject(); | |
params.put("nonce", nonce); | |
params.put("access_token", ACCESS_TOKEN); | |
//Base64 인코딩은 org.apache.common.codec 외부 라이브러리 이용 | |
//split한 이유는 디버깅하면서 알게 됐는데 hex처리 과정에서 \r\n 들어가서 | |
String payload_str = Base64.encodeBase64String(params.toString().getBytes()); | |
String[] payload_arr = payload_str.split("\r\n"); | |
String payload = payload_arr[0]+payload_arr[1]; | |
//hmac을 이용한 무결성 검사 | |
String signature = Encryptor.getHmacSha512(SECRET_KEY.toUpperCase(),payload).toLowerCase(); | |
//http response-request 하는 코드 | |
//이것 또한 외부 라이브러리 이용, org.apache.http.client | |
CloseableHttpClient httpClient = HttpClients.createDefault(); | |
//coinone api doc에 명시되어있는대로 header 추가 | |
HttpPost httpPost = new HttpPost(balance_url); | |
httpPost.addHeader("Content-Type", "application/json"); | |
httpPost.addHeader("Accept", "application/json"); | |
httpPost.addHeader("X-COINONE-PAYLOAD", payload); | |
httpPost.addHeader("X-COINONE-SIGNATURE", signature); | |
HttpResponse httpResponse = httpClient.execute(httpPost); | |
HttpEntity response_entity = httpResponse.getEntity(); | |
String response_sting = EntityUtils.toString(response_entity); | |
System.out.println(response_sting); | |
httpClient.close(); | |
//반환 값은 디버깅 쉽게 string으로 했는데 | |
//데이터 처리하려면 json이 쉬울 듯 | |
return response_sting; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Main { | |
public static void main(String[] args) throws Exception { | |
String str = Getinfo.get_info(); | |
// 파싱이야 간단하니까 jsp action tag 내에서 처리 | |
// balance 구현에 성공했으니 같은 방식으로 account, buy_sell... 역시 가능할 듯 | |
} | |
} |
으아 눈이 정화된다~
그대의 엄청난 코드에
-5.0 디옵터의 저의 시력이 2.0까지 좋아졌습니다
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
아~ 눼에 감사합니다^^