java实现RSA加密和解密的代码

下面的内容是关于 java实现RSA加密和解密的内容。

public static void main(String[] args) throws Exception { HashMap<String, Object> map = RSAUtils.getKeys(); RSAPublicKey publicKey = (RSAPublicKey) map.get("public"); RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");

	String modulus = publicKey.getModulus().toString();
	String public_exponent = publicKey.getPublicExponent().toString();
	String private_exponent = privateKey.getPrivateExponent().toString();
	String ming = "123456789";
	RSAPublicKey pubKey = RSAUtils.getPublicKey(modulus, public_exponent);
	RSAPrivateKey priKey = RSAUtils.getPrivateKey(modulus, private_exponent);
	String mi = RSAUtils.encryptByPublicKey(ming, pubKey);
	System.err.println(mi);
	ming = RSAUtils.decryptByPrivateKey(mi, priKey);
	System.err.println(ming);
}
复制代码

RSAUtils.java

package yyy.test.rsa;

import java.math.BigInteger; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.RSAPrivateKeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.HashMap;

import javax.crypto.Cipher;

public class RSAUtils {

public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException{
	HashMap<String, Object> map = new HashMap<String, Object>();
	KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    keyPairGen.initialize(1024);
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    map.put("public", publicKey);
    map.put("private", privateKey);
    return map;
}
public static RSAPublicKey getPublicKey(String modulus, String exponent) {
	try {
		BigInteger b1 = new BigInteger(modulus);
		BigInteger b2 = new BigInteger(exponent);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
		return (RSAPublicKey) keyFactory.generatePublic(keySpec);
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}

public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
	try {
		BigInteger b1 = new BigInteger(modulus);
		BigInteger b2 = new BigInteger(exponent);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
		return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}

public static String encryptByPublicKey(String data, RSAPublicKey publicKey)
		throws Exception {
	Cipher cipher = Cipher.getInstance("RSA");
	cipher.init(Cipher.ENCRYPT_MODE, publicKey);
	int key_len = publicKey.getModulus().bitLength() / 8;
	String[] datas = splitString(data, key_len - 11);
	String mi = "";
	for (String s : datas) {
		mi += bcd2Str(cipher.doFinal(s.getBytes()));
	}
	return mi;
}

public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey)
		throws Exception {
	Cipher cipher = Cipher.getInstance("RSA");
	cipher.init(Cipher.DECRYPT_MODE, privateKey);
	int key_len = privateKey.getModulus().bitLength() / 8;
	byte[] bytes = data.getBytes();
	byte[] bcd = ASCII_To_BCD(bytes, bytes.length);
	System.err.println(bcd.length);
	String ming = "";
	byte[][] arrays = splitArray(bcd, key_len);
	for(byte[] arr : arrays){
		ming += new String(cipher.doFinal(arr));
	}
	return ming;
}
public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {
	byte[] bcd = new byte[asc_len / 2];
	int j = 0;
	for (int i = 0; i < (asc_len + 1) / 2; i++) {
		bcd[i] = asc_to_bcd(ascii[j++]);
		bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));
	}
	return bcd;
}
public static byte asc_to_bcd(byte asc) {
	byte bcd;

	if ((asc >= '0') && (asc <= '9'))
		bcd = (byte) (asc - '0');
	else if ((asc >= 'A') && (asc <= 'F'))
		bcd = (byte) (asc - 'A' + 10);
	else if ((asc >= 'a') && (asc <= 'f'))
		bcd = (byte) (asc - 'a' + 10);
	else
		bcd = (byte) (asc - 48);
	return bcd;
}
public static String bcd2Str(byte[] bytes) {

	for (int i = 0; i < bytes.length; i++) {
		val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);

		val = (char) (bytes[i] & 0x0f);
	}
	return new String(temp);
}
public static String[] splitString(String string, int len) {
	int x = string.length() / len;
	int y = string.length() % len;
	int z = 0;
	if (y != 0) {
		z = 1;
	}
	String[] strings = new String[x + z];
	String str = "";
	for (int i=0; i<x+z; i++) {
		if (i==x+z-1 && y!=0) {
		}else{
		}
		strings[i] = str;
	}
	return strings;
}
public static byte[][] splitArray(byte[] data,int len){
	int x = data.length / len;
	int y = data.length % len;
	int z = 0;
	if(y!=0){
		z = 1;
	}
	byte[][] arrays = new byte[x+z][];
	byte[] arr;
	for(int i=0; i<x+z; i++){
		arr = new byte[len];
		if(i==x+z-1 && y!=0){
		}else{
		}
		arrays[i] = arr;
	}
	return arrays;
}
复制代码

}

转载于:https://juejin.im/post/5c164aee6fb9a049e70201a2

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值