Java 3DES 加密
阿新 • • 發佈:2019-01-10
package com.dataservice.utils.crypto;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Enumeration;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.util.encoders.Base64;
import com.dataservice.utils.DsContent;
/**
* 3DES加密
*
* @version 1.0
* @author
*
*/
@Slf4j
public class EncDecUtil {
private EncDecUtil() {
}
/**
* 獲取證書私鑰
*
* @return
* @throws IOException
*/
public static String getCertKey(String mi, String path) {
try {
InputStream is = new FileInputStream(path);
return getCertKey(mi, is);
} catch (FileNotFoundException e) {
log.error("read file error", e);
}
return null;
}
/**
* 獲取證書私鑰
*
* @return
* @throws IOException
*/
public static String getCertKey(String mi, InputStream is) {
String billRsaKey = "";
try {
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(is, mi.toCharArray());
Enumeration<String> enuma = ks.aliases();
String keyAlias = null;
if (enuma.hasMoreElements()) {
keyAlias = (String) enuma.nextElement();
}
PrivateKey privatekey = (PrivateKey) ks.getKey(keyAlias, mi.toCharArray());
billRsaKey = StringUtils.toEncodedString(Base64.encode(privatekey.getEncoded()), DsContent.DATA_CHARSET);
} catch (Exception e) {
log.error("get private key error", e);
} finally {
IOUtils.closeQuietly(is);
}
return billRsaKey;
}
/**
* 獲取證書公鑰
*
* @return
* @throws IOException
*/
public static String getPublicCertKey(String path) {
String publicCertPath = path;// "D://dev2.cer";
String billRsaKey = "";
try {
// 簽名 公鑰解密
CertificateFactory cff = CertificateFactory.getInstance("X.509");
FileInputStream fis1 = new FileInputStream(publicCertPath); // 證書檔案
Certificate cf = cff.generateCertificate(fis1);
PublicKey publicKey = cf.getPublicKey();
byte[] pk = publicKey.getEncoded();
billRsaKey = StringUtils.toEncodedString(Base64.encode(pk), DsContent.DATA_CHARSET);
} catch (Exception e) {
log.error("get public key error", e);
}
return billRsaKey;
}
}