Java examples for Security:Key
sign password by key
//package com.java2s; import java.io.FileInputStream; import java.security.KeyStore; import java.security.PrivateKey; import java.security.Signature; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; public class Main { public static final String KEY_STORE = "JKS"; public static final String X509 = "X.509"; public static String sign(byte[] sign, String keyStorePath, String alias, String password) throws Exception { // ?// w ww. java 2 s . co m X509Certificate x509Certificate = (X509Certificate) getCertificate( keyStorePath, alias, password); // ? KeyStore ks = getKeyStore(keyStorePath, password); // ? PrivateKey privateKey = (PrivateKey) ks.getKey(alias, password.toCharArray()); // Signature signature = Signature.getInstance(x509Certificate .getSigAlgName()); signature.initSign(privateKey); signature.update(sign); return encryptBASE64(signature.sign()); } public static Certificate getCertificate(String certificatePath) throws Exception { CertificateFactory certificateFactory = CertificateFactory .getInstance(X509); FileInputStream in = new FileInputStream(certificatePath); Certificate certificate = certificateFactory .generateCertificate(in); in.close(); return certificate; } public static Certificate getCertificate(String keyStorePath, String alias, String password) throws Exception { KeyStore ks = getKeyStore(keyStorePath, password); Certificate certificate = ks.getCertificate(alias); return certificate; } public static KeyStore getKeyStore(String keyStorePath, String password) throws Exception { FileInputStream is = new FileInputStream(keyStorePath); KeyStore ks = KeyStore.getInstance(KEY_STORE); ks.load(is, password.toCharArray()); is.close(); return ks; } private static String encryptBASE64(byte[] bytes) { return new sun.misc.BASE64Encoder().encode(bytes); } }