在Java中从数据库读取公共密钥文件

时间:2019-10-29 04:53:41

标签: java bouncycastle

我正在使用Bouncy城​​堡源代码使用公共密钥对字符串进行加密。但是在代码中,我将公共密钥作为文件输入提供,但是我必须从mysql数据库中获取公共密钥。请帮助我进行修改。

这是我使用的代码

    public static String encryptToString(String inputStr, String keyFile) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        byte[] original = inputStr.getBytes();
        FileInputStream pubKey = new FileInputStream(keyFile);
        byte[] encrypted = encrypt(original, readPublicKey(pubKey), null,
                true, true);
        return new String(encrypted);
    }

    public static void main(String[] args) throws Exception {
        String encrypted = encryptToString("zuhair","/root/Documents/pubK.asc");
        System.out.println(encrypted);

}

这是readPublicKey方法

 private static PGPPublicKey readPublicKey(InputStream in)
            throws IOException, PGPException {
        in = PGPUtil.getDecoderStream(in);

        PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in);

           Iterator rIt = pgpPub.getKeyRings();

        while (rIt.hasNext()) {
            PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next();
            Iterator kIt = kRing.getPublicKeys();

            while (kIt.hasNext()) {
                PGPPublicKey k = (PGPPublicKey) kIt.next();

                if (k.isEncryptionKey()) {
                    return k;
                }
            }
        }

        throw new IllegalArgumentException(
                "Can't find encryption key in key ring.");
    }

0 个答案:

没有答案