RSA秘钥生成,数据签名,签名验证

RSA秘钥生成,数据签名,签名验证

秘钥生成并保存到本地

public static Map<String, String> createKeys(int keySize) {
	// 为RSA算法创建一个KeyPairGenerator对象
	KeyPairGenerator kpg;
	try {
		kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
	}
	catch (NoSuchAlgorithmException e) {
		throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
	}

	// 初始化KeyPairGenerator对象,密钥长度
	kpg.initialize(keySize);
	// 生成密匙对
	KeyPair keyPair = kpg.generateKeyPair();
	// 得到公钥
	Key publicKey = keyPair.getPublic();
	String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
	// 得到私钥
	Key privateKey = keyPair.getPrivate();
	String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
	Map <String, String> keyPairMap = new HashMap <>();
	// 打印到控制台
	System.out.println("publicKey===>\n"+NewRsaUtil.bytesToStringNoSpace(publicKey.getEncoded()));
	System.out.println("private===>\n"+NewRsaUtil.bytesToStringNoSpace(privateKey.getEncoded()));

	keyPairMap.put("publicKey", publicKeyStr);
	keyPairMap.put("privateKey", privateKeyStr);

	return keyPairMap;
}
// 保存签名文件到本地
public static void genneratePemFile(String content, String name, boolean isPublic) {
	byte bytes[] = fromString(content);
	String result = Base64.encodeBase64String(bytes);
	System.out.println(result);
	// 生成文件
	try {
		FileOutputStream fos = new FileOutputStream(new File(name));
		if (isPublic) {
			fos.write("-----BEGIN PUBLIC KEY-----".getBytes());
		} else {
			fos.write("-----BEGIN PRIVATE KEY-----".getBytes());
		}
		fos.write(result.getBytes());
		if (isPublic) {
			fos.write("-----END PUBLIC KEY-----".getBytes());
		} else {
			fos.write("-----END PRIVATE KEY-----".getBytes());
		}
		fos.flush();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
// 调用
Map<String, String> keyPairs = createKeys(1024);
String publicKey = keyPairs.get("publicKey");
String privateKey = keyPairs.get("privateKey");
genneratePemFile(publicKey,"public_key.pem",true);
genneratePemFile(privateKey,"private_key.pem",false);

数据签名并验证

public static byte[] fromString(String pData) {
	if (pData == null) {
		throw new IllegalArgumentException("Argument can\'t be null");
	} else {
		String text = pData.replace(" ", "");
		if (text.length() % 2 != 0) {
			throw new IllegalArgumentException("Hex binary needs to be even-length :" + pData);
		} else {
			byte[] commandByte = new byte[Math.round((float) text.length() / 2.0F)];
			int j = 0;

			for (int i = 0; i < text.length(); i += 2) {
				Integer val = Integer.valueOf(Integer.parseInt(text.substring(i, i + 2), 16));
				commandByte[j++] = val.byteValue();
			}

			return commandByte;
		}
	}
}

public static String bytesToString(byte[] pBytes) {
	return formatByte(pBytes, "%02x ", false);
}

public static String bytesToString(byte[] pBytes, boolean pTruncate) {
	return formatByte(pBytes, "%02x ", pTruncate);
}

public static String bytesToStringNoSpace(byte pByte) {
	return formatByte(new byte[]{pByte}, "%02x", false);
}

public static String bytesToStringNoSpace(byte[] pBytes) {
	return formatByte(pBytes, "%02x", false);
}

public static String bytesToStringNoSpace(byte[] pBytes, boolean pTruncate) {
	return formatByte(pBytes, "%02x", pTruncate);
}

private static String formatByte(byte[] pByte, String pFormat, boolean pTruncate) {
	StringBuilder sb = new StringBuilder();
	if (pByte != null) {
		boolean t = false;
		for (byte b : pByte) {
			if (b != 0 || !pTruncate || t) {
				t = true;
				sb.append(String.format(pFormat, b & 255));
			}
		}
	}
	return sb.toString().toUpperCase(Locale.getDefault()).trim();
}

数据签名及验证

public static final String SIGN_ALGORITHMS = "SHA256withRSA";
public static final String ALGORITHMS = "RSA";
// 签名
public static String sign(byte [] content, String privateKey) {
	try {
		PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
		KeyFactory keyf = KeyFactory.getInstance(ALGORITHMS);
		PrivateKey priKey = keyf.generatePrivate(priPKCS8);
		Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
		signature.initSign(priKey);
		signature.update(content);
		byte[] signed = signature.sign();
		return bytesToStringNoSpace(signed);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
// 验证
public static boolean verify(String sign,byte [] content,String publicKey){
	try {
		byte [] signBytes = fromString(sign);
		KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHMS);
		byte[] encodedKey = Base64.decodeBase64(publicKey);
		PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
		Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
		signature.initVerify(pubKey);
		signature.update(content);
		return signature.verify(signBytes);
	}catch (Exception e){
		e.printStackTrace();
	}
	return false;
}
// 方法调用
// 数据签名
byte [] content1 = NewRsaUtil.fromString("hello world");
String result = NewRsaUtil.sign(content1,privateKey);
System.out.println("签名:\n"+result);
// 验证签名
boolean verifyResult = NewRsaUtil.verify(result,content1,publicKey);
System.out.println("验证签名:"+verifyResult);


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值