# Please help me rewrite this Javascript function to Elixir

**URL:** <https://forum.elixirforum.com/t/please-help-me-rewrite-this-javascript-function-to-elixir/13532>\
**Category:** Questions\
**Created:** [April 6, 2018, 10:10pm UTC](https://forum.elixirforum.com/t/please-help-me-rewrite-this-javascript-function-to-elixir/13532 "2018-04-06T22:10:41Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![cmkarlsson](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/cmkarlsson/32/23000_2.png) [@cmkarlsson](https://forum.elixirforum.com/u/cmkarlsson)\
**Post date:** [April 6, 2018, 10:32pm UTC](https://forum.elixirforum.com/t/please-help-me-rewrite-this-javascript-function-to-elixir/13532/2 "2018-04-06T22:32:48Z")

</div>

Assuming this is what you want. RSA with RSA\_PKCS1\_PADDING has known flaws which is exploitable though the Bleichenbacker’s CCA attack. The improved version claims to crack RSA with as little as 15,000 attempts (assuming it has access to an oracle of some sort).

Anyway what you are trying to do is:

1. Read a PEM encoded certificate with a public key
2. Encrypt a buffer of data (max 245 for PKCS1 padding)
3. Base64 encode it.

You can use the `public_key` module to achieve this. From memory you do something like this:

```elixir
def security(plaintext, certificate) do

    #1) Decode the certificate. This assumes only one entry in the cert.
    [pem_entry] = :public_key.pem_decode(certificate)
    plk = :public_key.pem_entry_decode(pem_entry)

    #2) Encrypt the plaintext
    ciphertext = :public_key.encrypt_public(plaintext, plk, [{:rsa_pad, :rsa_pkcs1_padding}])

     #3) Base64 encode and return the result
     :base64.encode(ciphertext)
end

```

end

---

_[View the full topic](https://forum.elixirforum.com/t/please-help-me-rewrite-this-javascript-function-to-elixir/13532)._
