java加密解密和證書的demo

<!-- lang: java -->
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
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 UtilDemo{
public static void main(String[] args) throws Exception {
	String keystorePath = "C:/Users/CeoiHong/x.keystore";
	String keystorePass = "123456";
	String certPath = "C:/Users/CeoiHong/x003.cer";
	String certPass = "abc002";
	String alias = "x002";
	
	
	KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
	KeyPair keyPair = keyPairGenerator.genKeyPair();
	
	
	System.out.println("==========|加密|==========");
	String source = "徐航 www.xuhang.us";
	String source2 = "wayne_xuhang@163.com";
	
	System.out.println("原始數據爲:" + source);
	KeyStore keyStore = loadKeyStore(keystorePath, keystorePass);
	//得到私鑰
	PrivateKey privateKey = getPrivateKey(keyStore, alias, certPass);
	//PrivateKey privateKey = keyPair.getPrivate();
	//使用私鑰加密
	byte[] encrypted = asymmetricEncrypt("RSA/ECB/PKCS1Padding", source.getBytes("UTF-8"), privateKey);
	//加密後的數據
	System.out.println("加密算法(私鑰):" + privateKey.getAlgorithm());
	System.out.println("私鑰:" + privateKey.getEncoded());
	System.out.println("加密後的數據(十六進制):" + byte2Hex(encrypted));
	
	System.out.println("==========|解密|==========");
	//得到公鑰
	PublicKey publicKey = getPublicKey(keyStore.getCertificate(alias));
	//PublicKey publicKey = keyPair.getPublic();
	//使用公鑰解密
	byte[] decrypted = asymmetricDecrypt("RSA/ECB/PKCS1Padding", encrypted, publicKey);
	//解密後的數據
	System.out.println("解密算法(公鑰):" + publicKey.getAlgorithm());
	System.out.println("公鑰:" + publicKey.getEncoded());
	System.out.println("解密後數據(字節):" + byte2Hex(decrypted));
	System.out.println("解密後的數據(明文):" + new String(decrypted, "UTF-8"));
	
	
	System.out.println("==========|簽名|==========");
	//若是私鑰使用的rsa算法,這裏簽名也只能使用rsa算法
	//得到簽名對象Signature和使用的私鑰算法必須一致,DSA不能配合md5使用
	
	String alg = ((X509Certificate)getCertFromKStore(alias, keyStore)).getSigAlgName();
	Signature signature = Signature.getInstance("SHA1WithDSA");
	signature.initSign(keyPair.getPrivate());
	signature.update(source.getBytes("UTF-8"));
	signature.update(source2.getBytes("UTF-8"),0,source2.getBytes("UTF-8").length);
	byte[] sign = signature.sign();
	System.out.println("簽名plain:" + source);
	System.out.println("簽名後數據:" + byte2Hex(sign));
	System.out.println("簽名算法/私鑰算法:" + signature.getAlgorithm() + "/" + keyPair.getPrivate().getAlgorithm());
	
	System.out.println("==========|驗籤|==========");
	Signature vSignature = Signature.getInstance("SHA1WithDSA");
	vSignature.initVerify(keyPair.getPublic());
	vSignature.update(source.getBytes("UTF-8"));
	vSignature.update(source2.getBytes("UTF-8"));
	boolean b = vSignature.verify(hex2Byte(byte2Hex(sign)));
	System.out.println("驗籤算法/公鑰算法:" + vSignature.getAlgorithm() + "/" + keyPair.getPublic().getAlgorithm());
	System.out.println("驗簽結果:" + b);

	System.out.println("==========|手動簽名|==========");
	System.out.println("簽名plain:" + source);
	byte[] digestText = digest(source);
	System.out.println("信息摘要:" + byte2Hex(digestText));
	byte[] sign1 = asymmetricEncrypt("RSA", digestText, privateKey);
	System.out.println("數字簽名:" + byte2Hex(sign1));
	
	
	System.out.println("==========|手動驗籤|==========");
	byte[] digest1 = asymmetricDecrypt("RSA", sign1, publicKey);
	System.out.println("解密簽名獲得的摘要:" + byte2Hex(digest1));
	System.out.println("手動驗簽結果" + byte2Hex(digest1).equals(byte2Hex(digestText)));
	
	
	
	
}

//加載密鑰庫keystore
public static KeyStore loadKeyStore(String keystorePath, String keystorePass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{
	//提供密鑰庫類型
	KeyStore keyStore = KeyStore.getInstance("JKS");
	//讀取keystore文件的輸入流
	InputStream in = new FileInputStream(keystorePath);
	keyStore.load(in, keystorePass.toCharArray());
	
	return keyStore;
	
}

//直接從文件加載證書certificate
public static Certificate loadCertificate(String certPath, String certPass) throws CertificateException, FileNotFoundException{
	//證書格式爲X509
	CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
	//讀取證書文件的輸入流
	InputStream in = new FileInputStream(certPath);
	Certificate certificate = certificateFactory.generateCertificate(in);
	return certificate;
}

//從密鑰庫根據別名alias得到證書certificate
public static Certificate getCertFromKStore(String alias, KeyStore keyStore) throws KeyStoreException{
	return keyStore.getCertificate(alias);
}

//對稱加密
public static byte[] symmetricEncrypt(String transformation, byte[] plainText, Key key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
	Cipher cipher = Cipher.getInstance(transformation);
	
	cipher.init(Cipher.ENCRYPT_MODE, key);
	
	cipher.update(plainText);
	
	return cipher.doFinal();
}

//對稱解密
public static byte[] symmetricDecrypt(String transformation, byte[] cipherText, Key key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
	Cipher cipher = Cipher.getInstance(transformation);
	
	cipher.init(Cipher.DECRYPT_MODE, key);
	
	cipher.update(cipherText);
	
	return cipher.doFinal();
}

//非對稱加密
public static byte[] asymmetricEncrypt(String transformation, byte[] plainText, PrivateKey key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
	Cipher cipher = Cipher.getInstance(transformation);
	
	cipher.init(Cipher.ENCRYPT_MODE, key);
	
	cipher.update(plainText);
	
	return cipher.doFinal();
}

//非對稱解密
public static byte[] asymmetricDecrypt(String transformation, byte[] cipherText, PublicKey key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
	Cipher cipher = Cipher.getInstance(transformation);
	
	cipher.init(Cipher.DECRYPT_MODE, key);
	
	cipher.update(cipherText);
	
	return cipher.doFinal();
}



//獲取公鑰PublicKey
public static PublicKey getPublicKey(Certificate certificate){
	return certificate.getPublicKey();
}

//獲取私鑰PrivateKey
public static PrivateKey getPrivateKey(KeyStore keyStore, String alias, String certpass) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException{
	return (PrivateKey)keyStore.getKey(alias, certpass.toCharArray());
}

//對稱
//TODO

//字節數組轉十六進制
public static String byte2Hex(byte[] b){
	StringBuilder sb = new StringBuilder();
	for(int i=0;i<b.length;i++){
		String hex = Integer.toHexString(0x00ff & b[i]);
		if(hex.length()<2){
			sb.append('0');
		}
		sb.append(hex);
	}
	return sb.toString();
}

//十六進制轉字節數組
public static byte[] hex2Byte(String hex){
	byte[] bytes = new byte[hex.length()/2];
	for(int i=0;i*2<hex.length();i++){
		bytes[i] = (byte) Integer.parseInt(hex.substring(2*i, 2*i+2), 16);
	}
	return bytes;
}

public static void printByte(byte[] bytes){
	for(int i=0;i<bytes.length;i++){
		if(i>0){
			System.out.print(",");
		}
		System.out.print(bytes[i]);
	}
	System.out.println();
}

//信息摘要
public static byte[] digest(String source) throws NoSuchAlgorithmException{
	MessageDigest md = MessageDigest.getInstance("SHA1");
	
	md.update(source.getBytes());
	
	return md.digest();
}
}

keytool的使用

列出密鑰庫密鑰 keytool -list -keystore x.keystore -v(詳細)java

相關文章
相關標籤/搜索