java获取证书私钥,并加密签名

/**
* 签名算法
* @author zhoujia
* @date 2017-9-8
* @todo TODO
* @param data  需要签名的内容
* @param keyStoreFileName  含私钥的文件
* @param keyStorePassword  含私钥文件的密码
* @param keyStoreAlias  别名
* @return
*/
public static String signData(String data,String keyStoreFileName,String keyStorePassword,String keyStoreAlias)
{
KeyStore keyStore;
byte[]  signRstByte=null;
String signValue="";
try {
keyStore = KeyStore.getInstance("PKCS12");//获取pfx证书实例  当证书为jks 格式时参数应当为JKS
FileInputStream in=new FileInputStream(keyStoreFileName);//获取证书文件流
char[]pwdChar=keyStorePassword.toCharArray();//证书密码
keyStore.load(in, pwdChar);//加载证书到keystore中

 Enumeration enumas = keyStore.aliases();  

    //此处不知道别名。(如有固定别名则直接用)

           String keyAlias = null;   
           if (enumas.hasMoreElements())// we are readin just one certificate.  
           {  
               keyAlias = (String)enumas.nextElement();   
               DevLogger.tradeLog("alias=[" + keyAlias + "]");  

           } 


PrivateKey privateKey=(PrivateKey)keyStore.getKey(keyAlias, pwdChar);//从证书中获取私钥
Signature sign=Signature.getInstance("SHA1WithRSA");//SHA1WithRSA签名算法
sign.initSign(privateKey);//设置私钥
sign.update(data.getBytes());//设置明文
signRstByte=sign.sign();//加密
BASE64Encoder encoder=new BASE64Encoder();
signValue=encoder.encodeBuffer(signRstByte);//BASE64编码
//System.out.println("签名并编码后的内容signValue=="+signValue);
} catch (KeyStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CertificateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return signValue;


}

你可能感兴趣的:(JAVA,算法,加密,java)