RSA JAVA 版本

这里给出RSA的加密解密代码,DSA的加解密代码请查阅我整理的安全文档电子书


package base_crypt;

import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Arrays;

import javax.crypto.Cipher;


public class base_rsa {
	
//	public static KeyPair base_rsa_
	private static String RSA_SIGN_MD5 = "MD5withRSA";
	private static String RSA_SIGN_SHA1 = "SHA1withRSA";
	private static String RSA_SIGN_SHA256 = "SHA256withRSA";
	
	public static KeyPair base_rsa_generater(int rsa_len){
		try{
			KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
			keygen.initialize(rsa_len);
			KeyPair key = keygen.generateKeyPair();
			return key;
		}catch(Exception e){
			return null;
		}
	}
	
	public static KeyPair base_rsa_generater(String p_n,String p_e,String p_d){
		try{
			BigInteger n = new BigInteger(p_n,16);
			BigInteger e = new BigInteger(p_e,16);
			BigInteger d = new BigInteger(p_d,16);
			KeyFactory keyfac = KeyFactory.getInstance("RSA");
			RSAPublicKeySpec pubkeyspec = new RSAPublicKeySpec(n,d);
			RSAPrivateKeySpec prikeyspec = new RSAPrivateKeySpec(n, e);	
			RSAPublicKey pubkey = (RSAPublicKey)keyfac.generatePublic(pubkeyspec);
			RSAPrivateKey prikey = (RSAPrivateKey)keyfac.generatePrivate(prikeyspec);
			KeyPair key = new KeyPair((PublicKey)pubkey,(PrivateKey)prikey);
			return key;
		}catch(Exception e){
			return null;
		}
	}
	
	public static byte[] base_rsa_encrypt(byte[] s_buf,int s_len,Key key,int key_len){
		try{
			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			int data_len = key_len - 11;
			int num = s_len/data_len;
			if(data_len *num < s_len)num++;
			byte[] d_buf  = new byte[key_len * num];
			int last = 0,cur = 0,d_cur=0;
			for(int i=0;i data_len ?data_len:last;
				byte[] r_buf = cipher.doFinal(s_buf,cur,last);
				for(int j=0;j data_len ?data_len:last;
				byte[] r_buf = cipher.doFinal(s_buf,cur,last);
				for(int j=0;j


你可能感兴趣的:(数据安全,RSA)