如何在Ruby中使用Java生成的RSA密钥?

时间:2014-07-18 08:50:44

标签: java ruby encryption rsa public-key

我在加载由 Ruby 中的 Java 生成的 RSA公钥时遇到问题。

RSA公钥由Java以X509格式编码。仅供参考,这是用于生成公钥的Java代码

public static void generateKeys() throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);
    KeyPair kp = kpg.genKeyPair();
    PublicKey publicKey = kp.getPublic();
    PrivateKey privateKey = kp.getPrivate();

    System.out.println("keys created");

    KeyFactory fact = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec pub = fact.getKeySpec(publicKey,
            RSAPublicKeySpec.class);
    RSAPrivateKeySpec priv = fact.getKeySpec(privateKey,
            RSAPrivateKeySpec.class);

    saveToFile("public.key", pub.getModulus(), pub.getPublicExponent());
    saveToFile("private.key", priv.getModulus(), priv.getPrivateExponent());

    System.out.println("keys saved");
}

public static void saveToFile(String fileName, BigInteger mod,
        BigInteger exp) throws IOException {
    ObjectOutputStream fileOut = new ObjectOutputStream(
            new BufferedOutputStream(new FileOutputStream(fileName)));
    try {
        fileOut.writeObject(mod);
        fileOut.writeObject(exp);
    } catch (Exception e) {
        throw new IOException("Unexpected error");
    } finally {
        fileOut.close();
        System.out.println("Closed writing file.");
    }
}

我尝试使用:

在Ruby中使用public.key
public_key = OpenSSL::PKey::RSA.new File.read 'public.key' and
cert = OpenSSL::X509::Certificate.new File.read 'public.key'

但它们都不起作用,而是打印出错误信息:

OpenSSL::PKey::RSAError:
  Neither PUB key nor PRIV key:: header too long
OpenSSL::X509::CertificateError:
  header too long

我打算使用 public.key 加密Ruby中的某些数据。谁能帮我吗?我非常感谢,谢谢!

0 个答案:

没有答案