JAVA中RSA签名算法实现
JAVA中RSA签名算法实现
吕兵阳 发表于3个月前
JAVA中RSA签名算法实现
  • 发表于 3个月前
  • 阅读 16
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

摘要: RSA算法java实现
import java.security.InvalidKeyException;
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.Signature;
import java.security.SignatureException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

/**
 * Created by Lb on 2017/9/10.
 */
public class RSACoder {

  //非对称加密算法
  public static final String KEY_ALGORITHM = "RSA";
  //数字签名 签名/验证算法
  public static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
  //公钥
  private static final String PUBLIC_KEY = "RSAPublicKey";
  //私钥
  private static final String PRIVATE_KEY = "RSAPrivateKey";
  //RSA密钥长度默认1024位,密钥长度必须是64的倍数,范围在512-65536位之间
  private static final int KEY_SIZE = 512;

  /**
   * 私钥解密
   */
  public static byte[] decryptByPrivateKey(byte[] data, byte[] key)
      throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    //取得私钥
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    //生成私钥
    PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    //对数据解密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    return cipher.doFinal(data);
  }

  /**
   * 公钥解密
   */
  public static byte[] decryptByPublicKey(byte[] data, byte[] key)
      throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    //取得公钥
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    //生成公钥
    PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
    //对数据解密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, publicKey);
    return cipher.doFinal(data);
  }

  /**
   * 公钥加密
   */
  public static byte[] encryptByPublicKey(byte[] data, byte[] key)
      throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    //取得公钥
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    //生成公钥
    PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
    //对数据加密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    return cipher.doFinal(data);
  }


  /**
   * 私钥加密
   */
  public static byte[] encryptByPrivateKey(byte[] data, byte[] key)
      throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    //取得私钥
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    //生成私钥
    PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    //对数据加密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, privateKey);
    return cipher.doFinal(data);
  }

  /**
   * 取得私钥
   */
  public static byte[] getPrivateKey(Map<String, Object> keyMap)
      throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    Key key = (Key) keyMap.get(PRIVATE_KEY);
    return key.getEncoded();
  }

  /**
   * 取得公钥
   */
  public static byte[] getPublicKey(Map<String, Object> keyMap)
      throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    Key key = (Key) keyMap.get(PUBLIC_KEY);
    return key.getEncoded();
  }

  /**
   * 初始化密钥
   */
  public static Map<String, Object> initKey() throws NoSuchAlgorithmException {
    //实例化密钥生成器
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    //初始化密钥对生成器
    keyPairGenerator.initialize(KEY_SIZE);
    //生成密钥对
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    //公钥
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    //私钥
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    //封装密钥
    Map<String, Object> keyMap = new HashMap<>();
    keyMap.put(PUBLIC_KEY, publicKey);
    keyMap.put(PRIVATE_KEY, privateKey);
    return keyMap;
  }

  /**
   * 签名
   *
   * @param data 待签名数据
   * @param privateKey 私钥
   * @return 数字签名
   */
  public static byte[] sign(byte[] data, byte[] privateKey)
      throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
    //转换私钥材料
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey);
    //实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    //取私钥对象
    PrivateKey priKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    //实例化Signature
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    //初始化Signature
    signature.initSign(priKey);
    //更新
    signature.update(data);
    //签名
    return signature.sign();
  }

  /**
   * 公钥校验
   *
   * @param data 待校验数据
   * @param publicKey 公钥
   * @param sign 数字签名
   * @return 校验成功返回true 失败返回false
   */
  public static boolean verify(byte[] data, byte[] publicKey, byte[] sign)
      throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
    //转换公钥材料
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
    //实例化密钥工厂
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    //生成公钥
    PublicKey pubKey = keyFactory.generatePublic(keySpec);
    //实例化Signature
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    //初始化Signature
    signature.initVerify(pubKey);
    //更新
    signature.update(data);
    //验证
    return signature.verify(sign);
  }

  /**
   * 私钥签名
   *
   * @param data 待签名数据
   * @param privateKey 私钥
   * @return 十六进行签名字符串
   */
  public static String sign(byte[] data, String privateKey)
      throws DecoderException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    byte[] sign = sign(data, getKey(privateKey));
    return Hex.encodeHexString(sign);
  }


  /**
   * 公钥校验
   *
   * @param data 待校验数据
   * @param publicKey 公钥
   * @param sign 签名
   * @return 成功返回true,失败返回false
   */
  public static boolean verify(byte[] data, String publicKey, String sign)
      throws DecoderException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    return verify(data, getKey(publicKey), Hex.decodeHex(sign.toCharArray()));
  }


  /**
   * 私钥加密
   */
  public static byte[] encryptByPrivateKey(byte[] data, String key)
      throws DecoderException, NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
    return encryptByPrivateKey(data, getKey(key));
  }

  /**
   * 公钥加密
   */
  public static byte[] encryptByPublicKey(byte[] data, String key)
      throws DecoderException, NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
    return encryptByPublicKey(data, getKey(key));
  }

  /**
   * 私钥解密
   */
  public static byte[] decryptByPrivateKey(byte[] data, String key)
      throws DecoderException, NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
    return decryptByPrivateKey(data, getKey(key));
  }

  /**
   * 公钥解密
   */
  public static byte[] decryptByPublicKey(byte[] data, String key)
      throws DecoderException, NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
    return decryptByPublicKey(data, getKey(key));
  }

  /**
   * 初始化密钥
   *
   * @return 十六进制编码密钥
   */
  public static String getPrivateKeyString(Map<String, Object> keyMap)
      throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
//    return Base64.encodeBase64String(getPrivateKey(keyMap));
    return Hex.encodeHexString(getPrivateKey(keyMap));
  }

  /**
   * 初始化密钥
   *
   * @return 十六进制编码密钥
   */
  public static String getPublicKeyString(Map<String, Object> keyMap)
      throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
//    return Base64.encodeBase64String(getPublicKey(keyMap));
    return Hex.encodeHexString(getPublicKey(keyMap));
  }

  /**
   * 获取密钥
   *
   * @param key 密钥
   * @return 密钥
   */
  public static byte[] getKey(String key) throws DecoderException {
    return Hex.decodeHex(key.toCharArray());
//    return Base64.decodeBase64(key);
  }


  public static void main(String[] args)
      throws NoSuchAlgorithmException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, InvalidKeySpecException, NoSuchPaddingException, DecoderException, SignatureException {
    Map<String, Object> keyMap = RSACoder.initKey();
    //获取并打印公钥
    String publicKey = RSACoder.getPublicKeyString(keyMap);

    System.out.println("publicKey=" + publicKey);
    //获取并打印私钥
    String privateKey = RSACoder.getPrivateKeyString(keyMap);
    System.out.println("privateKey=" + privateKey);

    String inputStr = "测试加密18803696960http://www.baidu.com///xxxx";
    byte[] data = inputStr.getBytes();
    System.out.println("原文:" + inputStr);
    byte[] encodeData = RSACoder.encryptByPublicKey(data, publicKey);
    System.out.println("加密后:" + Hex.encodeHexString(encodeData));
    byte[] decodeData = RSACoder.decryptByPrivateKey(encodeData, privateKey);
    System.out.println("解密后:" + new String(decodeData));
    //私钥签名  公钥校验
    String sign = RSACoder.sign(data, privateKey);
    System.out.println("校验=" + RSACoder.verify(data, publicKey, sign));
  }
}
标签: java RSA
共有 人打赏支持
粉丝 77
博文 271
码字总数 104261
×
吕兵阳
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: