package jdbc.pro.lin;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class MyCertifacate {
private static final String STORE_PASS = "abcd1234";
private static final String ALIAS = "myCertificate";
private static final String KEYSTORE_PATH = "D:\\Program Files\\Java\\jdk1.8.0_101\\bin\\myKeystore.keystore";//这个私钥可以放在硬盘的其他地方
private static final String CERT_PATH = "D:\\Program Files\\Java\\jdk1.8.0_101\\bin\\myCer.cer";//这个数字证书也可以放到硬盘的其他地方
private static final String PLAIN_TEXT = "MANUTD is the most greatest club in the world.";
/** JDK6只支持X.509标准的证书 */
private static final String CERT_TYPE = "X.509";
public static void main(String[] args) throws IOException {
/**
* 假设现在有这样一个场景 。A机器上的数据,需要加密导出,然后将导出文件放到B机器上导入。 在这个场景中,A相当于服务器,B相当于客户端
*/
/** A */
KeyStore keyStore = getKeyStore(STORE_PASS, KEYSTORE_PATH);
PrivateKey privateKey = getPrivateKey(keyStore, ALIAS, STORE_PASS);
X509Certificate certificate = getCertificateByKeystore(keyStore, ALIAS);
/** 加密和签名 */
byte[] encodedText = encode(PLAIN_TEXT.getBytes(), privateKey);
byte[] signature = sign(certificate, privateKey, PLAIN_TEXT.getBytes());
/** 现在B收到了A的密文和签名,以及A的可信任证书 */
X509Certificate receivedCertificate = getCertificateByCertPath(
CERT_PATH, CERT_TYPE);
PublicKey publicKey = getPublicKey(receivedCertificate);
byte[] decodedText = decode(encodedText, publicKey);
System.out.println("Decoded Text : " + new String(decodedText));
System.out.println("Signature is : "
+ verify(receivedCertificate, decodedText, signature));
}
/**
* 加载密钥库,与Properties文件的加载类似,都是使用load方法
*
* @throws IOException
*/
public static KeyStore getKeyStore(String storepass, String keystorePath)
throws IOException {
InputStream inputStream = null;
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
inputStream = new FileInputStream(keystorePath);
keyStore.load(inputStream, storepass.toCharArray());
return keyStore;
} catch (KeyStoreException | NoSuchAlgorithmException
| CertificateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != inputStream) {
inputStream.close();
}
}
return null;
}
/**
* 获取私钥
*
* @param keyStore
* @param alias
* @param password
* @return
*/
public static Priv