1

Where can I find the equivalent to Google Go's EncryptRSA-OAEP() in Java?

From the link above, the following code example is given in Go:

secretMessage := []byte("send reinforcements, we're going to advance")
label := []byte("orders")

// crypto/rand.Reader is a good source of entropy for randomizing the
// encryption function.
rng := rand.Reader

ciphertext, err := EncryptOAEP(sha256.New(), rng, &test2048Key.PublicKey, secretMessage, label)
if err != nil {
    fmt.Fprintf(os.Stderr, "Error from encryption: %s\n", err)
    return
}

// Since encryption is a randomized function, ciphertext will be
// different each time.
fmt.Printf("Ciphertext: %x\n", ciphertext)

My question: How do you do the above in Java?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
user1068636
  • 1,871
  • 7
  • 33
  • 57
  • Mostly dupe https://stackoverflow.com/questions/49678052/rsa-oaep-golang-encrypt-java-decrypt-badpaddingexception-decryption-error except that you have a nonempty label fka parameters so you'll need `PSource.PSpecified(byte[])` – dave_thompson_085 Mar 04 '21 at 07:57

1 Answers1

1

You can use javax.crypto.Cipher for the rsa encryption with oaep padding

Cipher cipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC"); // Creating CIpher instance with RSA algorithm and oaep padding
// Random key generation for RSA
SecureRandom random = new SecureRandom();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC");

generator.initialize(386, random);

KeyPair pair = generator.generateKeyPair();
Key pubKey = pair.getPublic();

Key privKey = pair.getPrivate();
// Initializing Cipher with key and encrypt/decrypt mode
cipher.init(Cipher.ENCRYPT_MODE, pubKey, random);
// Encrypts the text
byte[] cipherText = cipher.doFinal(input);

Note: You need to add bouncycastle dependancy for this. Also add Bouncy castle provider to security.

Security.addProvider(new BouncyCastleProvider());
Sreejith
  • 102
  • 5
  • 1
    You should note in your answer that you need an external library ("Bouncy Castle") to run the example code. Btw: you can run a RSA OAEP-256 encryption without any 3rd party libraries. – Michael Fehr Mar 03 '21 at 07:37
  • Sreejith Unnikrishnan or @Michael Fehr , could either one of you modify the above code so that it works for SHA 256? If it requires Bouncy Castle that's fine, but I would like to see how it works with SHA 256. – user1068636 Mar 03 '21 at 21:13
  • You don't need Bouncy for RSA-OAEP since about 2006 and this doesn't handle a nonempty label fka parameters as in the Q. @user1068636: in general it depends on which provider(s) you are using whether you can just change the algorithm name, but in your case you are using a nonempty label so you _must_ use explicit `OAEPParameterSpec` which overrides the name. See link I added on Q. – dave_thompson_085 Mar 04 '21 at 07:59