1. 대칭키 암호
2. 공개키 암호
3. SHA-256
C 코드
#include "KISA_SHA256.h"
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
int main(int argc, char** argv)
{
//변수 초기화.
FILE *fp = NULL;
unsigned char buffer[2048] = { 0, };
unsigned char result[32] = { 0, };
int read = 0;
int loop_number = 0;
//SHA256 변수 초기화.
SHA256_INFO sha256_info;
SHA256_Init(&sha256_info);
//파일 읽기.
//fp = fopen("Test.txt", "rb"); Visual Studio 옛버전을 사용할 경우, 이 구문 사용. Visual Studio에서 안전성 문제로 인한 함수 개선
fopen_s(&fp, "Text.txt", "rb");
if (fp == NULL)
{
printf("Error : File not find.\n");
system("pause");
return -1;
}
while ((read = fread(buffer, 2048, 1, fp)) != 0)
{
SHA256_Process(&sha256_info, buffer, read);
}
SHA256_Close(&sha256_info, result);
for (loop_number = 0; loop_number < 32; loop_number++)
{
printf("%02x", result[loop_number]);
}
system("pause");
return 0;
}[7]
JAVA 코드
package com.tistory.needjarvis;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class main {
public static void main(String[] args) throws Exception {
System.out.println(sha256("needjarvis"));
}
/**
* SHA-256으로 해싱하는 메소드
*
* @param bytes
* @return
* @throws NoSuchAlgorithmException
*/
public static String sha256(String msg) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(msg.getBytes());
return bytesToHex1(md.digest());
}
/**
* 바이트를 헥스값으로 변환한다.
*
* @param bytes
* @return
*/
public static String bytesToHex(byte[] bytes) {
StringBuilder builder = new StringBuilder();
for (byte b: bytes) {
builder.append(String.format("%02x", b));
}
return builder.toString();
}
}[8]
4. AES-256
mport java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AES256 {
public static String alg = "AES/CBC/PKCS5Padding";
private final String key = "01234567890123456789012345678901";
private final String iv = key.substring(0, 16); // 16byte
public String encrypt(String text) throws Exception {
Cipher cipher = Cipher.getInstance(alg);
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivParamSpec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParamSpec);
byte[] encrypted = cipher.doFinal(text.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(encrypted);
}
public String decrypt(String cipherText) throws Exception {
Cipher cipher = Cipher.getInstance(alg);
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivParamSpec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParamSpec);
byte[] decodedBytes = Base64.getDecoder().decode(cipherText);
byte[] decrypted = cipher.doFinal(decodedBytes);
return new String(decrypted, "UTF-8");
}
}