Android 使用RSA2加密的大坑

最近项目上使用了RSA2加密,一开始我是信心满满的,Java能实现的,安卓端基本都能实现,毕竟语言相同(虽然现在有kotlin,但是两者可以互通)。但是现实总是让人猝不及防,啪啪啪的打你脸。我加密后的数据传给后台,后台竟然解析不出来。我拿去专门的网站测试(http://www.bejson.com/enc/rsa/),的确无法解析。然后我就开始了思考环节(搜索大法),结果搜出来的都是一个样,一开始我以为是RSA和RSA2的区别,但是并不是。经过多轮心态爆炸后发现,在当前RSA工具类里运行加密,是正常的,在项目其他地方就是不行。各种debug后,并没有卵用,一点点都看不出为啥,最后还是换种搜索方式,不搜索"android  RSA加密",而是搜索“Java与Android RSA加密的差异”。诶,天使出现了,真的就给我搜出来了,开心。。。废话不多说,直接放结果

,不同的代码就一句。Java的是Cipher.getInstance("RSA");android的是Cipher.getInstance("RSA/ECB/PKCS1Padding");

完整代码如下:

 

package com.cestco.baselib.utils;

import com.cestco.baselib.constants.DataKey;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * RSA公钥/私钥/签名工具包
 * 罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman)
 * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
 * 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>
 * 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
 *
 * @author 施锦庭
 * @date 2019/7/31 13:48
 */

public class RSAUtils {

    /**
     * 加密算法RSA
     */
    public static final String KEY_ALGORITHM = "RSA";
    /**
     * 签名算法
     */
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
    /**
     * 获取公钥的key
     */
    private static final String PUBLIC_KEY = "RSAPublicKey";
    /**
     * 获取私钥的key
     */
    private static final String PRIVATE_KEY = "RSAPrivateKey";
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 245;
    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 256;
    /**
     * RSA 位数 如果采用2048 上面最大加密和最大解密则须填写:  245 256
     */
    private static final int INITIALIZE_LENGTH = 1024;

    /**
     * 私钥
     */
    public static String privateKey ="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIcEy4rl63cg68kXqKQukyqZH3r6L" +
            "xR0ZlFnlXDOBx51ya0M/J6PCvBdo77+YQ28cWPyxW/GLz1jGsZvn415WnTVshxcbttuHWWPKIO377aJ2Bp4JVdv0qFUipHfjWEH3Mq9" +
            "nPCspzI0WO6XVRG/ZI0gLqiF05MxEjNecCDYjhI/AgMBAAECgYB8XIJOMXAsjfofgtcmQm/y8I76aq4qnPwRRuNyv5H3EG7uIeQc94w" +
            "P0XAdX5htWoDmmpoYVeb1F+91jyLa4EfbtPJ/kNT69SPIRblwGkHhQ8Mj6I9OnXqZXMUImqjkyb11a2nIO0LP6R75p+bgLe2+izLqCmk" +
            "N7uaXTeJae5TioQJBAM78TmuCBbMWiJBH9vULrE2I40dvetogoOMW/9oc8xbVj9Pc/kh54sisMIQMy+nHpKKIkfprqFzhcIj2uQD/KY0" +
            "CQQCm/ceMck58jf2Tm6tUzfjf7FF8QNlkaRRYJfjst3WDXXGIXUDTyRveOADMbCaZymLP/BJzX0OrEW/G/0Pai+n7AkA3ZLiL9wEVe4t" +
            "SqZ/C1rvnCCJjJMeJBsBn5ejU83hu/Pp/5Z27wbran5JgVJhh2UcLJGeE0Dj/mmmmjfjW9nKlAkEAo3WxGipd55A50n5DpJyF6/LwB" +
            "HeaFK7DKlHpKxWd4vvaAUh/B5BJRil9ppyK4Gl6dephyStMGqzTxG/kZI4mdwJABOUmmMK8k//GKzxVA0j/ClQD5vsz8ODA7Tjp" +
            "Lh6hBcr1NhIRsVlev4kpv92Ug4IBXzaPgshnMPl5iyHLMzGT4w==";



    /**
     * 生成密钥对(公钥和私钥)
     *
     * @return
     * @throws Exception
     */
    public static Map<String, Object> genKeyPair() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(INITIALIZE_LENGTH);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<String, Object>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    /** */
    /**
     * 用私钥对信息生成数字签名
     *
     * @param data       已加密数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
//    public static String sign(byte[] data, String privateKey) throws Exception {
//        byte[] keyBytes = Base64.decodeBase64(privateKey);
//        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
//        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
//        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
//        signature.initSign(privateK);
//        signature.update(data);
//        return Base64.encodeBase64String(signature.sign());
//    }
    /**
     * 校验数字签名
     *
     * @param data      已加密数据
     * @param publicKey 公钥(BASE64编码)
     * @param sign      数字签名
     * @return
     * @throws Exception
     */
//    public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
//        byte[] keyBytes = Base64.decodeBase64(publicKey);
//        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
//        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//        PublicKey publicK = keyFactory.generatePublic(keySpec);
//        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
//        signature.initVerify(publicK);
//        signature.update(data);
//        return signature.verify(Base64.decodeBase64(sign));
//    }

    /**
     * <p>
     * 私钥解密
     *
     * @param encryptedData 已加密数据
     * @param privateKey    私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    private static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
        byte[] keyBytes = Base64Utils.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        return getBytes(encryptedData, privateK, cipher, Cipher.DECRYPT_MODE, MAX_DECRYPT_BLOCK);
    }
    /**
     * 公钥解密
     *
     * @param encryptedData 已加密数据
     * @param publicKey     公钥(BASE64编码)
     * @return
     * @throws Exception
     */
//    public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
//        byte[] keyBytes = Base64.decodeBase64(publicKey);
//        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
//        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//        Key publicK = keyFactory.generatePublic(x509KeySpec);
//        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//        return getBytes(encryptedData, publicK, cipher, Cipher.DECRYPT_MODE, MAX_DECRYPT_BLOCK);
//    }

    /**
     * 公钥加密
     *
     * @param data      源数据
     * @param publicKey 公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    private static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
        byte[] keyBytes = Base64Utils.decode(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        return getBytes(data, publicK, cipher, Cipher.ENCRYPT_MODE, MAX_ENCRYPT_BLOCK);
    }

    /**
     * 私钥加密
     *
     * @param data       源数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
//    public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
//        byte[] keyBytes = Base64.decodeBase64(privateKey);
//        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
//        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
//        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
//        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//        return getBytes(data, privateK, cipher, Cipher.ENCRYPT_MODE, MAX_ENCRYPT_BLOCK);
//    }
    private static byte[] getBytes(byte[] data, Key privateK, Cipher cipher, int encryptMode, int maxEncryptBlock) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException {
        cipher.init(encryptMode, privateK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > maxEncryptBlock) {
                cache = cipher.doFinal(data, offSet, maxEncryptBlock);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * maxEncryptBlock;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    /**
     * 获取私钥
     *
     * @param keyMap 密钥对
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return Base64Utils.encode(key.getEncoded());
    }

    /**
     * 获取公钥
     *
     * @param keyMap 密钥对
     * @return
     * @throws Exception
     */
    public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return Base64Utils.encode(key.getEncoded());
    }

    /**
     * java端公钥加密
     */
    public static String encryptedDataOnJava(String data, String PUBLICKEY) {
        try {
            data = Base64Utils.encode(encryptByPublicKey(data.getBytes(), PUBLICKEY));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("报错了" );
        }
        return data;
    }



    public static void main(String[] args) throws Exception {
        Map<String, Object> map = RSAUtils.genKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) map.get(PUBLIC_KEY);
        RSAPrivateKey privateKey = (RSAPrivateKey) map.get(PRIVATE_KEY);
        // 得到公钥字符串
        String publicKeyString = Base64Utils.encode(publicKey.getEncoded());
        // 得到私钥字符串
        String privateKeyString = Base64Utils.encode(privateKey.getEncoded());
        System.out.println("公钥:" + publicKeyString);
        System.out.println("私钥:" + privateKeyString);
        String java = encryptedDataOnJava("123456", DataKey.public_key);
        System.out.println("公钥jiami:" + java);
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值