简体   繁体   中英

RSA algorithm PKCS #1.5 padding (not OEAP) password encryption with client certificate public key in Java

I am new to RSA algorithm and cryptography in Java. I have a client certificate provided by the 3rd party organization which is in .cer format. Now I need to encrypt my password with the public portion of the password key certificate, using the RSA algorithm and PKCS #1.5 padding - so not OAEP - in Java.

Could you check if the following does perform the above?

Security.addProvider(neworg.bouncycastle.jce.provider.BouncyCastleProvider());
byte[] input = "Abc123".getBytes();
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
FileInputStream fin = new FileInputStream(new File("/test.cer"));
CertificateFactory f = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
PublicKey pk = certificate.getPublicKey();
cipher.init(Cipher.ENCRYPT_MODE, pk, new SecureRandom());
byte[] cipherText = cipher.doFinal(input);

Yes, the code you provided looks OK.

Note that if you replace "RSA/None/PKCS1Padding" with "RSA/ECB/PKCS1Padding" that you could rely on the default Sun provider instead.


It is important to note that your code generates a "plain" signature; it doesn't include your data or certificate. Generally it is better to create a CMS Signed Data structure, which can for instance include the "leaf" certificate that you used to create the signature.

CMS is a so called cryptographic container format , which can hold structures such as the data, signature and additional information on the signature algorithm, certificates, signer etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM