YanWei-Rookie 的博客

本博客主要是把自己的经验记录于此,方便自己以后查阅及参考

android RSA公钥加密 公钥解密,解决乱码问题

/**
 * <p>
 * 公钥解密
 * </p>
 *
 * @param encryptedData 已加密数据
 * @param  publicKey  公钥 (无需base64编码,靠,网上的代码为毛说要base64编码,坑啊哥哥们)
 * @return  (已解决解密乱码问题)
 * @throws Exception
 */
public static byte[] decryptByPublicKey(byte[] encryptedData,String publicKey )
        throws Exception {
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key publicK = keyFactory.generatePublic(x509KeySpec);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.DECRYPT_MODE, publicK);
    int inputLen = encryptedData.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(encryptedData, offSet, MAX_DECRYPT_BLOCK);
        } else {
            cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
        }
        out.write(cache, 0, cache.length);
        i++;
        offSet = i * MAX_DECRYPT_BLOCK;
    }
    byte[] decryptedData = out.toByteArray();
    out.close();
    return decryptedData;
}
/**
 * <p>
 * 公钥加密
 * </p>
 *
 * @param data      源数据
 * @param
 * @return
 * @throws Exception
 */
public static byte[] encryptByPublicKey(byte[] data,String publicKey)
        throws Exception {
    byte[] keyBytes = Base64.decode(publicKey, Base64.DEFAULT);
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key publicK = keyFactory.generatePublic(x509KeySpec);
    // 对数据加密
    Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, publicK);
    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 encryptedData;
}


注:本方法中base64为util包下  
 android.util.Base64;
另外:方法中公钥 为"ASDFG"这种  ,网上有好多公钥前后有---BIGIN   END—— 这种,在本文中并不适用。
本人菜鸟,不知道问什么,求告知

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a1047189887/article/details/51539789
个人分类: android
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭