Java 3DES 加密

来源:互联网 发布:麦德斯 米科尔森 知乎 编辑:程序博客网 时间:2024/06/05 14:48
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 *  */@Slf4jpublic 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;    }}
原创粉丝点击