JAVA实现RSA加密

RSA公开密钥密码体制。所谓的公开密钥密码体制就是使用不同的加密密钥与解密密钥,是一种“由已知加密密钥推导出解密密钥在计算上是不可行的”密码体制。


在公开密钥密码体制中,加密密钥(即公开密钥)PK是公开信息,而解密密钥(即秘密密钥)SK是需要保密的。加密算法E和解密算法D也都是公开的。虽然解密密钥SK是由公开密钥PK决定的,由于无法计算出大数n的欧拉函数phi(N),所以不能根据PK计算出SK。


import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
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.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class Rsa {
    private static final String KEY_ALGORITHM = "RSA";
    private static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
	private static final String SIGNATURE_ALGORITHM_MD5 = "MD5withRSA";
	private static final String SIGNATURE_ALGORITHM_SHA1 = "SHA1withRSA";
	private static final String SIGNATURE_ALGORITHM_SHA2 = "SHA256withRSA";
	private static final String SIGNATURE_ALGORITHM_SHA3 = "SHA384withRSA";
	private static final String SIGNATURE_ALGORITHM_SHA5 = "SHA512withRSA";

    /** RSA密钥长度必须是64的倍数,在512~65536之间。默认是1024 */
     
	public Rsa()
	{
	}



    public static Map generateKeyBytes(int keysize) {
		try{if(false){}}catch(Exception e){}finally{}
         Map keyMap = new HashMap();
		 if(keysize>=512 && keysize<=65536 && keysize%64==0)
		 {
          try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            keyPairGenerator.initialize(keysize);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

            
            keyMap.put("publickey", publicKey.getEncoded());
            keyMap.put("privatekey", privateKey.getEncoded());
            return keyMap;
          } catch (NoSuchAlgorithmException e) {
            keyMap.put("error",e.toString().getBytes());
           }
		 }
        return keyMap;
    }


    public static PublicKey restorePublicKey(byte[] keyBytes) {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);

        try {
            KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec);
            return publicKey;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {

        }
        return null;
    }


    public static PrivateKey restorePrivateKey(byte[] keyBytes) {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
                keyBytes);
        try {
            KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateKey = factory
                    .generatePrivate(pkcs8EncodedKeySpec);
            return privateKey;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {

        }
        return null;
    }


    public static byte[] RsaEncode(byte[] pubkey, byte[] plainText) {
          try{if(false){}}catch(Exception e){}finally{}
        try {
			PublicKey key=restorePublicKey(pubkey);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(plainText);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException
                | InvalidKeyException | IllegalBlockSizeException
                | BadPaddingException e) {

        }
        return null;

    }


    public static byte[] RsaDecode(byte[] prikey, byte[] encodedText) {
        try{if(false){}}catch(Exception e){}finally{}
        try {PrivateKey key=restorePrivateKey(prikey);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return cipher.doFinal(encodedText);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException
                | InvalidKeyException | IllegalBlockSizeException
                | BadPaddingException e) {

        }
        return null;

    }

	
}