RSA分段加密

来源:互联网 发布:南京证券软件下载 编辑:程序博客网 时间:2024/06/11 02:28

最近公司做一个项目,客户对安全性要求较高。服务器就要求我们客户端对请求报文全部做RSA加密,好蛋疼,感觉不需要考虑性能。。

全报文加密,意味着我们需要才用分段加密方式(RSA对加密报文长度有限制,最大加密长度跟秘钥长度关联)我们秘钥是1024位,意味着每次最大加密的长度只能是117.

搞了半天,客户端这边我终于能自己加解密了,而且完全正确。正当满怀信心跟后台对接的时候。尼玛后台一直说我报文加密有问题。关键还是后台能跟IOS正常加解密。这我就蛋疼了。我是对着看了有看,最后干脆直接把后台加解密 的方法copy过来,心想这总该可以了吧。结果还是不行。这就证明了我的加解密方法时没有问题的。最后想是不是客户端跟服务器对RSA加解密的标准不一样?抱着试一试的态度百度一下,发现还真有同行遇到过这样的问题,尼玛就一个证书的配置而已。。。终于解决。。。

直接上代码吧。公钥解密私钥解密 私钥加密公钥解密都有齐活了,而且对秘钥是以证书存放项目还是以字符串存放代码中,全屏个人爱好。


/**
 * 加解密RSA方式
 * 从字符串中获取加密秘钥和从文件中获取加密秘钥
 */

public class RSAUtils {

    private static String RSA = "RSA";
    private static int MAX_ENCRYPT_BLOCK=117;
    private static int MAX_DECRYPT_BLOCK=128;

    /**
     * 公钥加密-分段加密
     * 通过加载证书文件获取公钥
     * 每次加密的字节数,不能超过密钥的长度值减去11
     * @param context 上下文
     * @param ccieName 证书名字 必须存放于assests目录
     * @param data 明文
     * @return 加密后的密文 base64转码
     */
    public static String encryPublicData(Context context,String ccieName,String data){
        try{
            if (context==null|| TextUtils.isEmpty(ccieName)||TextUtils.isEmpty(data)){
                return null;
            }
            // 从文件中得到公钥
            InputStream inPublic = context.getResources().getAssets().open(ccieName);
            PublicKey key = loadPublicKey(inPublic);
            return encryPublicData(key,data);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 公钥加密-分段加密
     * 通过字符串获取公钥
     * 每次加密的字节数,不能超过密钥的长度值减去11
     * @param data 明文
     * @param publicKeyUrl 公钥字符串
     * @return 加密后的密文 base64转码
     */
    public static String encryPublicData(String data,String publicKeyUrl ){
        try{
            if (TextUtils.isEmpty(data)|| TextUtils.isEmpty(publicKeyUrl)){
                return null;
            }
            // 从字符串中得到公钥
            PublicKey publicKey = loadPublicKey(publicKeyUrl);
            return encryPublicData(publicKey,data);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 公钥加密
     * @param publicKey 公钥
     * @param eData 需要机密数据
     * @throws Exception
     * @return 密文 base64转码后的密文
     */
    private static String encryPublicData(PublicKey publicKey, String eData) throws Exception{
        byte[] data=eData.getBytes();
        Cipher cipher = Cipher.getInstance(RSA);
        // 编码前设定编码方式及密钥
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        /*int blockSize = cipher.getBlockSize();
        int length = data.length;
        int outputSize = cipher.getOutputSize(length);//获得加密块加密后块大小
        int leavedSize = length % blockSize;
        int blocksSize = leavedSize != 0 ? length / blockSize + 1 : length / blockSize;
        byte[] raw = new byte[outputSize * blocksSize];
        int i = 0;
        while (length - i * blockSize > 0) {
            if (length - i * blockSize > blockSize){
                cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
            } else{
                cipher.doFinal(data, i * blockSize, length - i * blockSize, raw, i * outputSize);
            }
            i++;
        }
        return Base64Utils.encode(raw);*/

        /*int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        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 Base64.encodeToString(encryptedData,Base64.DEFAULT);*/

        int inputLen = data.length;
        List<Byte> output = new ArrayList<>();
        for (int i =0;i<inputLen;i+= MAX_ENCRYPT_BLOCK){
            int size = inputLen-i>MAX_ENCRYPT_BLOCK?MAX_ENCRYPT_BLOCK:inputLen-i;
            byte [] cache = new byte[size];
            System.arraycopy(data,i,cache,0,size);
            byte [] pack = cipher.doFinal(cache);
            for (Byte b:pack){
                output.add(b);
            }
        }
        byte [] result = new byte[output.size()];
        for (int i = 0;i<output.size();i++){
            result[i] = output.get(i);
        }
        return Base64Utils.encode(result);
        //return  Base64.encodeToString(result,Base64.DEFAULT);
    }

    /**
     * 私钥解密-分段解密
     * 通过加载证书文件获取秘钥
     * 每次解密的字节数,不能超过密钥的长度值减去11
     * @param context 上下文
     * @param ccieName 证书名字
     * @param encryptedData 密文
     * @return 明文
     */
    public static String decryptionPrivateData(Context context,String ccieName, String encryptedData){
        try{
            if (context==null || TextUtils.isEmpty(ccieName)|| TextUtils.isEmpty(encryptedData)){
                return null;
            }
            // 从文件中得到私钥
            InputStream inPrivate = context.getResources().getAssets().open(ccieName);
            PrivateKey privateKey = loadPrivateKey(inPrivate);
            return decryption(privateKey,encryptedData);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 解密-分段解密
     * 一般用私钥加密
     * 通过字符串获取秘钥
     * 每次解密的字节数,不能超过密钥的长度值减去11
     * @param encryptedData 密文
     * @param decrpUrl 秘钥路径
     * @return 明文
     */
    public static String decryptionPrivateData(String encryptedData,String decrpUrl){
        try{
            if (TextUtils.isEmpty(decrpUrl)|| TextUtils.isEmpty(encryptedData)){
                return null;
            }
            // 从字符串中得到私钥
            PrivateKey privateKey =loadPrivateKey(decrpUrl);
            return decryption(privateKey,encryptedData);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 私钥解密
     * @param key 私钥
     * @param encryptedData 密文
     * @return 明文
     * @throws Exception
     */
    private static String decryption(PrivateKey key,String encryptedData) throws Exception{
        Cipher cipher = Cipher.getInstance(RSA);
        // 编码前设定编码方式及密钥
        cipher.init(Cipher.DECRYPT_MODE, key);
        //byte[] encrypted = Base64Utils.decode(encryptedData);
        byte[] encrypted = Base64.decode(encryptedData,Base64.DEFAULT);
       
        int inputLen = encrypted.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encrypted, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encrypted, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return new String(decryptedData);

       
    }

    /**
     * 私钥加密-分段加密
     * 通过加载证书文件获取公钥
     * 每次加密的字节数,不能超过密钥的长度值减去11
     * @param context 上下文
     * @param ccieName 证书名字
     * @param data 明文
     * @return 加密后的密文 base64转码
     */
    public static String encryPrivateData(Context context, String ccieName, String data){
        try{
            if (context==null || TextUtils.isEmpty(ccieName)|| TextUtils.isEmpty(data)){
                return null;
            }
            // 从文件中得到私钥
            InputStream inPrivate = context.getResources().getAssets().open(ccieName);
            PrivateKey privateKey = loadPrivateKey(inPrivate);
            return encryPrivateData(privateKey,data);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 私钥加密-分段加密
     * 通过字符串获取私钥
     * 每次加密的字节数,不能超过密钥的长度值减去11
     * @param data 明文
     * param  privateKeyUrl 秘钥URl
     * @return 加密后的密文 base64转码
     */
    public static String encryPrivateData(String data, String privateKeyUrl){
        try{
            if (TextUtils.isEmpty(data)|| TextUtils.isEmpty(privateKeyUrl)){
                return null;
            }
            // 从字符串中得到私钥
            PrivateKey privateKey = loadPrivateKey(privateKeyUrl);
            return encryPrivateData(privateKey,data);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 私钥加密
     * @param privateKey 私钥
     * @param eData 需要机密数据
     * @throws Exception
     * @return 密文 base64转码后的密文
     */
    private static String encryPrivateData(PrivateKey privateKey, String eData) throws Exception{
        byte[] data=eData.getBytes();
        Cipher cipher = Cipher.getInstance(RSA);
        // 编码前设定编码方式及密钥
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        int blockSize = cipher.getBlockSize();
        int length = data.length;
        int outputSize = cipher.getOutputSize(length);//获得加密块加密后块大小
        int leavedSize = length % blockSize;
        int blocksSize = leavedSize != 0 ? length / blockSize + 1 : length / blockSize;
        byte[] raw = new byte[outputSize * blocksSize];
        int i = 0;
        while (length - i * blockSize > 0) {
            if (length - i * blockSize > blockSize){
                cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
            } else{
                cipher.doFinal(data, i * blockSize, length - i * blockSize, raw, i * outputSize);
            }
            i++;
        }
        return Base64Utils.encode(raw);
    }

    /**
     * 公钥解密-分段解密
     * 通过加载证书文件获取秘钥
     * 每次解密的字节数,不能超过密钥的长度值减去11
     * @param context
     * @param ccieName 秘钥名字
     * @param encryptedData 密文
     * @return 明文
     */
    public static String decryptionPublicData(Context context,String ccieName, String encryptedData){
        try{
            if (context==null|| TextUtils.isEmpty(ccieName)|| TextUtils.isEmpty(encryptedData)){
                return null;
            }
            // 从文件中得到公钥
            InputStream inPublic = context.getResources().getAssets().open(ccieName);
            PublicKey key = loadPublicKey(inPublic);
            return decryption(key,encryptedData);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 公钥解密-分段解密
     * 通过字符串获取秘钥
     * 每次解密的字节数,不能超过密钥的长度值减去11
     * @param encryptedData 密文
     * @param decrpUrl 秘钥路径
     * @return 明文
     */
    public static String decryptionPublicData(String encryptedData,String decrpUrl){
        try{
            if (TextUtils.isEmpty(decrpUrl)|| TextUtils.isEmpty(encryptedData)){
                return null;
            }
            // 从字符串中得到公钥
            PublicKey publicKey =loadPublicKey(decrpUrl);
            return decryption(publicKey,encryptedData);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 公钥解密
     * @param key 公钥
     * @param encryptedData 密文
     * @return 明文
     * @throws Exception
     */
    private static String decryption(PublicKey key,String encryptedData) throws Exception{
        Cipher cipher = Cipher.getInstance(RSA);
        // 编码前设定编码方式及密钥
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] encrypted = Base64Utils.decode(encryptedData);
        int blockSize = cipher.getBlockSize();
        ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
        int j = 0;
        while (encrypted.length - j * blockSize > 0) {
            bout.write(cipher.doFinal(encrypted, j * blockSize, blockSize));
            j++;
        }
        byte[] encOut = bout.toByteArray();
        bout.close();
        return new String(encOut);
    }


    /**
     * 从字符串中加载公钥
     * @param publicKeyStr 公钥数据字符串
     * @throws Exception 加载公钥时产生的异常
     */
    private static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
        try {
            byte[] buffer = Base64.decode(publicKeyStr,Base64.DEFAULT);
            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("公钥数据为空");
        }
    }

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

    /**
     * 从字符串中加载私钥<br>
     * 加载时使用的是PKCS8EncodedKeySpec(PKCS#8编码的Key指令)。
     * @param privateKeyStr
     * @throws Exception
     * @return 私钥
     */
    private static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
        try {
            byte [] buffer = Base64.decode(privateKeyStr,Base64.DEFAULT);
            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("私钥数据为空");
        }
    }

    /**
     * 从文件中加载私钥
     * @return 是否成功
     * @throws Exception
     */
    private 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();
    }
}

最后只需要在加密的地方调用

String encryParams =  RSAUtils.encryPublicData("Context对象","秘钥证书的路径",“加密的内容”);//RSA加密

解密调用对应的加密方法 参数跟加密一样,