1、先通过keytool生产私钥,保存在keystore中
keytool -genkey -alias serverkey -keystore server.keystore -keyalg RSA
输入keystore密码:123456
输入<serverkey>的主密码:123456
2、导出公钥
keytool -export -alias serverkey -keystore server.keystore -file server.crt
代码实例:
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import org.apache.commons.codec.binary.Base64; public class SignUtil { /** * * @param privateKeyFileName 存储私钥的keystore的路劲 * @param privateKeyStorePwd keystore的密码 * @param privateKeyPwd privateKey的密码 * @param privateKeyAlias 私钥别名 * @param data 需要签名数据 * @return */ public static String signData(String privateKeyFileName, String privateKeyStorePwd, String privateKeyPwd, String privateKeyAlias, String data) { InputStream input = null; try { // 获取指定地址的私钥文件 String storePass = privateKeyStorePwd; String keyPass = privateKeyPwd; String keyAlias = privateKeyAlias; KeyStore keyStore = KeyStore.getInstance("JKS"); input = new FileInputStream(privateKeyFileName); keyStore.load(input, storePass.toCharArray()); PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyPass.toCharArray()); Signature dsa = Signature.getInstance("SHA1withRSA"); dsa.initSign(privateKey); dsa.update(data.getBytes()); return Base64.encodeBase64String(dsa.sign()); } catch (GeneralSecurityException gse) { gse.printStackTrace(); return null; } catch (FileNotFoundException e) { return null; } catch (IOException e) { return null; } finally { try { if (input != null) input.close(); } catch (Exception e) { } } } /** * 通过公钥对签名进行验证 * @param data 明文 * @param signature 签名 * @param publicKeyFile 公钥 * @return */ public static boolean verifyData(String data, String signature, String publicKeyFile) { boolean verifies = false; InputStream in = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); in = new FileInputStream(publicKeyFile); Certificate cert = cf.generateCertificate(in); PublicKey publicKey = cert.getPublicKey(); Signature dsa = Signature.getInstance("SHA1withRSA"); dsa.initVerify(publicKey); dsa.update(data.getBytes()); verifies = dsa.verify(Base64.decodeBase64(signature)); } catch (Exception gse) { } finally { try { if (in != null) in.close(); } catch (Exception e) { } } return verifies; } public static void main(String[] args) { String data = "Hello World"; String signature = SignUtil.signData("C:/Users/Feng/server.keystore","123456", "123456", "serverkey", data); System.out.println("signature:" + signature); boolean signflag = SignUtil.verifyData(data, signature,"C:/Users/Feng/server.crt"); System.out.println("signflag:" + signflag); } }