【问题标题】:Using Java to Encrypt a private key [closed]使用 Java 加密私钥 [关闭]
【发布时间】:2013-01-29 06:44:09
【问题描述】:

我使用 CertAndKeyGen 类生成了一个私钥。现在我想用密码加密私钥,并在启动 PostgreSQL 服务器时将其用作密钥。有人可以帮我用java代码加密私钥,谷歌搜索可以帮助我。下面是我用来生成私钥的代码。

    CertAndKeyGen keypair = new CertAndKeyGen("RSA", "SHA1WithRSA", null);
    PrivateKey privKey = keypair.getPrivateKey();

任何帮助或建议将不胜感激。

【问题讨论】:

  • 你确定这真的是你需要做的吗?很奇怪的要求。肯定 PostGRES 服务器只需要 SSL 握手,可能带有客户端证书?

标签: java ssl x509certificate public-key-encryption private-key


【解决方案1】:
public class KeyEncryptExample {

    public static void main(String[] args) {
        try {
            String key = "mariahussain"; // needs to be at least 8 characters for DES

            FileInputStream fis = new FileInputStream("C:/Users/hussain.a/Desktop/original.txt");
            FileOutputStream fos = new FileOutputStream("C:/Users/hussain.a/Desktop/encrypted.txt");
            encrypt(key, fis, fos);

            FileInputStream fis2 = new FileInputStream("C:/Users/hussain.a/Desktop/encrypted.txt");
            FileOutputStream fos2 = new FileOutputStream("C:/Users/hussain.a/Desktop/decrypted.txt");
            decrypt(key, fis2, fos2);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
        encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
    }

    public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
        encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
    }

    public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {

        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
        SecretKey desKey = skf.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE

        if (mode == Cipher.ENCRYPT_MODE) {
            cipher.init(Cipher.ENCRYPT_MODE, desKey);
            CipherInputStream cis = new CipherInputStream(is, cipher);
            doCopy(cis, os);
        } else if (mode == Cipher.DECRYPT_MODE) {
            cipher.init(Cipher.DECRYPT_MODE, desKey);
            CipherOutputStream cos = new CipherOutputStream(os, cipher);
            doCopy(is, cos);
        }
    }

    public static void doCopy(InputStream is, OutputStream os) throws IOException {
        byte[] bytes = new byte[64];
        int numBytes;
        while ((numBytes = is.read(bytes)) != -1) {
            os.write(bytes, 0, numBytes);
        }
        os.flush();
        os.close();
        is.close();
    }

}

【讨论】:

    猜你喜欢
    • 2016-03-19
    • 2013-02-08
    • 2015-08-23
    • 2018-07-05
    • 2014-02-07
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多