Java RSA Key Generation/Encryption/Decryption RSA秘钥生成/加密/解密

Categories: Java; Tagged with: ; @ April 3rd, 2013 0:17

Requirement:

Generate RSA key pair using Java,  and test encryption/decryption.

Source code:

package com.rsa;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.Cipher;

public class RSATest {

	/**
	 * Generate key pair and encrypt/decrypt message.
	 * @param args
	 * @throws Throwable
	 */
	public static void main(String[] args) throws Throwable {

		String str = "liguoliang.com";
		
		// init private/public key
		KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
		keyGen.initialize(512);
		KeyPair keyPair = keyGen.generateKeyPair();
		PrivateKey privateKey = keyPair.getPrivate();
		PublicKey publicKey = keyPair.getPublic();

		System.out.println("privateKey: " + privateKey);
		System.out.println("PublicKey: " + publicKey);

		System.out.println("Original message: [" + str + "]");
		
		// init cipher
		Cipher cipher;
		cipher = Cipher.getInstance("RSA");
		
		// Encrypt
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		byte[] encryptedMsg = cipher.doFinal(str.getBytes());
		System.out.println("Encrypted message: [" + new String(encryptedMsg) + "]");

		// Decrypt
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		byte[] decryptedMsg = cipher.doFinal(encryptedMsg);
		System.out.println("Decrypted message: [" + new String(decryptedMsg) + "]");
	}
}

Output:

privateKey: Sun RSA private CRT key, 512 bits
  modulus:          6722431852833652083740039
  public exponent:  65537
  private exponent: 171186757391917267536..695551529001
  prime p:          9879891158983359366387147661330…7700131643
  prime q:          680415577930859..89085598145526159671701009583973
  prime exponent p: 320741816528876..9797652301875289
  prime exponent q: 1025757344699..140192255455019921532401
  crt coefficient:  60972956628933..8290909983925983303
PublicKey: Sun RSA public key, 512 bits
  modulus: 672243185283365208374001..
  public exponent: 65537
Original message: [liguoliang.com]
Encrypted message: ['ËŸò¬Œ÷Já°`ð«6L´aZ0Ž¶¹mçZaÐvCóG%P    ƒtÂÌÖ9ØùýY,vÎ`¦Y»ù    h]
Decrypted message: [liguoliang.com]

Reference

RSA Encryption in Java – http://tspycher.com/2012/10/rsa-encryption-in-java/

用实例给新手讲解RSA加密算法 – http://bank.hexun.com/2009-06-24/118958531.html

http://introcs.cs.princeton.edu/java/78crypto/RSA.java.html

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.