android RSA算法之路

RSA加密:非对称密钥,公开密钥算法。

在实现过程中,android端和服务器端(用Java实现的)总是不能互相签名和验签,取到服务器端生成的签名进行解签的时候,总是得到一串乱码,后来定位到cipher.doFinal(srcBytes)这一行代码出的错。返回的byte数组都是-1。后来发现是填充方式的问题。改成Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding")就行了,而不是Cipher cipher = Cipher.getInstance("RSA")。

另外RSA加密长度有限制,待加密的字节数不能超过密钥的长度值除以 8 再减去 11,而加密后得到密文的字节数,正好是密钥的长度值除以 8。一般情况下RSA密钥长度必须是64的倍数,在512~65536之间。默认是1024。加密密文最大长度就是117个字节。一旦超过这个长度就会报错,javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes。这个时候可以采取分段加密的方式。

    /**
     * RSA密钥长度必须是64的倍数,在512~65536之间。默认是1024
     */
    public static final int KEY_SIZE = 1024;
    
    //将Base64编码后的公钥转换成PublicKey对象
    public static PublicKey getPublicKey(String pubStr) throws Exception {
        byte[] keyBytes = Base64Utils.decode(pubStr);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * 获取私钥对象
     *
     * @param privateKeyBase64
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static PrivateKey getPrivateKey(String privateKeyBase64) throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec privatekcs8KeySpec = new PKCS8EncodedKeySpec(Base64Utils.decode(privateKeyBase64));
        PrivateKey privateKey = keyFactory.generatePrivate(privatekcs8KeySpec);
        return privateKey;
    }

 

   /**
     * 使用公钥加密
     *
     * @param content      待加密内容
     * @param publicKeyStr 公钥
     * @return 经过 base64 编码后的字符串
     */
    public static String encrypt(String content, String publicKeyStr) throws Exception {
        PublicKey publicKey = getPublicKey(publicKeyStr);
        return encipher(content, publicKey, KEY_SIZE / 8 - 11);
    }

    /**
     * 签名
     *
     * @param content       待加密内容
     * @param privateKeyStr 私钥
     * @return 经过 base64 编码后的字符串
     */
    public static String sign(String content, String privateKeyStr) throws InvalidKeySpecException, NoSuchAlgorithmException {
        PrivateKey privateKey = getPrivateKey(privateKeyStr);
        return encipher(content, privateKey, KEY_SIZE / 8 - 11);
    }

    /**
     * 分段加密
     *
     * @param cipherText  密文
     * @param key         加密秘钥
     * @param segmentSize 分段大小,<=0 不分段
     * @return
     */
    public static String encipher(String cipherText, Key key, int segmentSize) {
        try {
            byte[] srcBytes = cipherText.getBytes();

            // Cipher负责完成加密或解密工作,基于RSA
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            // 根据公钥,对Cipher对象进行初始化
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] resultBytes = null;

            if (segmentSize > 0)
                resultBytes = cipherDoFinal(cipher, srcBytes, segmentSize); //分段加密
            else
                resultBytes = cipher.doFinal(srcBytes);
            String base64Str = Base64Utils.encode(resultBytes);
            return base64Str;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 分段大小
     *
     * @param cipher
     * @param srcBytes
     * @param segmentSize
     * @return
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws IOException
     */
    public static byte[] cipherDoFinal(Cipher cipher, byte[] srcBytes, int segmentSize) throws IllegalBlockSizeException, BadPaddingException, IOException {
        if (segmentSize <= 0)
            throw new RuntimeException("分段大小必须大于0");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int inputLen = srcBytes.length;
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > segmentSize) {
                cache = cipher.doFinal(srcBytes, offSet, segmentSize);
            } else {
                cache = cipher.doFinal(srcBytes, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * segmentSize;
        }
        byte[] data = out.toByteArray();
        out.close();
        return data;
    }

    /**
     * 验签
     *
     * @param content      待解密内容,
     * @param publicKeyStr 公钥
     * @return
     * @segmentSize 分段大小
     */
    public static String verify(String content, String publicKeyStr) throws Exception {
        PublicKey publicKey = getPublicKey(publicKeyStr);
        return decipher(content, publicKey, KEY_SIZE / 8);
    }

    /**
     * 使用私钥解密
     *
     * @param content       待解密内容
     * @param privateKeyStr 私钥
     * @return
     * @segmentSize 分段大小
     */
    public static String decrypt(String content, String privateKeyStr) throws InvalidKeySpecException, NoSuchAlgorithmException {
        PrivateKey privateKey = getPrivateKey(privateKeyStr);
        return decipher(content, privateKey, KEY_SIZE / 8);
    }

    /**
     * 分段解密
     *
     * @param contentBase64 密文
     * @param key           解密秘钥
     * @param segmentSize   分段大小(小于等于0不分段)
     * @return
     */
    public static String decipher(String contentBase64, Key key, int segmentSize) {
        try {
            // 用私钥解密
            byte[] srcBytes = Base64Utils.decode(contentBase64);
            // Cipher负责完成加密或解密工作,基于RSA
            Cipher deCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            // 根据公钥,对Cipher对象进行初始化
            deCipher.init(Cipher.DECRYPT_MODE, key);
            byte[] decBytes = null;//deCipher.doFinal(srcBytes);
            if (segmentSize > 0)
                decBytes = cipherDoFinal(deCipher, srcBytes, segmentSize); //分段加密
            else
                decBytes = deCipher.doFinal(srcBytes);

            String decrytStr = new String(decBytes);
            return decrytStr;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

 详细代码见下载

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值