2
votes

I want to encrypt my post payload with an X.509 certificate and the inherited public key. So far I have this java code to perform the encryption

private String encrypt(String str) throws Exception {
    ClassPathResource classPathResource = new ClassPathResource("testcert1.crt");
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate)certificateFactory.generateCertificate(classPathResource.getInputStream());
    PublicKey pk = certificate.getPublicKey();
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    cipher.init(Cipher.ENCRYPT_MODE, pk);
    return Base64.encodeBase64String(cipher.doFinal(str.getBytes()));
}

which returns the base64 encoded string. From the endpoint I am always getting the result, that the certificate is not valid.

So I want to validate my encrypted string on the console using the openssl command, but failing to do so.

I can read out the certificate with: openssl x509 -in testcert1.crt -text -noout

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 0 (0x0)
        Signature Algorithm: md5WithRSAEncryption
        Issuer: C=xxx, ST=xxx, L=xxx, O=xxx, OU=xxx, CN=xxx
        Validity
            Not Before: Jul 24 11:40:39 2013 GMT
            Not After : Jul 24 11:40:39 2015 GMT
        Subject: C=xxx, ST=xxx, L=xxx, O=xxx, OU=xxx, CN=xxx
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
            RSA Public Key: (4096 bit)
                Modulus (4096 bit):
                ....
             Exponent: 65537 (0x10001)

But I cannot figure out the command lines to encrypt/decrypt a text file using that certificate

2
md5WithRSAEncryption and a 4096-bit key is a real mismatch. Perhaps you should consider sha256WithRSAEncryption. MD5 has less than 64-bits of security remaining, while a 4096-bit modulus has over 128-bits of security. MD5 is broken, and cannot provide the collision resistance over time.jww
ok I will take that for consideration. I haven't been the one creating that key, rather the consumer that received the key from a third partyMatthiasLaug
Why? Why not use HTTPS like everybody else?user207421
And what encrypted string. If the certificate isn't valid, how can you possibly get an encryption? And where s the stack trace for the exception?user207421

2 Answers

1
votes

You can validate your encrypted string using openssl with the following command:

echo -n 'string to encrypt' | openssl rsautl -encrypt -certin -inkey testcert1.crt | base64
-4
votes

As you are using asymmetric cryptography, if you encrypt using the public key of your certificate, you can only decrypt using the corresponding private key. Make sure you have that key and use it for decryption.