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

  • Post author:
  • Post category:其他




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);




版权声明:本文为shuzhuchengfu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。