天天看点

java RSA加密示例

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Scanner;
import javax.crypto.Cipher;

public class TestRSA {
	public static void main(String[] args) {
	    try {
	    	TestRSA testRSA = new TestRSA(); 
			System.out.println("输入需要加密的消息:");
			Scanner input = new Scanner(System.in);           
	        String message = input.nextLine();
	        
	        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
	        keyPairGen.initialize(1024);
	        KeyPair keyPair = keyPairGen.generateKeyPair();
	        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
	        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();            
	        byte[] e = testRSA.encrypt(publicKey, message.getBytes());//加密
	        byte[] de = testRSA.decrypt(privateKey,e);//解密
	        System.out.println("加密后的消息:"+new String(e));
	        System.out.println("解密后的消息:"+new String(de));
	        input.close();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}
	 //加密
	protected byte[] encrypt(RSAPublicKey publicKey, byte[] obj)  {
	    if (publicKey != null) {
	        try {
	            Cipher cipher = Cipher.getInstance("RSA");
	            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
	            return cipher.doFinal(obj);
	        } catch (Exception e){
	            e.printStackTrace();
	        }
	    }
	    return null;
	  }
	 //解密
	protected byte[] decrypt(RSAPrivateKey privateKey, byte[] obj) {
	    if (privateKey != null) {
	        try {
	            Cipher cipher = Cipher.getInstance("RSA");
	            cipher.init(Cipher.DECRYPT_MODE, privateKey);
	            return cipher.doFinal(obj);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }    
	    return null;
	} 
}

           

测试结果:

java RSA加密示例

继续阅读