Android RSA分段加解密,及私钥生成签名公钥验签

rsa是一种比较普遍的移动端加密方式,公钥用于加密跟验签,私钥用于解密跟生成签名,客户端只需要保存一个公钥即可,私钥用于后台。

RSA加解密

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import android.util.Base64;

public class RSAUtils {
    private static String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding"; // 加密算法
    private static int KEYBIT = 2048;// 密钥位数
    private static int RESERVEBYTES = 11;// 加密block需要预留字节数
    private static int decryptBlock = KEYBIT / 8; // 每段解密block数,256 bytes
    private static int encryptBlock = decryptBlock - RESERVEBYTES; // 每段加密block数245bytes

    /**
     * 获取公钥
     * 
     * @param key
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = Base64.decode(key, Base64.DEFAULT);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * 获取私钥
     * 
     * @param key
     *            pkcs#8
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = Base64.decode(key, Base64.DEFAULT);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    public static String getKeyString(Key key) {
        byte[] keyBytes = key.getEncoded();
        String s = Base64.encodeToString(keyBytes, Base64.DEFAULT);
        return s;
    }

    /**
     * 加密
     * 
     * @param key
     *            公钥
     * @param data
     *            加密报文 getBytes()
     * @return
     */
    public static String encode(String pubKey, byte[] data) {
        // 计算分段加密的block数 (向上取整)
        int nBlock = (data.length / encryptBlock);
        if ((data.length % encryptBlock) != 0) { // 余数非0,block数再加1
            nBlock += 1;
        }
        // 输出buffer, 大小为nBlock个decryptBlock
        ByteArrayOutputStream outbuf = new ByteArrayOutputStream(nBlock * decryptBlock);
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            PublicKey publicKey = getPublicKey(pubKey);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            for (int offset = 0; offset < data.length; offset += encryptBlock) {
                // block大小: encryptBlock 或剩余字节数
                int inputLen = (data.length - offset);
                if (inputLen > encryptBlock) {
                    inputLen = encryptBlock;
                }
                // 得到分段加密结果
                byte[] encryptedBlock = cipher.doFinal(data, offset, inputLen);
                // 追加结果到输出buffer中
                outbuf.write(encryptedBlock);
            }
            return Base64.encodeToString(outbuf.toByteArray(), Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                outbuf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 解密
     * 
     * @param priKey
     *            pkcs#8
     * @param data
     *            解密报文 "string".getBytes();
     * @return new String( byte[] )
     */
    public static byte[] decode(String priKey, byte[] data) {
        // 计算分段加密的block数 (向上取整)
        int nBlock = (data.length / encryptBlock);
        if ((data.length % encryptBlock) != 0) { // 余数非0,block数再加1
            nBlock += 1;
        }
        ByteArrayOutputStream outbuf = new ByteArrayOutputStream(nBlock * encryptBlock);
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            PrivateKey privateKey = getPrivateKey(priKey);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            for (int offset = 0; offset < data.length; offset += decryptBlock) {
                // block大小: decryptBlock 或剩余字节数
                int inputLen = (data.length - offset);
                if (inputLen > decryptBlock) {
                    inputLen = decryptBlock;
                }
                // 得到分段加密结果
                byte[] decryptedBlock = cipher.doFinal(data, offset, inputLen);
                // 追加结果到输出buffer中
                outbuf.write(decryptedBlock);
            }
            return outbuf.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                outbuf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 普通解密
     * @param key 
     * @param data 
     * @return new String()
     */
    public static byte[] decode(String key, String data) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            PrivateKey privateKey = getPrivateKey(key);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return cipher.doFinal(Base64.decode(data.getBytes(), Base64.DEFAULT));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 普通加密
     * @param key
     * @param data getBytes()
     * @return Bsae64.enCodeToString()
     */
    public static byte[] encode2(String key, byte[] data) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            PublicKey publicKey = getPublicKey(key);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}

RSA私钥生成签名公钥验签

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import android.util.Base64;

public class RSASignature {
    /**
     * 签名算法
     */
    public static final String SIGN_ALGORITHMS = "SHA1WithRSA";

    /**
     * RSA签名
     * 
     * @param content
     *            待签名数据
     * @param privateKey
     *            商户私钥
     * @param encode
     *            字符集编码
     * @return 签名值
     */
    public static String sign(String content, String privateKey, String encode) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey, Base64.DEFAULT));
            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);

            signature.initSign(priKey);
            signature.update(content.getBytes(encode));

            byte[] signed = signature.sign();

            return Base64.encodeToString(signed, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * RSA验签名检查
     * 
     * @param content
     *            待签名数据
     * @param sign
     *            签名值
     * @param publicKey
     *            分配给开发商公钥
     * @param encode
     *            字符集编码
     * @return 布尔值
     */
    public static boolean doCheck(String content, String sign, String publicKey, String encode) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = Base64.decode(publicKey, Base64.DEFAULT);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);

            signature.initVerify(pubKey);
            signature.update(content.getBytes(encode));

            boolean bverify = signature.verify(Base64.decode(sign, Base64.DEFAULT));
            return bverify;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    public static boolean doCheck(String content, String sign, String publicKey) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = Base64.decode(publicKey, Base64.DEFAULT);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
            signature.initVerify(pubKey);
            signature.update(content.getBytes("UTF-8"));
            boolean bverify = signature.verify(Base64.decode(sign, Base64.DEFAULT));
            return bverify;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RSA是一种非对称加密算法,其公钥私钥是成对生成的。以下是RSA生成公钥私钥以及加解密的步骤: 1. 生成RSA公钥私钥: 首先需要随机生成两个大素数p和q,计算n = p * q,再选取一个整数e(一般为65537),计算d = e^-1 mod ((p-1) * (q-1))。 生成公钥为(n, e),私钥为(n, d)。 2. RSA加密: 假设要将明文M加密为密文C,使用公钥(n, e)进行加密,计算C = M^e mod n。 3. RSA解密: 使用私钥(n, d)进行解密,计算M = C^d mod n。 以下是一个简单的RSA加解密的C语言实现示例: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/bio.h> #include <openssl/rsa.h> #include <openssl/pem.h> int main() { // 生成RSA公钥私钥 RSA *rsa = RSA_generate_key(2048, 65537, NULL, NULL); if (rsa == NULL) { printf("Failed to generate RSA key pair.\n"); return -1; } // 获取公钥私钥 BIO *pubBio = BIO_new(BIO_s_mem()); BIO *priBio = BIO_new(BIO_s_mem()); PEM_write_bio_RSAPublicKey(pubBio, rsa); PEM_write_bio_RSAPrivateKey(priBio, rsa, NULL, NULL, 0, NULL, NULL); // 获取公钥私钥字符串 char pubKey[1024] = {0}; char priKey[4096] = {0}; BIO_read(pubBio, pubKey, sizeof(pubKey)); BIO_read(priBio, priKey, sizeof(priKey)); // 输出公钥私钥 printf("Public Key:\n%s\n", pubKey); printf("Private Key:\n%s\n", priKey); // 加密明文 char *plaintext = "Hello World!"; int plaintextLen = strlen(plaintext) + 1; char ciphertext[4096] = {0}; int ciphertextLen = RSA_public_encrypt(plaintextLen, (unsigned char *)plaintext, (unsigned char *)ciphertext, rsa, RSA_PKCS1_PADDING); if (ciphertextLen == -1) { printf("Failed to encrypt plaintext.\n"); return -1; } // 输出密文 printf("Ciphertext:\n"); for (int i = 0; i < ciphertextLen; i++) { printf("%02x", ciphertext[i]); } printf("\n"); // 解密密文 char decrypted[4096] = {0}; int decryptedLen = RSA_private_decrypt(ciphertextLen, (unsigned char *)ciphertext, (unsigned char *)decrypted, rsa, RSA_PKCS1_PADDING); if (decryptedLen == -1) { printf("Failed to decrypt ciphertext.\n"); return -1; } // 输出解密后的明文 printf("Decrypted plaintext: %s\n", decrypted); // 释放资源 RSA_free(rsa); BIO_free_all(pubBio); BIO_free_all(priBio); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值