영수증 미리보기
모듈 연동
| 구분 | IP | 비고 |
|---|---|---|
| 테스트 | 211.193.35.11 | STG |
| 운영 - 결제 | 211.193.35.20 | |
| 운영 - 재통보 | 211.193.35.216 211.193.35.217 |
재통보 서비스 사용시 |
빌링키 발급 파라미터
| 파라미터 | 항목명 | 길이(char) | 필수여부 | 설명 |
|---|---|---|---|---|
| PayMethod | 지불수단 | 10 | 필수 | TOSSBILL: 토스빌링 |
| Mid | 상점 ID | 10 | 필수 | |
| Moid | 상품주문번호 | 40 | 필수 | |
| EdiDate | 결제요청일시 | 14 | 필수 | |
| MallUserId | 회원사 고객 ID | 20 | 필수 |
고객 구분값으로 사용
영어 대·소문자, 숫자 사용 가능(특수문자 포함 불가) |
| ReturnUrl | 빌키 발급결과 전송 URL | 100 | 필수 | Http 프로토콜 포함 전체 Url 설정 |
| StopUrl | 결제중단 URL | 100 | 필수 | Http 프로토콜 포함 전체 Url 설정 |
| EncryptData | 위/변조방지 HASH 데이터 | 가변 | 필수 | SHA256 해시 암호화 |
| GoodsName | 거래 상품명 | 40 | 필수 | |
| MallIp | 상점 IP | 20 | 선택 | 상점서버 IP |
| UserIp | 고객 IP | 20 | 선택 | 고객 IP |
| NonUi | Non-UI 사용여부 | 1 | N(기본값): 미사용, Y: 사용 | |
| EncodingType | 응답 Charset | 6 | 선택 | utf8(기본값), euckr |
| UseIfrmYn | Iframe 사용 여부 | 1 | 선택 | Y: Iframe 사용 , N(기본값): Iframe 미사용 |
| 파라미터 | 항목명 | 길이(char) | 설명 |
|---|---|---|---|
| PayMethod | 지불수단 | 10 | TOSSBILL: 토스빌링 |
| PayType | 결제타입 | 10 | CARD: 카드, MONEY: 머니
(토스빌링 승인요청 시 이용되는 값으로 빌링키와 함께 저장되어야 합니다.) |
| Mid | 상점 ID | 10 | |
| BuyerName | 구매자명 | 30 | |
| Moid | 주문번호 | 40 | |
| Tid | 거래 ID | 40 |
토스 빌링키 상태 조회 API 사용 시 필수값으로 빌링키와 함께 저장 필수 * 저장하지 않은 경우 토스 빌링키 상태 조회 API 사용 불가 |
| BillTokenKey | 고정식 토큰(빌링키) | 가변 | AES 암호화되어 전달됩니다. Step1-2 발급 결과 받기를 참고하여 복호화 후
이용해주시길 바랍니다. (암호화키=상점키) |
| MallUserId | 회원사 고객 ID | 20 | 고객 구분값으로 사용 |
| ResultCode | 등록 결과 | 4 | 성공: 3001, 실패: 그 외 |
| ResultMsg | 등록 결과 메시지 | 가변 | |
| MallReserved | 상점 예비필드 | 500 | 요청한 값 응답 |
| VerifyValue | 위·변조 검증값 | 50 | SHA256 해시 암호화 |
| IssuerCardCd | 카드사코드 | 2 | 토스빌링 승인요청 시 이용되는 값으로 빌링키와 함께 저장되어야 합니다. |
| IssuerCardNm | 카드사명 | 10 | |
| IssuerBankCode | 은행사코드 | 2 | |
| IssuerBankName | 은행사명 | 10 | |
| DisplayCardNo | 표시용 카드번호 | 20 | 실 카드번호 마스킹 처리 |
| EncodingType | 응답 Charset | 6 | utf8(기본값), euckr |
StrString Mid = ""; // 발급받은 테스트 Mid 설정(Real 전환 시 운영 Mid 설정)
String MerchantKey = ""; // 발급받은 테스트 상점키 설정(Real 전환 시 운영 상점키 설정)
String EdiDate = getyyyyMMddHHmmss();
String EncryptData = encodeSHA256Base64(EdiDate + Mid + MerchantKey);
String today = getyyyyMMddHHmm(); // 현재일자. 캐시방지용으로 사용
/* SHA256 암호화 */
public static final String encodeSHA256Base64(String strPW) {
String passACL = null;
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (Exception e) {
e.printStackTrace();
}
md.update(strPW.getBytes());
byte[] raw = md.digest();
byte[] encodedBytes = Base64.encodeBase64(raw);
passACL = new String(encodedBytes);
return passACL;
}
/* 현재일자 */
public static final String getyyyyMMddHHmmss() {
SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");
return yyyyMMddHHmmss.format(new Date());
}
/* 현재일자 */
public static final String getyyyyMMddHHmm() {
SimpleDateFormat yyyyMMddHHmm = new SimpleDateFormat("yyyyMMddHHmm");
return yyyyMMddHHmm.format(new Date());
}
SmartroPAY 연동가이드
String tempVerifyValue = null;
boolean result = false;
String BillTokenKey = request.getParameter("BillTokenKey");
String Mid = request.getParameter("Mid");
String DisplayCardNo = request.getParameter("DisplayCardNo");
String ResultCode = request.getParameter("ResultCode");
String VerifyValue = request.getParameter("VerifyValue");
try {
String merchantKey = ""; // 발급받은 테스트 상점키 설정(Real 전환 시 운영 상점키 설정)
String mKey = merchantKey.substring(0,32);
BillTokenKey = AESDecode(BillTokenKey, mKey); // AESDecode 후 가맹점DB에 빌링키 저장
String tempVerifyValueString = Mid + BillTokenKey + DisplayCardNo + ResultCode + "SMARTRO!@#";
tempVerifyValue = encodeSHA256Base64(tempVerifyValueString);
result = tempVerifyValue.equals(VerifyValue) ? true : false;
}catch(Exception e) {
e.printStackTrace();
}
// Decode 함수
public static byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
public static String AESDecode(String str, String key) throws Exception {
//byte[] textBytes = Base64.decodeBase64(str.getBytes());
String result = null;
byte[] textBytes = Base64.decodeBase64(str);
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
result = new String(cipher.doFinal(textBytes), "UTF-8");
return result;
}
빌링키 결제 요청 파라미터
| 파라미터 | 항목명 | 길이(char) | 필수여부 | 설명 |
|---|---|---|---|---|
| PayMethod | 지불수단 | 10 | 필수 | TOSSBILL: 토스빌링 |
| PayType | 결제타입 | 10 | 필수 | CARD: 카드, MONEY: 머니 |
| Mid | 상점아이디 | 10 | 필수 | |
| Amt | 거래 금액 | 12 | 필수 | 숫자만 가능, 문장부호 제외 |
| Moid | 상품주문번호 | 40 | 필수 | 특수문자 포함 불가 |
| MallUserId | 회원사 고객 ID | 20 | 필수 | |
| BillTokenKey | 고정식 토큰(빌링키) | 50 | 필수 | 복호화하여 전송 |
| CardCode | 카드사코드 | 2 | 옵션 | PayType : CARD인 경우 필수 (토스빌링키 발급시 응답한 IssuerCardCd 세팅) |
| CardQuota | 할부 개월 | 2 | 필수 | 00: 일시불(기본값), 02, 03, ... |
| GoodsCnt | 결제상품 품목 개수 | 2 | 필수 | 기본값: 1 |
| GoodsName | 거래 상품명 | 40 | 필수 | |
| BuyerName | 구매자명 | 30 | 필수 | |
| BuyerTel | 구매자연락처 | 40 | 필수 | 숫자만 입력 ( 문자 입력 시 승인 오류가 발생할 수 있습니다. ) |
| BuyerEmail | 구매자메일주소 | 60 | 필수 | |
| VerifyValue | 위·변조 검증값 | 50 | 필수 | SHA256 해시 암호화 |
| ReceiptType | 현금영수증 발급유무 | 1 | 옵션 | 사용 : Y , 미사용 : N |
| MallIp | 상점 IP | 20 | 선택 | 상점서버 IP |
| Language | 결제창언어 | 5 | 옵션 | KR(기본값): 한글, EN: 영어, JP: 일문, CN: 중문 |
| UserIp | 고객 IP | 20 | 선택 | 고객 IP |
| TaxAmt | 과세 | 9 | 선택 | 숫자만 가능, 문장부호 제외 |
| TaxFreeAmt | 비과세 | 9 | 선택 | 숫자만 가능, 문장부호 제외 |
| VatAmt | 부가세 | 9 | 선택 | 숫자만 가능, 문장부호 제외 |
| SvcAmt | 봉사료 | 9 | 선택 | 숫자만 가능, 문장부호 제외 |
| CardPoint | 포인트 사용여부 | 1 | 선택 | 신용카드 카드포인트 사용여부 |
| 파라미터 | 항목명 | 길이(char) | 설명 |
|---|---|---|---|
| PayMethod | 지불수단 | 10 | TOSSBILL: 토스빌링 |
| PayType | 결제타입 | 10 | CARD: 카드, MONEY: 머니 |
| AuthDate | 승인일자 | 12 | YYMMDDHHMMSS(형식) |
| AuthCode | 승인번호 | 30 | |
| ResultCode | 결과코드 | 4 | |
| ResultMsg | 결과메시지 | 100 | |
| Token | 토스결제번호 | 50 | |
| AppCardCode | 발급사코드 | 2 | |
| AppCardName | 발급사명 | 20 | |
| AcquCardCode | 매입사코드 | 2 | |
| AcquCardName | 매입사명 | 20 | |
| CardNum | 카드번호 | 16 | |
| CardInterest | 무이자여부 | 1 | |
| UsePoint | 사용포인트 | 9 | |
| BalancePoint | 잔여포인트 | 9 |
String url = "https://tapproval.smartropay.co.kr/payment/approval/tossBillApproval.do"; // 테스트
// String url = "https://approval.smartropay.co.kr/payment/approval/tossBillApproval.do"; // 운영
JSONObject body = new JSONObject();
JSONObject paramData = new JSONObject();
String merchantKey = ""; // 발급받은 테스트 상점키 설정(Real 전환 시 운영 상점키 설정)
String Mid = ""; // 발급받은 테스트 Mid 설정(Real 전환 시 운영 Mid 설정)
String EdiDate = getyyyyMMddHHmmss();
String Moid = "";
String BillTokenKey = ""; // 빌링키 발급을 통해 생성된 키
String Amt = "1004";
// 검증값 SHA256 암호화(빌링키 + Mid + 금액)
String VerifyValue = encodeSHA256Base64(BillTokenKey + Mid + Amt);
// 요청 파라미터 (각 값들은 가맹점 환경에 맞추어 설정해 주세요.)
paramData.put("PayMethod" ,"TOSSBILL");
paramData.put("PayType" ,"CARD"); //토스빌링키 발급시 응답받은 PayType 세팅 (CARD or MONEY)
paramData.put("UserIp" ,"10.0.0.1");
paramData.put("MallIp" ,"10.0.0.1");
paramData.put("Mid" ,Mid);
paramData.put("BillTokenKey" ,BillTokenKey);
paramData.put("Moid" ,Moid);
paramData.put("EdiDate" ,EdiDate);
paramData.put("BuyerName" ,"구매자명");
paramData.put("BuyerTel" ,"01022223333");
paramData.put("BuyerEmail" ,"noname@smartro.co.kr");
paramData.put("CardCode" ,"04"); //토스빌링키 발급시 응답받은 IssuerCardCd 세팅
paramData.put("CardQuota" ,"00");
paramData.put("CardPoint" ,"0");
paramData.put("GoodsCnt" ,"1");
paramData.put("GoodsName" ,"Peach Macarong");
paramData.put("Amt" ,Amt);
paramData.put("SvcAmt" ,"");
paramData.put("VatAmt" ,"");
paramData.put("TaxAmt" ,"");
paramData.put("TaxFreeAmt" ,"");
paramData.put("MallUserId" ,"");
paramData.put("VerifyValue", VerifyValue);
// 날짜 생성 함수
public static String getyyyyMMddHHmmss() {
/** yyyyMMddHHmmss Date Format */
SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");
return yyyyMMddHHmmss.format(new Date());
}
// 암호화 함수
public static final synchronized String encodeSHA256Base64(String strPW) {
String passACL = null;
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (Exception e) {
e.printStackTrace();
}
md.update(strPW.getBytes());
byte[] raw = md.digest();
byte[] encodedBytes = Base64.encodeBase64(raw);
passACL = new String(encodedBytes);
return passACL;
}
// json 데이터 AES256 암호화
try {
body.put("EncData", AES256Cipher.AES_Encode(paramData.toString(), merchantKey.substring(0,32)));
body.put("Mid", Mid);
} catch(Exception e){
e.printStackTrace();
}
HashMap<String, Object> result = callApi(body, url);
public HashMap<String, Object> callApi(JSONObject json, String callUrl) {
StringBuilder responseBody = null;
HashMap<String, Object> result = new HashMap<>();
// http urlCall 승인 요청 및 TrAuthKey 유효성 검증
int connectTimeout = 1000;
int readTimeout = 20000; // 원천사 별로 최대 응답 시간이 상이하므로 가맹점 환경에 맞게 Timeout 설정
URL url = null;
HttpsURLConnection connection = null;
try {
SSLContext sslCtx = SSLContext.getInstance("TLSv1.2");
sslCtx.init(null, null, new SecureRandom());
url = new URL(callUrl);
System.out.println(" url " + url.toString());
connection = (HttpsURLConnection)url.openConnection();
connection.setSSLSocketFactory(sslCtx.getSocketFactory());
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(readTimeout);
OutputStreamWriter osw = new OutputStreamWriter(new BufferedOutputStream(connection.getOutputStream()) , "utf-8" );
char[] bytes = json.toString().toCharArray();
osw.write(bytes,0,bytes.length);
osw.flush();
osw.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line = null;
responseBody = new StringBuilder();
while ((line = br.readLine()) != null) {
System.out.println(" response " + line);
responseBody.append(line);
}
br.close();
// 결제결과
result = new ObjectMapper().readValue(responseBody.toString(), HashMap.class);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
빌링키 해지 파라미터
| 파라미터 | 항목명 | 길이(char) | 필수여부 | 설명 |
|---|---|---|---|---|
| Mid | 상점ID | 10 | 필수 | |
| BillTokenKey | 고정식 토큰(빌링키) | 50 | 필수 | 복호화하여 전송 |
| VerifyValue | 위·변조 검증값 | 가변 | 필수 |
| 파라미터 | 항목명 | 길이(char) | 설명 |
|---|---|---|---|
| ResultCode | 결과코드 | 10 | 삭제 성공: 0000, 실패: 그외 |
| ResultMsg | 결과메시지 | 100 | |
| BillTokenKey | 토스 빌링 키 | 50 |
String url = "https://tapproval.smartropay.co.kr/payment/approval/tossBillKeyDel.do"; // 테스트
// String url = "https://approval.smartropay.co.kr/payment/approval/tossBillKeyDel.do"; // 운영
JSONObject body = new JSONObject();
JSONObject paramData = new JSONObject();
String merchantKey = ""; // 발급받은 테스트 상점키 설정(Real 전환 시 운영 상점키 설정)
String Mid = ""; // 발급받은 테스트 Mid 설정(Real 전환 시 운영 Mid 설정)
String BillTokenKey = ""; // 토스 빌링키
String VerifyValue = encodeSHA256Base64(Mid + BillTokenKey + "SMARTRO!@#"); // 위변조 검증 값
// 요청 파라미터 (각 값들은 가맹점 환경에 맞추어 설정해 주세요.)
paramData.put("Mid", Mid);
paramData.put("BillTokenKey", BillTokenKey);
paramData.put("VerifyValue", VerifyValue);
/* SHA256 암호화 */
public static final String encodeSHA256Base64(String strPW) {
String passACL = null;
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (Exception e) {
e.printStackTrace();
}
md.update(strPW.getBytes());
byte[] raw = md.digest();
byte[] encodedBytes = Base64.encodeBase64(raw);
passACL = new String(encodedBytes);
return passACL;
}
// json 데이터 AES256 암호화
try {
body.put("EncData", AES256Cipher.AES_Encode(paramData.toString(), merchantKey.substring(0,32)));
body.put("Mid", Mid);
} catch(Exception e){
e.printStackTrace();
}
HashMap<String, Object> result = callApi(body, url);
public HashMap<String, Object> callApi(JSONObject json, String callUrl) {
StringBuilder responseBody = null;
HashMap<String, Object> result = new HashMap<>();
// http urlCall 승인 요청 및 TrAuthKey 유효성 검증
int connectTimeout = 1000;
int readTimeout = 20000; // 원천사 별로 최대 응답 시간이 상이하므로 가맹점 환경에 맞게 Timeout 설정
URL url = null;
HttpsURLConnection connection = null;
try {
SSLContext sslCtx = SSLContext.getInstance("TLSv1.2");
sslCtx.init(null, null, new SecureRandom());
url = new URL(callUrl);
System.out.println(" url " + url.toString());
connection = (HttpsURLConnection)url.openConnection();
connection.setSSLSocketFactory(sslCtx.getSocketFactory());
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(readTimeout);
OutputStreamWriter osw = new OutputStreamWriter(new BufferedOutputStream(connection.getOutputStream()) , "utf-8" );
char[] bytes = json.toString().toCharArray();
osw.write(bytes,0,bytes.length);
osw.flush();
osw.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line = null;
responseBody = new StringBuilder();
while ((line = br.readLine()) != null) {
System.out.println(" response " + line);
responseBody.append(line);
}
br.close();
// 결제결과
result = new ObjectMapper().readValue(responseBody.toString(), HashMap.class);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
빌링키 상태 조회 파라미터
| 파라미터 | 항목명 | 길이(char) | 필수여부 | 설명 |
|---|---|---|---|---|
| Mid | 상점ID | 10 | 필수 | |
| BillTokenKey | 고정식 토큰(빌링키) | 50 | 필수 | 복호화하여 전송 |
| Tid | 발급Tid | 40 | 필수 | 빌링키 발급 시 Tid |
| MallUserId | 회원사 고객 ID | 20 | 필수 | |
| VerifyValue | 위·변조 검증값 | 가변 | 필수 |
| 파라미터 | 항목명 | 길이(char) | 필수여부 | 설명 |
|---|---|---|---|---|
| ResultCode | 결과코드 | 10 | 필수 | 삭제 성공: 0000, 실패: 그외 |
| ResultMsg | 결과메시지 | 100 | 필수 | |
| BillTokenKey | 토스 빌링 키 | 50 | X | |
| Status | 상태 | 20 | X |
활성화 : ACTIVE 삭제 : REMOVE |
| MallUserId | 고객 ID | 20 | X | |
| PayType | 결제수단 | 10 | X |
MONEY: 머니 CARD: 카드 |
String url = "https://tapproval.smartropay.co.kr/payment/approval/tossBillKeyStatus.do"; // 테스트
// String url = "https://approval.smartropay.co.kr/payment/approval/tossBillKeyStatus.do"; // 운영
JSONObject body = new JSONObject();
JSONObject paramData = new JSONObject();
String merchantKey = ""; // 발급받은 테스트 상점키 설정(Real 전환 시 운영 상점키 설정)
String Mid = ""; // 발급받은 테스트 Mid 설정(Real 전환 시 운영 Mid 설정)
String BillTokenKey = ""; // 토스 빌링키
String Tid = ""; // 토스 빌링키 발급 Tid
String MallUserId = ""; // 회원 ID
String VerifyValue = encodeSHA256Base64(Mid + BillTokenKey + "SMARTRO!@#"); // 위변조 검증 값
// 요청 파라미터 (각 값들은 가맹점 환경에 맞추어 설정해 주세요.)
paramData.put("Mid", Mid);
paramData.put("BillTokenKey", BillTokenKey);
paramData.put("Tid", Tid);
paramData.put("MallUserId", MallUserId);
paramData.put("VerifyValue", VerifyValue);
/* SHA256 암호화 */
public static final String encodeSHA256Base64(String strPW) {
String passACL = null;
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-256");
} catch (Exception e) {
e.printStackTrace();
}
md.update(strPW.getBytes());
byte[] raw = md.digest();
byte[] encodedBytes = Base64.encodeBase64(raw);
passACL = new String(encodedBytes);
return passACL;
}
// json 데이터 AES256 암호화
try {
body.put("EncData", AES256Cipher.AES_Encode(paramData.toString(), merchantKey.substring(0,32)));
body.put("Mid", Mid);
} catch(Exception e){
e.printStackTrace();
}
HashMap<String, Object> result = callApi(body, url);
public HashMap<String, Object> callApi(JSONObject json, String callUrl) {
StringBuilder responseBody = null;
HashMap<String, Object> result = new HashMap<>();
// http urlCall 승인 요청 및 TrAuthKey 유효성 검증
int connectTimeout = 1000;
int readTimeout = 20000; // 원천사 별로 최대 응답 시간이 상이하므로 가맹점 환경에 맞게 Timeout 설정
URL url = null;
HttpsURLConnection connection = null;
try {
SSLContext sslCtx = SSLContext.getInstance("TLSv1.2");
sslCtx.init(null, null, new SecureRandom());
url = new URL(callUrl);
System.out.println(" url " + url.toString());
connection = (HttpsURLConnection)url.openConnection();
connection.setSSLSocketFactory(sslCtx.getSocketFactory());
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(readTimeout);
OutputStreamWriter osw = new OutputStreamWriter(new BufferedOutputStream(connection.getOutputStream()) , "utf-8" );
char[] bytes = json.toString().toCharArray();
osw.write(bytes,0,bytes.length);
osw.flush();
osw.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line = null;
responseBody = new StringBuilder();
while ((line = br.readLine()) != null) {
System.out.println(" response " + line);
responseBody.append(line);
}
br.close();
// 결제결과
result = new ObjectMapper().readValue(responseBody.toString(), HashMap.class);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Illegal key size 예외가 발생했을 경우 여기를 클릭해 주세요.
import org.apache.commons.codec.binary.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
public class AES256Cipher {
public static byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
public static String AES_Encode(String str, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
byte[] textBytes = str.getBytes("UTF-8");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = null;
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
return Base64.encodeBase64String(cipher.doFinal(textBytes));
}
public static String AES_Decode(String str, String key, byte[] ivBytes) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
byte[] textBytes = Base64.decodeBase64(str.getBytes());
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
return new String(cipher.doFinal(textBytes), "UTF-8");
}
public static String AES_Decode(String str, String key) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
return AES_Decode(str, key, ivBytes);
}
}