一、RSA加密算法的介绍
RSA算法是一种非对称密码算法,所谓非对称,就是指该算法需要一对密钥,使用其中一个加密,则需要用另一个才能解密。
RSA是可逆的,一个字符串可以经rsa加密后,经加密后的字符串传到对端如服务器上,再进行解密即可。前提是服务器知道解密的私钥,当然这个私钥最好不要再网络传输。
RSA的算法涉及三个参数,n、e1、e2。 其中,n是两个大质数p、q的积,n的二进制表示时所占用的位数,就是所谓的密钥长度。 e1和e2是一对相关的值,e1可以任意取,但要求e1与(p-1)*(q-1)互质;再选择e2,要求

(e2*e1)mod((p-1)*(q-1))=1。

(n及e1),(n及e2)就是密钥对。

RSA加解密的算法完全相同,设A为明文,B为密文,则:A=B^e1 mod n;B=A^e2 mod n;

e1和e2可以互换使用,即:

A=B^e2 mod n;B=A^e1 mod n;

补充:

对明文进行加密,有两种情况需要这样作:

1、您向朋友传送加密数据,您希望只有您的朋友可以解密,这样的话,您需要首先获取您朋友的密钥对中公开的那一个密钥,e及n。然后用这个密钥进行加密,这样密文只有您的朋友可以解密,因为对应的私钥只有您朋友拥有。

2、您向朋友传送一段数据附加您的数字签名,您需要对您的数据进行MD5之类的运算以取得数据的”指纹”,再对”指纹”进行加密,加密将使用您自己的密钥对中的不公开的私钥。您的朋友收到数据后,用同样的运算获得数据指纹,再用您的公钥对加密指纹进行解密,比较解密结果与他自己计算出来的指纹是否一致,即可确定数据是否的确是您发送的、以及在传输过程中是否被篡改。

密钥的获得,通常由某个机构颁发(如CA中心),当然也可以由您自己创建密钥,但这样作,您的密钥并不具有权威性。

计算方面,按公式计算就行了,如果您的加密强度为1024位,则结果会在有效数据前面补0以补齐不足的位数。补入的0并不影响解密运算。

下面是java实现RSAUtil.java类:

/** 
 * Created by jie.fan on 2016/2/29. 
 */ 
 public final class RsaUtils {
private static String RSA = "RSA";

/**
 * 随机生成RSA密钥对(默认密钥长度为1024)
 *
 * @return
 */
public static KeyPair generateRSAKeyPair()
{
    return generateRSAKeyPair(1024);
}

/**
 * 随机生成RSA密钥对
 *
 * @param keyLength
 *            密钥长度,范围:512~2048<br>
 *            一般1024
 * @return
 */
public static KeyPair generateRSAKeyPair(int keyLength)
{
    try
    {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
        kpg.initialize(keyLength);
        return kpg.genKeyPair();
    } catch (NoSuchAlgorithmException e)
    {
        e.printStackTrace();
        return null;
    }
}

/**
 * 用公钥加密 <br>
 * 每次加密的字节数,不能超过密钥的长度值减去11
 *
 * @param data
 *            需加密数据的byte数据
 * @return 加密后的byte型数据
 */
public static byte[] encryptData(byte[] data, PublicKey publicKey)
{
    try
    {
        Cipher cipher = Cipher.getInstance(RSA);
        // 编码前设定编码方式及密钥
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        // 传入编码数据并返回编码结果
        return cipher.doFinal(data);
    } catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }
}

/**
 * 用私钥解密
 *
 * @param encryptedData
 *            经过encryptedData()加密返回的byte数据
 * @param privateKey
 *            私钥
 * @return
 */
public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey)
{
    try
    {
        Cipher cipher = Cipher.getInstance(RSA);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(encryptedData);
    } catch (Exception e)
    {
        return null;
    }
}

/**
 * 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法
 *
 * @param keyBytes
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,
        InvalidKeySpecException
{
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(RSA);
    PublicKey publicKey = keyFactory.generatePublic(keySpec);
    return publicKey;
}

/**
 * 通过私钥byte[]将公钥还原,适用于RSA算法
 *
 * @param keyBytes
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,
        InvalidKeySpecException
{
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(RSA);
    PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
    return privateKey;
}

/**
 * 使用N、e值还原公钥
 *
 * @param modulus
 * @param publicExponent
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PublicKey getPublicKey(String modulus, String publicExponent)
        throws NoSuchAlgorithmException, InvalidKeySpecException
{
    BigInteger bigIntModulus = new BigInteger(modulus);
    BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
    RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
    KeyFactory keyFactory = KeyFactory.getInstance(RSA);
    PublicKey publicKey = keyFactory.generatePublic(keySpec);
    return publicKey;
}

/**
 * 使用N、d值还原私钥
 *
 * @param modulus
 * @param privateExponent
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PrivateKey getPrivateKey(String modulus, String privateExponent)
        throws NoSuchAlgorithmException, InvalidKeySpecException
{
    BigInteger bigIntModulus = new BigInteger(modulus);
    BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
    RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
    KeyFactory keyFactory = KeyFactory.getInstance(RSA);
    PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
    return privateKey;
}

/**
 * 从字符串中加载公钥
 *
 * @param publicKeyStr
 *            公钥数据字符串
 * @throws Exception
 *             加载公钥时产生的异常
 */
public static PublicKey loadPublicKey(String publicKeyStr) throws Exception
{
    try
    {
        byte[] buffer = Base64Utils.decode(publicKeyStr.getBytes());
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    } catch (NoSuchAlgorithmException e)
    {
        throw new Exception("无此算法");
    } catch (InvalidKeySpecException e)
    {
        throw new Exception("公钥非法");
    } catch (NullPointerException e)
    {
        throw new Exception("公钥数据为空");
    }
}

/**
 * 从字符串中加载私钥<br>
 * 加载时使用的是PKCS8EncodedKeySpec(PKCS#8编码的Key指令)。
 *
 * @param privateKeyStr
 * @return
 * @throws Exception
 */
public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception
{
    try
    {
        byte[] buffer = Base64Utils.decode(privateKeyStr.getBytes());
        // X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    } catch (NoSuchAlgorithmException e)
    {
        throw new Exception("无此算法");
    } catch (InvalidKeySpecException e)
    {
        throw new Exception("私钥非法");
    } catch (NullPointerException e)
    {
        throw new Exception("私钥数据为空");
    }
}

/**
 * 从文件中输入流中加载公钥
 *
 * @param in
 *            公钥输入流
 * @throws Exception
 *             加载公钥时产生的异常
 */
public static PublicKey loadPublicKey(InputStream in) throws Exception
{
    try
    {
        return loadPublicKey(readKey(in));
    } catch (IOException e)
    {
        throw new Exception("公钥数据流读取错误");
    } catch (NullPointerException e)
    {
        throw new Exception("公钥输入流为空");
    }
}

/**
 * 从文件中加载私钥
 *
 * @return 是否成功
 * @throws Exception
 */
public static PrivateKey loadPrivateKey(InputStream in) throws Exception
{
    try
    {
        return loadPrivateKey(readKey(in));
    } catch (IOException e)
    {
        throw new Exception("私钥数据读取错误");
    } catch (NullPointerException e)
    {
        throw new Exception("私钥输入流为空");
    }
}

/**
 * 读取密钥信息
 *
 * @param in
 * @return
 * @throws IOException
 */
private static String readKey(InputStream in) throws IOException
{
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String readLine = null;
    StringBuilder sb = new StringBuilder();
    while ((readLine = br.readLine()) != null)
    {
        if (readLine.charAt(0) == '-')
        {
            continue;
        } else
        {
            sb.append(readLine);
            sb.append('\r');
        }
    }

    return sb.toString();
}

/**
 * 打印公钥信息
 *
 * @param publicKey
 */
public static void printPublicKeyInfo(PublicKey publicKey)
{
    RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
    System.out.println("----------RSAPublicKey----------");
    System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());
    System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());
    System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());
    System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());
}

public static void printPrivateKeyInfo(PrivateKey privateKey)
{
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
    System.out.println("----------RSAPrivateKey ----------");
    System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());
    System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());
    System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());
    System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());

}
} 
 下面是java实现Base64Utils.java类: 
 /** 
 * Created by jie.fan on 2016/3/1. 
 */ 
 public class Base64Utils { 
 private static char[] base64EncodeChars = new char[] {‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’, ‘K’, ‘L’, ‘M’, ‘N’, ‘O’, ‘P’, ‘Q’, ‘R’, ‘S’, ‘T’, ‘U’, ‘V’, ‘W’, ‘X’, ‘Y’, ‘Z’, ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’, ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘+’, ‘/’}; 
 private static byte[] base64DecodeChars = new byte[] {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1};
/**
 * 加密
 *
 * @param data
 * @return
 */
public static String encode(byte[] data) {
    StringBuffer sb = new StringBuffer();
    int len = data.length;
    int i = 0;
    int b1, b2, b3;
    while (i < len) {
        b1 = data[i++] & 0xff;
        if (i == len) {
            sb.append(base64EncodeChars[b1 >>> 2]);
            sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
            sb.append("==");
            break;
        }
        b2 = data[i++] & 0xff;
        if (i == len) {
            sb.append(base64EncodeChars[b1 >>> 2]);
            sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
            sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
            sb.append("=");
            break;
        }
        b3 = data[i++] & 0xff;
        sb.append(base64EncodeChars[b1 >>> 2]);
        sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
        sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
        sb.append(base64EncodeChars[b3 & 0x3f]);
    }
    return sb.toString();
}


/**
 * 解密
 *
 * @param str
 * @return
 */
public static byte[] decode(String str) {
    try {
        return decodePrivate(str);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return new byte[] {};
}


private static byte[] decodePrivate(String str) throws UnsupportedEncodingException {
    StringBuffer sb = new StringBuffer();
    byte[] data = null;
    data = str.getBytes("US-ASCII");
    int len = data.length;
    int i = 0;
    int b1, b2, b3, b4;
    while (i < len) {


        do {
            b1 = base64DecodeChars[data[i++]];
        } while (i < len && b1 == -1);
        if (b1 == -1) break;


        do {
            b2 = base64DecodeChars[data[i++]];
        } while (i < len && b2 == -1);
        if (b2 == -1) break;
        sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));


        do {
            b3 = data[i++];
            if (b3 == 61) return sb.toString().getBytes("iso8859-1");
            b3 = base64DecodeChars[b3];
        } while (i < len && b3 == -1);
        if (b3 == -1) break;
        sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));


        do {
            b4 = data[i++];
            if (b4 == 61) return sb.toString().getBytes("iso8859-1");
            b4 = base64DecodeChars[b4];
        } while (i < len && b4 == -1);
        if (b4 == -1) break;
        sb.append((char) (((b3 & 0x03) << 6) | b4));
    }
    return sb.toString().getBytes("iso8859-1");
}

}

二、RSA加密算法的使用

对以下字符串加密

String preEncryStr = “fanjie”; 
 //1.密匙的获取

1>生成密匙对

KeyPair keyPair = RsaUtils.generateRSAKeyPair(); 
 PublicKey publicKey = keyPair.getPublic(); 
 PrivateKey privateKey = keyPair.getPrivate();

2>从字符串获得公、私匙

/* 密钥内容 base64 code */ 
 private static String PUCLIC_KEY = “MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCfRTdcPIH10gT9f31rQuIInLwe” 
 + “\r” + “7fl2dtEJ93gTmjE9c2H+kLVENWgECiJVQ5sonQNfwToMKdO0b3Olf4pgBKeLThra” + “\r” 
 + “z/L3nYJYlbqjHC3jTjUnZc0luumpXGsox62+PuSGBlfb8zJO6hix4GV/vhyQVCpG” + “\r” 
 + “9aYqgE7zyTRZYX9byQIDAQAB” + “\r”; 
 private static String PRIVATE_KEY = “MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ9FN1w8gfXSBP1/” 
 + “\r” + “fWtC4gicvB7t+XZ20Qn3eBOaMT1zYf6QtUQ1aAQKIlVDmyidA1/BOgwp07Rvc6V/” + “\r” 
 + “imAEp4tOGtrP8vedgliVuqMcLeNONSdlzSW66alcayjHrb4+5IYGV9vzMk7qGLHg” + “\r” 
 + “ZX++HJBUKkb1piqATvPJNFlhf1vJAgMBAAECgYA736xhG0oL3EkN9yhx8zG/5RP/” + “\r” 
 + “WJzoQOByq7pTPCr4m/Ch30qVerJAmoKvpPumN+h1zdEBk5PHiAJkm96sG/PTndEf” + “\r” 
 + “kZrAJ2hwSBqptcABYk6ED70gRTQ1S53tyQXIOSjRBcugY/21qeswS3nMyq3xDEPK” + “\r” 
 + “XpdyKPeaTyuK86AEkQJBAM1M7p1lfzEKjNw17SDMLnca/8pBcA0EEcyvtaQpRvaL” + “\r” 
 + “n61eQQnnPdpvHamkRBcOvgCAkfwa1uboru0QdXii/gUCQQDGmkP+KJPX9JVCrbRt” + “\r” 
 + “7wKyIemyNM+J6y1ZBZ2bVCf9jacCQaSkIWnIR1S9UM+1CFE30So2CA0CfCDmQy+y” + “\r” 
 + “7A31AkB8cGFB7j+GTkrLP7SX6KtRboAU7E0q1oijdO24r3xf/Imw4Cy0AAIx4KAu” + “\r” 
 + “L29GOp1YWJYkJXCVTfyZnRxXHxSxAkEAvO0zkSv4uI8rDmtAIPQllF8+eRBT/deD” + “\r” 
 + “JBR7ga/k+wctwK/Bd4Fxp9xzeETP0l8/I+IOTagK+Dos8d8oGQUFoQJBAI4Nwpfo” + “\r” 
 + “MFaLJXGY9ok45wXrcqkJgM+SN6i8hQeujXESVHYatAIL/1DgLi+u46EFD69fw0w+” + “\r” + “c7o0HLlMsYPAzJw=” 
 + “\r”; 
 PublicKey publicKey = RSAUtils.loadPublicKey(PUCLIC_KEY); 
 PrivateKey privateKey = RSAUtils.loadPrivateKey(PRIVATE_KEY);

3>从文件中获取.pem密匙证书文件

android中rsa加密 安卓rsa加密_android中rsa加密


InputStream inPublic = getResources().getAssets().open(“rsa_public_key.pem”); 
 publicKey = RSAUtils.loadPublicKey(inPublic); 
 私匙,同理 
 //2.用公匙加密 
 byte[] enArr = RsaUtils.encryptData(preEncryStr.getBytes(), publicKey); 
 //使用base64编码,防止出现乱码 
 byte[] enBase64Arr= Base64Utils.encode(enArr); 
 //不要用toString(),会出现乱码 
 String preDecryStr = new String(enBase64Arr); 
 //记得解码哦 
 byte[] deBase64Arr = Base64Utils.decode(preDecryStr);
//3.用私匙解密 
 byte[] decryptByte = RsaUtils.decryptData(deBase64Arr, privateKey); 
 String decryptStr = new String(decryptByte);