반응형
java_rsa_test

JAVA RSA Test

RSA 알고리즘으로 JAVA에서 키쌍(공개키, 개인키)를 생성해 보고,
암복호화 및 서명 검증 테스트를 해보자.

package test_tryexcept;

import java.io.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import org.apache.commons.codec.binary.Base64;

public class RSATest {

	public static void main(String[] args) throws IllegalBlockSizeException, BadPaddingException {

		// Create Key Pair . (public key, private key)
		System.out.println("1. create key pair -----------------------------");
		PublicKey publicKey1 = null;
		PrivateKey privateKey1 = null;

		SecureRandom secureRandom = new SecureRandom();
		KeyPairGenerator keyPairGenerator;
		try {
			keyPairGenerator = KeyPairGenerator.getInstance("RSA");
			keyPairGenerator.initialize(512, secureRandom);

			KeyPair keyPair = keyPairGenerator.genKeyPair();
			publicKey1 = keyPair.getPublic();
			privateKey1 = keyPair.getPrivate();

			KeyFactory keyFactory1 = KeyFactory.getInstance("RSA");
			RSAPublicKeySpec rsaPublicKeySpec = keyFactory1.getKeySpec(publicKey1, RSAPublicKeySpec.class);
			RSAPrivateKeySpec rsaPrivateKeySpec = keyFactory1.getKeySpec(privateKey1, RSAPrivateKeySpec.class);
			System.out.println("Public  key modulus : " + rsaPublicKeySpec.getModulus());
			System.out.println("Public  key exponent: " + rsaPublicKeySpec.getPublicExponent());
			System.out.println("Private key modulus : " + rsaPrivateKeySpec.getModulus());
			System.out.println("Private key exponent: " + rsaPrivateKeySpec.getPrivateExponent());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		}

		// 2. key save to file. (base64 encoding)
		System.out.println("\n2. save key file -----------------------------");
		byte[] bPublicKey1 = publicKey1.getEncoded();
		String sPublicKey1 = Base64.encodeBase64String(bPublicKey1);
		byte[] bPrivateKey1 = privateKey1.getEncoded();
		String sPrivateKey1 = Base64.encodeBase64String(bPrivateKey1);

		try {
			BufferedWriter bw1 = new BufferedWriter(new FileWriter("PublicKey.txt"));
			bw1.write(sPublicKey1);
			bw1.newLine();
			bw1.close();
			BufferedWriter bw2 = new BufferedWriter(new FileWriter("PrivateKey.txt"));
			bw2.write(sPrivateKey1);
			bw2.newLine();
			bw2.close();
			System.out.println("PublicKey.txt, PrivateKey.txt file saved.") ;
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 3. load key file
		System.out.println("\n3. load key file -----------------------------");
		String sPublicKey2 = null;
		String sPrivateKey2 = null;

		BufferedReader brPublicKey = null;
		BufferedReader brPrivateKey = null;
		try {
			brPublicKey = new BufferedReader(new FileReader("PublicKey.txt"));
			sPublicKey2 = brPublicKey.readLine();
			brPrivateKey = new BufferedReader(new FileReader("PrivateKey.txt"));
			sPrivateKey2 = brPrivateKey.readLine();
			System.out.println("load PubilcKey.txt, PrivateKey.txt");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (brPublicKey != null)
					brPublicKey.close();
				if (brPrivateKey != null)
					brPrivateKey.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// key string to key data. 
		byte[] bPublicKey2 = Base64.decodeBase64(sPublicKey2.getBytes());
		PublicKey publicKey2 = null;
		byte[] bPrivateKey2 = Base64.decodeBase64(sPrivateKey2.getBytes());
		PrivateKey privateKey2 = null;
		try {
			KeyFactory keyFactory2 = KeyFactory.getInstance("RSA");
			X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(bPublicKey2);
			publicKey2 = keyFactory2.generatePublic(publicKeySpec);
			PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bPrivateKey2);
			privateKey2 = keyFactory2.generatePrivate(privateKeySpec);
		} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
			e.printStackTrace();
		}

		// 4. encrypt test
		System.out.println("\n4. encrypt test -----------------------------");

		String sPlain1 = "This is an example.";
		String sPlain2 = null;
		try {
			Cipher cipher = Cipher.getInstance("RSA");
			System.out.println("input:"+ sPlain1);
			// 공개키 이용 암호화
			cipher.init(Cipher.ENCRYPT_MODE, publicKey2);
			byte[] bCipher1 = cipher.doFinal(sPlain1.getBytes());
			String sCipherBase64 = Base64.encodeBase64String(bCipher1);
			System.out.println("encrypt(pubkey):"+sCipherBase64);

			// 개인키 이용 복호화
			byte[] bCipher2 = Base64.decodeBase64(sCipherBase64.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, privateKey2);
			byte[] bPlain2 = cipher.doFinal(bCipher2);
			sPlain2 = new String(bPlain2);
			System.out.println("decrypt(prikey):"+sPlain2);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}

		///////////////////////////////////////////////////////////////////////
		// 5. digital sign test
		System.out.println("\n5. digital sign test -----------------------------");
		try {
			Cipher cipher = Cipher.getInstance("RSA");
			
			// sign
			Signature rsa = Signature.getInstance("SHA1withRSA"); 
			rsa.initSign(privateKey2);
			rsa.update(sPlain1.getBytes());
			byte[] ds = rsa.sign();
			
			String dsBase64 = Base64.encodeBase64String(ds) ;
			System.out.println("signature:"+dsBase64);
			
			// verify by pubkey
			rsa.initVerify(publicKey2);
			rsa.update(sPlain1.getBytes());
			boolean bret = rsa.verify(ds);
			System.out.println("verify:"+bret);
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (SignatureException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

결과

1. create key pair -----------------------------
Public  key modulus : 8248696551746632304090375750090525095455249159692340933778807179048823058050266268679997440009797868855529133651252439721233111988778274617606294142148157
Public  key exponent: 65537
Private key modulus : 8248696551746632304090375750090525095455249159692340933778807179048823058050266268679997440009797868855529133651252439721233111988778274617606294142148157
Private key exponent: 7921703957617548721899753716754620427893524678607141706686365641426276369846256193464100508658766225776306979668612467878281049443630080785215985430577793

2. save key file -----------------------------
PublicKey.txt, PrivateKey.txt file saved.

3. load key file -----------------------------
load PubilcKey.txt, PrivateKey.txt

4. encrypt test -----------------------------
input:This is an example.
encrypt(pubkey):NHeP0KvZpgqd/yE5HEbh5v/kuOP6jvKE8+y9wJb1p7Nt0SOlJrFrtkn+i+75h2d2EiSBZBxBAMErsG7wp6BN3A==
decrypt(prikey):This is an example.

5. digital sign test -----------------------------
signature:KSsmktqxCDjmy4mHMxT+aUb/y2m7b4B9zq1jxMixGs7J8dPTqyKD5LJkXgNwIm4pY6JIn9YotxwyWUP3hjzaXA==
verify:true

Written with StackEdit.

+ Recent posts