RSA操作

//加密

public class Encryption implements IEncryption {



    private static final Logger log = LoggerFactory.getLogger(Encryption.class);


    /**
     * 私钥加密
     *
     * @param data 内容
     * @param privatekey 私钥
     * @return 密文
     * @throws Exception
     */
    @Override
    public byte[] encryptByPrivateKey(byte[] data, Key privatekey) throws Exception {
        Cipher cipher = Cipher.getInstance(privatekey.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privatekey);
        return cipher.doFinal(data);
    }


    /**
     * 公钥加密
     *
     * @param data 内容
     * @param publickey 公钥
     * @return 密文
     * @throws Exception
     */
    @Override
    public byte[] encryptByPublicKey(byte[] data, Key publickey) throws Exception {
        //对数据解密
        Cipher cipher = Cipher.getInstance(publickey.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publickey);
        return cipher.doFinal(data);
    }


    /**
     * 私钥解密
     *
     * @param data 密文
     * @param privatekey 私钥
     * @return 明文
     * @throws Exception
     */
    @Override
    public byte[] decryptByPrivateKey(byte[] data, Key privatekey) throws Exception {
        //对数据解密
        Cipher cipher = Cipher.getInstance(privatekey.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privatekey);
        return cipher.doFinal(data);
    }


    /**
     * 公钥解密
     *
     * @param data 密文
     * @param publickey 公钥
     * @return 明文
     * @throws Exception
     */
    @Override
    public byte[] decryptByPublicKey(byte[] data, Key publickey) throws Exception {
        //对数据解密
        Cipher cipher = Cipher.getInstance(publickey.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publickey);
        return cipher.doFinal(data);
    }

}


//读取密钥

public class KeyReader implements IKeyReader {


    private static final Logger log = LoggerFactory.getLogger(KeyReader.class);


    public KeyReader() {
        
    }


    /**
     * 从密钥文件中读取公钥
     *
     * @param kstorefile 密钥文件
     * @param kstoretype 密钥文件类型,例如:JKS
     * @param kstorepwd 密钥文件访问密码
     * @param alias 别名
     * @return 公钥
     */
    @Override
    public PublicKey getPublicKey(String kstorefile, String kstoretype, String kstorepwd, String alias) {


        try {
            KeyStore ks;
            try (FileInputStream in = new FileInputStream(kstorefile)) {
                ks = KeyStore.getInstance(kstoretype);
                ks.load(in, kstorepwd.toCharArray());
            }
            if (!ks.containsAlias(alias)) {
                log.warn("No such alias in the keystore.");
                return null;
            }
            Certificate cert = ks.getCertificate(alias);
            return cert.getPublicKey();
        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        } catch (FileNotFoundException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        } catch (IOException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        }
    }


    /**
     * 从密钥文件中读取私钥
     *
     * @param kstorefile 密钥文件
     * @param kstoretype 密钥文件类型,例如:JKS
     * @param kstorepwd 密钥文件访问密码
     * @param alias 别名
     * @return 私钥
     */
    @Override
    public PrivateKey getPrivateKey(String kstorefile, String kstoretype, String kstorepwd, String alias, String keypwd) {
        try {
            KeyStore ks;
            try (FileInputStream in = new FileInputStream(kstorefile)) {
                ks = KeyStore.getInstance(kstoretype);
                ks.load(in, kstorepwd.toCharArray());
            }
            if (!ks.containsAlias(alias)) {
                log.warn("No such alias in the keystore.");
                return null;
            }
            return (PrivateKey) ks.getKey(alias, keypwd.toCharArray());
        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException ex) {
            log.warn("getPrivateKey failure.", ex);
            return null;
        } catch (FileNotFoundException ex) {
            log.warn("getPrivateKey failure.", ex);
            return null;
        } catch (IOException ex) {
            log.warn("getPrivateKey failure.", ex);
            return null;
        }
    }


    @Override
    public String getCert(String kstorefile, String kstoretype, String kstorepwd, String alias) {
        try {
            KeyStore ks;
            try (FileInputStream in = new FileInputStream(kstorefile)) {
                ks = KeyStore.getInstance(kstoretype);
                ks.load(in, kstorepwd.toCharArray());
            }
            if (!ks.containsAlias(alias)) {
                log.warn("No such alias in the keystore.");
                return null;
            }
            X509Certificate cert = (X509Certificate) ks.getCertificate(alias);


            return Base64.encodeBase64String(cert.getEncoded());
        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        } catch (FileNotFoundException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        } catch (IOException ex) {
            log.warn("getPublicKey failure.", ex);
            return null;
        }
    }


    @Override
    public PrivateKey getPrivatekey(String DERfile) {
        PrivateKey privateKey = null;
        try {
            InputStream in = null;
            byte[] key = new byte[2048];
            in = new FileInputStream(DERfile);
            in.read(key);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
            return privateKey;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
            log.error("私钥证书文件格式错误",ex);
        } catch (IOException ex) {
            log.error(ex.getMessage(),ex);
        } 
        return privateKey;
    }


    @Override
    public PublicKey getPublickey(String CRTfile) {
        try {
            CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
            FileInputStream bais = new FileInputStream(CRTfile);
            X509Certificate Cert = (X509Certificate) certificatefactory.generateCertificate(bais);
            return Cert.getPublicKey();
        } catch (CertificateException | FileNotFoundException ex) {
            log.warn("getPublicKey failure", ex);
        }
        return null;
    }


    private byte[] getPemFileBytes(String fileName) {
        BufferedReader br;
        byte[] key = null;
        try {
            br = new BufferedReader(new FileReader(fileName));
            String s = br.readLine();
            String str = "";
            s = br.readLine();
            while (s.charAt(0) != '-') {
                str += s + "\r";
                s = br.readLine();
            }
            key = Base64.decodeBase64(str);
        } catch (Exception ex) {
            log.warn("read pem file failure.", ex);
        }


        return key;
    }
}


//签名

public class Sign implements ISignature {
    private static final Logger log = LoggerFactory.getLogger(Sign.class);


    /**
     * RSA签名
     *
     * @param content 待签内容
     * @param algorithm 签名算法,例如:MD5WithRSA、SHA1WithRSA
     * @param privatekey 私钥
     * @return 签名
     */
    @Override
    public byte[] sign(byte[] content, String algorithm, PrivateKey privatekey) {
        try {
            //用私钥对信息生成数字签名
            Signature stool = Signature.getInstance(algorithm);
            stool.initSign(privatekey);
            stool.update(content);
            return stool.sign();
        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException ex) {
            log.warn("sign failure.",ex);
            return null;
        }
    }


    /**
     * 校验签名
     *
     * @param content 待验内容
     * @param signature 签名
     * @param algorithm 签名算法,例如:MD5WithRSA、SHA1WithRSA
     * @param publickey 公钥
     * @return 是否有效签名
     */
    @Override
    public boolean verify(byte[] content,byte[] signature, String algorithm, PublicKey publickey) {
        try {
            Signature stool = Signature.getInstance(algorithm);
            stool.initVerify(publickey);
            stool.update(content);
            //验证签名是否正常
            return stool.verify(signature);
        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException ex) {
            log.warn("verify failure.",ex);
            return false;
        }
    }


}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值