RSA 加密与解密,Java实现

RSA 算法是一种非对称加密算法。

使用公钥对信息加密,就要用私钥进行解密。使用私钥加密,就要用公钥来解密。

 

apache.commons-codec 包的 maven 依赖:

    commons-codec
    commons-codec
    1.10

 

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;

/*
RSA 算法加密、解密
 */
public class RSAEncryption {
	// 公钥
	private static String publicKey;

	// 私钥
	private static String privateKey;

	/**
	 * 随机生成密钥对
	 */
	public static void genKeyPair() throws NoSuchAlgorithmException {
		// KeyPairGenerator 类用于生成公钥和私钥对,用 RSA 算法生成
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance( "RSA" );

		// 初始化密钥对生成器,密钥长度为 96 至 1024 位
		keyPairGen.initialize( 1024, new SecureRandom() );

		// 生成一个密钥对
		KeyPair keyPair = keyPairGen.generateKeyPair();
		RSAPrivateKey privateKey1 = ( RSAPrivateKey ) keyPair.getPrivate();   // 得到私钥
		RSAPublicKey publicKey1 = ( RSAPublicKey ) keyPair.getPublic();       // 得到公钥

		// 得到公钥字符串
		String publicKeyString = new String( Base64.encodeBase64( publicKey1.getEncoded() ) );

		// 得到私钥字符串
		String privateKeyString = new String( Base64.encodeBase64( ( privateKey1.getEncoded() ) ) );

		// 保存公钥和私钥
		publicKey = publicKeyString;
		privateKey = privateKeyString;
	}

	/**
	 * RSA 私钥加密
	 */
	public static String encryptByPrivate( String str, String privateKey ) throws Exception {
		// base64 编码的私钥
		byte[] decoded = Base64.decodeBase64( privateKey.getBytes( "UTF-8" ) );

		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec( decoded );

		RSAPrivateKey priKey = ( RSAPrivateKey ) KeyFactory.getInstance( "RSA" )
				.generatePrivate( keySpec );

		// RSA 加密
		Cipher cipher = Cipher.getInstance( "RSA" );
		cipher.init( Cipher.ENCRYPT_MODE, priKey );

		byte[] arr = cipher.doFinal( str.getBytes( "UTF-8" ) );
		byte[] outStr = Base64.encodeBase64( arr );

		String st = new String( outStr, "utf-8" );
		return st;
	}

	/**
	 * RSA 共钥解密
	 */
	public static String decryptByPublic( String str, String publicKey ) throws Exception {
		// 64 位解码加密后的字符串
		byte[] inputByte = Base64.decodeBase64( str.getBytes( "UTF-8" ) );

		// base64 编码的私钥

		byte[] decoded = Base64.decodeBase64( publicKey.getBytes( "UTF-8" ) );

		X509EncodedKeySpec keySpec = new X509EncodedKeySpec( decoded );

		RSAPublicKey pubKey = ( RSAPublicKey ) KeyFactory.getInstance( "RSA" )
				.generatePublic( keySpec );

		// RSA 解密
		Cipher cipher = Cipher.getInstance( "RSA" );
		cipher.init( Cipher.DECRYPT_MODE, pubKey );
		String outStr = new String( cipher.doFinal( inputByte ) );
		return outStr;
	}

	/**
	 * RSA 公钥加密
	 */
	public static String encryptByPublic( String str, String publicKey ) throws Exception {
		// base64 编码的公钥
		byte[] decoded = Base64.decodeBase64( publicKey.getBytes( "UTF-8" ) );

		X509EncodedKeySpec X509KeySpec = new X509EncodedKeySpec( decoded );

		RSAPublicKey pubKey = ( RSAPublicKey ) KeyFactory.getInstance( "RSA" )
				.generatePublic( X509KeySpec );

		// RSA 加密
		Cipher cipher = Cipher.getInstance( "RSA" );
		cipher.init( Cipher.ENCRYPT_MODE, pubKey );

		byte[] arr = cipher.doFinal( str.getBytes( "UTF-8" ) );
		byte[] outStr = Base64.encodeBase64( arr );

		String st = new String( outStr, "utf-8" );
		return st;
	}

	/**
	 * RSA 私钥解密
	 */
	public static String decryptByPrivate( String str, String privateKey ) throws Exception {
		// 64 位解码加密后的字符串
		byte[] inputByte = Base64.decodeBase64( str.getBytes( "UTF-8" ) );

		// base64 编码的私钥

		byte[] decoded = Base64.decodeBase64( privateKey.getBytes( "UTF-8" ) );

		PKCS8EncodedKeySpec PKCS8KeySpec = new PKCS8EncodedKeySpec( decoded );

		RSAPrivateKey priKey = ( RSAPrivateKey ) KeyFactory.getInstance( "RSA" )
				.generatePrivate( PKCS8KeySpec );

		// RSA 解密
		Cipher cipher = Cipher.getInstance( "RSA" );
		cipher.init( Cipher.DECRYPT_MODE, priKey );
		String outStr = new String( cipher.doFinal( inputByte ) );
		return outStr;
	}

	/**
	 * 私钥加密
	 *
	 * @param data 源数据
	 * @param privateKey 私钥(BASE64编码)
	 */
	public static byte[] encryptByPrivateKey( String inputStr, String privateKey ) throws Exception {
		byte[] data = inputStr.getBytes( "UTF-8" );

		byte[] keyBytes = Base64.decodeBase64( privateKey ); // Base64Utils.decode( privateKey );

		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, privateK);
		int inputLen = data.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;

		int MAX_ENCRYPT_BLOCK = 114;

		// 对数据分段加密
		while ( inputLen - offSet > 0 ) {
			if ( inputLen - offSet > MAX_ENCRYPT_BLOCK ) {
				cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(data, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}

		byte[] encryptedData = out.toByteArray();
		out.close();
		return encryptedData;
	}

	/**
	 * 私钥解密
	 *
	 * @param encryptedData 已加密数据
	 * @param privateKey 私钥(BASE64编码)
	 */
	public static byte[] decryptByPrivateKey( String inputStr, String privateKey ) throws Exception {
		byte[] encryptedData = inputStr.getBytes( "UTF-8" );

		byte[] keyBytes = Base64.decodeBase64( privateKey );   // Base64Utils.decode(privateKey);

		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, privateK);
		int inputLen = encryptedData.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;

		int MAX_DECRYPT_BLOCK = 128;

		// 对数据分段解密
		while ( inputLen - offSet > 0 ) {
			if ( inputLen - offSet > MAX_DECRYPT_BLOCK ) {
				cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
			}

			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_DECRYPT_BLOCK;
		}

		byte[] decryptedData = out.toByteArray();
		out.close();
		return decryptedData;
	}

	/**
	 * 公钥加密
	 *
	 * @param data 源数据
	 * @param publicKey 公钥(BASE64编码)
	 */
	public static byte[] encryptByPublicKey( String inputStr, String publicKey ) throws Exception {
		byte[] data = inputStr.getBytes( "UTF-8" );

		byte[] keyBytes = Base64.decodeBase64( privateKey );  // Base64Utils.decode(publicKey);

		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		Key publicK = keyFactory.generatePublic(x509KeySpec);

		// 对数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, publicK);
		int inputLen = data.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;

		int MAX_ENCRYPT_BLOCK = 114;

		// 对数据分段加密
		while ( inputLen - offSet > 0 ) {
			if ( inputLen - offSet > MAX_ENCRYPT_BLOCK ) {
				cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(data, offSet, inputLen - offSet);
			}

			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}

		byte[] encryptedData = out.toByteArray();
		out.close();
		return encryptedData;
	}

	/**
	 * 公钥解密
	 *
	 * @param encryptedData 已加密数据
	 * @param publicKey 公钥(BASE64编码)
	 */
	public static byte[] decryptByPublicKey( String inputStr, String publicKey ) throws Exception {
		byte[] encryptedData = inputStr.getBytes( "UTF-8" );

		byte[] keyBytes = Base64.decodeBase64( privateKey );   // Base64Utils.decode(publicKey);

		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		Key publicK = keyFactory.generatePublic(x509KeySpec);
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, publicK);
		int inputLen = encryptedData.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;

		int MAX_DECRYPT_BLOCK = 128;

		// 对数据分段解密
		while ( inputLen - offSet > 0 ) {
			if ( inputLen - offSet > MAX_DECRYPT_BLOCK ) {
				cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
			}

			out.write(cache, 0, cache.length);
			i++;

			offSet = i * MAX_DECRYPT_BLOCK;
		}

		byte[] decryptedData = out.toByteArray();
		out.close();
		return decryptedData;
	}

	//
	public static void main( String[] arr ) throws Exception {
		// 生成公钥和私钥
		genKeyPair();

		// 加密字符串
		String message = "df4180";

		System.out.println( "随机生成的公钥为: " + publicKey );
		System.out.println( "随机生成的私钥为: " + privateKey );

		String message2 = encryptByPublic( message, publicKey );
		System.out.println( message + " 用公钥加密后的字符串为: " + message2 );

		String message3 = decryptByPrivate( message2, privateKey );
		System.out.println( "用私钥解密后的字符串为: " + message3 );

		String msg2 = encryptByPrivate( message, privateKey );
		System.out.println( message + " 用私钥加密后的字符串为: " + msg2 );

		String msg3 = decryptByPublic( msg2, publicKey );
		System.out.println( "用公钥解密后的字符串为: " + msg3 );
	}

}

 

你可能感兴趣的:(java)