加解密示例代码
package cpcn.dsp.institution.simulator.test;
import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.Enumeration;
import java.util.Random;
public class TestEncrypt {
private static final String certificateFilepath = "/CPCN/DSP/DSPInstitutionSimulator/config/dsp/dsptest.cer";
private static PublicKey publicKey;
private static X509Certificate x509Certificate;
private static String encryptSN;
private static final String myKeystoreFilepath = "/CPCN/DSP/DSPInstitutionSimulator/config/dsp/test.pfx";
private static final String myKeystorePassword = "cfca1234";
private static PrivateKey privateKey;
private static X509Certificate x509Certificate2;
private static String signSN;
private static final String algorithm = "SHA1withRSA";
public static final String aes_algorithm = "AES/ECB/PKCS7Padding";
public static final String rsa_algorithm = "RSA/ECB/PKCS1Padding";
private static String message = "";
private static String signature = "";
private static String dgtlenvlp = "";
public static void main(String[] args) throws Exception {
String source = getSource2331();
initEnv();
createRequest(source);
parseResult(dgtlenvlp, message, signature);
byte[] decode = Base64.getDecoder().decode(
"eyJNZXNzYWdlIjoi6Kej5p6Q5oql5paH6ZSZ6K+vIiwiQ29kZSI6IjIwMDMifQ==");
System.out.println(new String(decode, "UTF-8"));
}
private static String getSource2331(){
JSONObject json = new JSONObject();
json.put("InstitutionID", "000020");
json.put("TxCode", "2104");
json.put("TxSN", "202005181330189983132331151");
json.put("Remark", "");
json.put("Name", "张三");
json.put("IdentificationType","0");
json.put("IdentificationNumber", "511102198310242028");
return json.toString();
}
private static void createRequest(String source) throws Exception {
String randomKeyData = randomHexString();
System.out.println("随机密钥_source: " + randomKeyData);
dgtlenvlp = encryptByRSA(randomKeyData.getBytes("UTF-8"), publicKey);
message = encodeByAES(source, randomKeyData);
signature = sign(source.getBytes("UTF-8"));
System.out.println("dgtlenvlp:" + dgtlenvlp);
System.out.println("message:" + message);
System.out.println("signature:" + signature);
}
private static void parseResult(String requestDgtlEnvlp, String requestMessage, String sign) throws Exception {
String randomKeyData2 = getDecryptKeyByteByRSA(requestDgtlEnvlp, privateKey);
String randomKeyData3 = new String(hex2bytes(randomKeyData2), "UTF-8");
System.out.println("随机密钥_return: " + randomKeyData3);
String decryptMsg = decodeByAES(randomKeyData2, requestMessage);
System.out.println("将消息解密后: " + decryptMsg);
Boolean verify = verify(decryptMsg.getBytes("UTF-8"), sign);
System.out.println("验签结果: " + verify);
}
private static void initEnv() throws Exception {
Security.addProvider(new BouncyCastleProvider());
initPublicKey(certificateFilepath);
initPfxKey(myKeystoreFilepath, myKeystorePassword);
}
private static String randomHexString() {
int len = 32;
StringBuffer result = new StringBuffer();
Random random = new Random();
for (int i = 0; i < len; i++) {
result.append(Integer.toHexString(random.nextInt(16)));
}
return result.toString().toUpperCase();
}
private static String sign(byte[] msg) throws Exception {
Signature signature = Signature.getInstance(algorithm);
signature.initSign(privateKey);
signature.update(msg);
return bytes2hex(signature.sign());
}
private static Boolean verify (byte[] msg, String sign) throws Exception {
byte[] signature = hex2bytes(sign);
Signature sig = Signature.getInstance(algorithm);
sig.initVerify(publicKey);
sig.update(msg);
return sig.verify(signature);
}
private static String encryptByRSA(byte[] plainData, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] output = cipher.doFinal(plainData);
return new String(Base64.getEncoder().encode(output));
}
public static String getDecryptKeyByteByRSA(String signData, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(rsa_algorithm);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] output = cipher.doFinal(Base64.getDecoder().decode(signData));
return bytes2hex(output);
}
private static String encodeByAES(String str, String key) throws Exception {
Cipher cipher = Cipher.getInstance(aes_algorithm, "BC");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] result = cipher.doFinal(str.getBytes("UTF-8"));
return new String(Base64.getEncoder().encode(result));
}
public static String decodeByAES(String key, String cipherText) throws Exception {
byte[] resByte = Base64.getDecoder().decode(cipherText);
Cipher cipher = Cipher.getInstance(aes_algorithm, "BC");
SecretKeySpec keySpec = new SecretKeySpec(hex2bytes(key), "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decoded = cipher.doFinal(resByte);
return new String(decoded, "UTF-8");
}
private static void initPublicKey(String file) throws Exception {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
x509Certificate = (X509Certificate) cf.generateCertificate(fis);
publicKey = x509Certificate.getPublicKey();
encryptSN = String.valueOf(x509Certificate.getSerialNumber());
System.out.println("encryptSN:"+encryptSN );
} finally {
if (null != fis) {
fis.close();
}
}
}
private static void initPfxKey(String pfxfilename, String password) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream fis = new FileInputStream(pfxfilename);
keyStore.load(fis, password.toCharArray());
fis.close();
Enumeration<String> aliases = keyStore.aliases();
String alias = (String) aliases.nextElement();
privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
x509Certificate2 = (X509Certificate)keyStore.getCertificate(alias);
signSN = String.valueOf(x509Certificate2.getSerialNumber());
System.out.println("signSN:" + signSN);
}
private static String bytes2hex(byte[] bytes) {
StringBuilder result = new StringBuilder();
String b = "";
if (null == bytes) {
return null;
}
for (int i = 0; i < bytes.length; i++) {
b = Integer.toHexString(bytes[i] & 0xFF);
if (b.length() == 1) {
result.append("0");
}
result.append(b);
}
return result.toString().toUpperCase();
}
public static byte[] hex2bytes(String hexStringParam) {
String hexString = hexStringParam;
hexString = hexString.toUpperCase();
char[] chars = hexString.toCharArray();
byte[] bytes = new byte[chars.length / 2];
int index = 0;
for (int i = 0; i < chars.length; i += 2) {
byte newByte = 0x00;
newByte |= char2byte(chars[i]);
newByte <<= 4;
newByte |= char2byte(chars[i + 1]);
bytes[index] = newByte;
index++;
}
return bytes;
}
private static byte char2byte(char ch) {
switch (ch) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
return Byte.parseByte(String.valueOf(ch), 16);
default:
return 0x00;
}
}
}