Android和JAVA后台实现RSA加解密

原文链接:https://blog.csdn.net/qq_40525756/article/details/109649435

##安卓端代码

import android.util.Base64;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;

/**

  • author: WeiFeiChen
  • date: 2020/11/6.
  • describe: RSA加解密

/
public class RSAUtils {
/
*
* RSA最大加密明文大小
/
private static final int MAX_ENCRYPT_BLOCK = 117;
/
*
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;

public static final String KEY_ALGORITHM = "RSA";
private static KeyFactory keyFactory = null;

static {
    try {
        keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

public static Key getPrivateKeyFromBase64KeyEncodeStr(String keyStr) {
    byte[] keyBytes = Base64.decode(keyStr, Base64.NO_WRAP);
    // 取得私钥
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
    Key privateKey = null;
    try {
        privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }
    return privateKey;
}

/**
 * 获取base64加密后的字符串的原始公钥
 *
 * @param keyStr
 * @return
 */
public static Key getPublicKeyFromBase64KeyEncodeStr(String keyStr) {
    byte[] keyBytes = Base64.decode(keyStr, Base64.NO_WRAP);
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    Key publicKey = null;
    try {
        publicKey = keyFactory.generatePublic(x509KeySpec);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return publicKey;
}

/**
 * 公钥加密
 *
 * @param data 待加密数据
 * @param key  密钥
 * @return byte[] 加密数据
 */
public static String encryptPublicKey(byte[] data, String key) throws Exception {
    //解密密钥
    byte[] keyBytes = Base64.decode(key, Base64.NO_WRAP);
    //实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    //初始化公钥
    //密钥材料转换
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    //产生公钥
    PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);

    //数据加密
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");//Android端使用
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    byte[] bytes = cipher.doFinal(data);
    return new String(Base64.encode(bytes, Base64.NO_WRAP));
}

/**
 * 私钥解密
 *
 * @param data       待解密数据
 * @param privateKey 密钥
 * @return byte[] 解密数据
 */
public static String decryptPrivateKey(String data, String privateKey) throws Exception {


    Key decodePrivateKey = getPrivateKeyFromBase64KeyEncodeStr(privateKey);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");//Android端使用
    cipher.init(Cipher.DECRYPT_MODE, decodePrivateKey);

    byte[] encryptedData = Base64.decode(data, Base64.NO_WRAP);
    byte[] decodedData = cipher.doFinal(encryptedData);
    String decodedDataStr = new String(decodedData);
    return decodedDataStr;
}

//-----------------------------------------------------------------------------------------------------------------------------------------------------------------

/**
 * 使用公钥进行分段加密
 *
 * @param dataStr 要加密的数据
 * @return 公钥base64字符串
 * @throws Exception
 */
public static String encryptByPublicKey(String dataStr, String publicKey)
        throws Exception {
    byte[] data = dataStr.getBytes();
    // 对公钥解密
    Key decodePublicKey = getPublicKeyFromBase64KeyEncodeStr(publicKey);
    // 对数据加密
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");//Android端使用
    cipher.init(Cipher.ENCRYPT_MODE, decodePublicKey);
    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();
    String encodedDataStr = new String(Base64.encode(encryptedData, Base64.NO_WRAP));

    return encodedDataStr;
}

/**
 * 使用私钥进行分段解密
 *
 * @param dataStr 使用base64处理过的密文
 * @return 解密后的数据
 * @throws Exception
 */
public static String decryptByPrivateKey(String dataStr, String privateKey)
        throws Exception {

    byte[] encryptedData = Base64.decode(dataStr, Base64.NO_WRAP);

    Key decodePrivateKey = getPrivateKeyFromBase64KeyEncodeStr(privateKey);

    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");//Android端使用
    cipher.init(Cipher.DECRYPT_MODE, decodePrivateKey);
    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();
    String decodedDataStr = new String(decryptedData, "utf-8");
    return decodedDataStr;
}

}

##Java后台代码

package com.gbss.common.utils;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**

  • RSA加解密

  • @author 吴帅

  • created at 2017/6/8
    */
    public class RSAUtils {

    /** //*

    • RSA最大加密明文大小
      */
      private static final int MAX_ENCRYPT_BLOCK = 117;

    /** //*

    • RSA最大解密密文大小
      */
      private static final int MAX_DECRYPT_BLOCK = 128;

    public static final String KEY_ALGORITHM = “RSA”;//RSA/ECB/PKCS1Padding

    private static KeyFactory keyFactory = null;

    static {
    try {
    keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
    }
    }

    /**

    • 获取base64加密后的字符串的原始私钥
    • @param keyStr
    • @return
      */
      public static Key getPrivateKeyFromBase64KeyEncodeStr(String keyStr) {
      byte[] keyBytes = Base64.getDecoder().decode(keyStr);
      // 取得私钥
      PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
      Key privateKey=null;
      try {
      privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
      } catch (InvalidKeySpecException e) {
      e.printStackTrace();
      }
      return privateKey;
      }

    /**

    • 获取base64加密后的字符串的原始公钥
    • @param keyStr
    • @return
      */
      public static Key getPublicKeyFromBase64KeyEncodeStr(String keyStr) {
      byte[] keyBytes = Base64.getDecoder().decode(keyStr);
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
      Key publicKey = null;
      try {
      publicKey = keyFactory.generatePublic(x509KeySpec);
      } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      }
      return publicKey;
      }

    /**

    • 公钥加密方法
    • @param dataStr 要加密的数据
    • @param dataStr 公钥base64字符串
    • @return 加密后的base64字符串
    • @throws Exception
      */
      public static String encryptPublicKey(String dataStr, String publicKey) throws Exception{
      //要加密的数据
      System.out.println(“要加密的数据:”+dataStr);
      byte[] data = dataStr.getBytes();
      // 对公钥解密
      Key decodePublicKey = getPublicKeyFromBase64KeyEncodeStr(publicKey);
      // 对数据加密
      Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
      cipher.init(Cipher.ENCRYPT_MODE, decodePublicKey);
      byte[] encodedData = cipher.doFinal(data);
      String encodedDataStr = new String(Base64.getEncoder().encode(encodedData));
      System.out.println(“公钥加密后的数据:”+encodedDataStr);
      return encodedDataStr;
      }

    /**

    • 私钥解密
      */
      public static String decrypt(String dataStr, String privateKey) throws Exception{
      //要加密的数据
      System.out.println(“要解密的数据:”+dataStr);
      //对私钥解密
      Key decodePrivateKey = getPrivateKeyFromBase64KeyEncodeStr(privateKey);
      //Log.i(“机密”,""+decodePrivateKey);
      Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
      cipher.init(Cipher.DECRYPT_MODE, decodePrivateKey);
      byte[] encodedData = Base64.getDecoder().decode(dataStr);
      byte[] decodedData = cipher.doFinal(encodedData);
      String decodedDataStr = new String(decodedData,“utf-8”);
      System.out.println(“私钥解密后的数据:”+decodedDataStr);
      return decodedDataStr;
      }

    /**

    • 使用公钥进行分段加密

    • @param dataStr 要加密的数据

    • @return 公钥base64字符串

    • @throws Exception
      */
      public static String encryptByPublicKey(String dataStr, String publicKey)
      throws Exception {
      //要加密的数据
      System.out.println(“要加密的数据:”+dataStr);
      byte[] data = dataStr.getBytes();
      // 对公钥解密
      Key decodePublicKey = getPublicKeyFromBase64KeyEncodeStr(publicKey);

      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
      // 对数据加密
      String s = keyFactory.getAlgorithm();
      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
      cipher.init(Cipher.ENCRYPT_MODE, decodePublicKey);
      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();
      String encodedDataStr = new String(Base64.getEncoder().encode(encryptedData));
      System.out.println(“公钥加密后的数据:”+encodedDataStr);
      return encodedDataStr;
      }

    /**

    • 使用私钥进行分段解密

    • @param dataStr 使用base64处理过的密文

    • @return 解密后的数据

    • @throws Exception
      */
      public static String decryptByPrivateKey(String dataStr, String privateKey)
      throws Exception {
      byte[] encryptedData = Base64.getDecoder().decode(dataStr);

      KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
      Key decodePrivateKey = getPrivateKeyFromBase64KeyEncodeStr(privateKey);

      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
      //Cipher cipher = Cipher.getInstance(“RSA/ECB/PKCS1Padding”);
      cipher.init(Cipher.DECRYPT_MODE, decodePrivateKey);
      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();
      String decodedDataStr = new String(decryptedData,“utf-8”);
      System.out.println(“私钥解密后的数据:”+decodedDataStr);
      return decodedDataStr;
      }

    /**

    • 生成公私钥
      */
      public static void genKeyPair() throws NoSuchAlgorithmException {
      Security.addProvider(new BouncyCastleProvider());
      KeyPairGenerator generator = KeyPairGenerator.getInstance(“RSA”);
      generator.initialize(1024, new SecureRandom());
      KeyPair pair = generator.generateKeyPair();
      PublicKey pubKey = pair.getPublic();
      PrivateKey privKey = pair.getPrivate();
      byte[] pk = pubKey.getEncoded();
      byte[] privk = privKey.getEncoded();
      String strpk = new String(Base64.getEncoder().encode(pk));
      String strprivk = new String(Base64.getEncoder().encode(privk));

      System.out.println(“公钥Base64编码:” + strpk);
      System.out.println(“私钥Base64编码:” + strprivk);
      }

    public static void main(String[] args) throws Exception {

// String pubKey = “公钥”;
// String prvKey = “私钥”;
// Map<String, String> data = new HashMap<String, String>();
// data.put(“account”,“111”);
// data.put(“password”,“JJHH”);
// System.out.println("–>加密前:" + data);
//
// String enData = RSAUtils.encryptByPublicKey(JacksonUtils.obj2json(data), pubKey);
// System.out.println("–>加密后:" + enData);
//
// String deData = RSAUtils.decryptByPrivateKey(enData, prvKey);
// System.out.println("–>解密后:" + deData);
// genKeyPair();
}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值