# Encryption and Decryption

Here goes the Encryption and Decryption procedure for data encrypted within the enc\_payload object of your webhook payload.

{% tabs %}
{% tab title="NodeJS (TS)" %}
Encryption

<pre class="language-typescript"><code class="lang-typescript"><strong>export const encryptor = (decryptedData: string, publicKey: any, encryptionKey: any) => {
</strong>    const cipher = 'aes-256-cbc'

    const enc_key = crypto.createHash('sha256').update(String(publicKey)).digest('base64').substr(0, 32);
    const pub_key = crypto.createHash('sha256').update(String(encryptionKey)).digest('base64').substr(0, 16);


    const encrypt = crypto.createCipheriv(cipher, enc_key, pub_key)

    let encryption = encrypt.update(decryptedData, 'utf8', 'base64')
    encryption += encrypt.final('base64')

    return encryption
}
</code></pre>

Decryption

```typescript
export const decryptor = (encryptedData: string, publicKey: any, encryptionKey: any) => {
    const cipher = 'aes-256-cbc'

    const enc_key = crypto.createHash('sha256').update(String(publicKey)).digest('base64').substr(0, 32);
    const pub_key = crypto.createHash('sha256').update(String(encryptionKey)).digest('base64').substr(0, 16);

    const decrypt = crypto.createDecipheriv(cipher, enc_key, pub_key)

    let decryption = decrypt.update(encryptedData, 'base64', 'utf8')
    decryption += decrypt.final('utf8')

    return decryption
}

```

{% endtab %}

{% tab title="PHP" %}
Encryption

```php
function encryptor($decryptedData, $publicKey, $encryptionKey) {
    $cipher = 'aes-256-cbc';

    $enc_key = substr(base64_encode(hash('sha256', strval($encryptionKey), true)), 0, 32);
    $pub_key = substr(base64_encode(hash('sha256', strval($publicKey), true)), 0, 16);

    $encryption = openssl_encrypt($decryptedData, $cipher, $enc_key, 0, $pub_key);

    return $encryption;
}
```

Decryption

```php
function decryptor($encryptedData, $publicKey, $encryptionKey) {
    $cipher = 'aes-256-cbc';

    $enc_key = substr(base64_encode(hash('sha256', strval($encryptionKey), true)), 0, 32);
    $pub_key = substr(base64_encode(hash('sha256', strval($publicKey), true)), 0, 16);

    $decryption = openssl_decrypt($encryptedData, $cipher, $enc_key, 0, $pub_key);

    return $decryption;
}
```

{% endtab %}

{% tab title="Python" %}
Encryption

```python
from Crypto.Cipher import AES
import hashlib
import base64

def encryptor(decryptedData, publicKey, encryptionKey):
    cipher = AES.new(hashlib.sha256(str(encryptionKey).encode()).digest()[:32], AES.MODE_CBC, hashlib.sha256(str(publicKey).encode()).digest()[:16])
    encryption = base64.b64encode(cipher.encrypt(decryptedData.encode())).decode('utf-8')
    return encryption
```

Decryption

```python
def decryptor(encryptedData, publicKey, encryptionKey):
    cipher = AES.new(hashlib.sha256(str(encryptionKey).encode()).digest()[:32], AES.MODE_CBC, hashlib.sha256(str(publicKey).encode()).digest()[:16])
    decryption = cipher.decrypt(base64.b64decode(encryptedData)).decode('utf-8').rstrip('\0')
    return decryption
```

{% endtab %}

{% tab title="JAVA" %}

```java
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class CryptoUtils {
    // Encryption Method
    public static String encryptor(String decryptedData, String publicKey, String encryptionKey) throws Exception {
        String cipher = "AES/CBC/PKCS5Padding";

        byte[] encKey = sha256(encryptionKey).substring(0, 32).getBytes(StandardCharsets.UTF_8);
        byte[] pubKey = sha256(publicKey).substring(0, 16).getBytes(StandardCharsets.UTF_8);

        Cipher encryptCipher = Cipher.getInstance(cipher);
        encryptCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encKey, "AES"), new IvParameterSpec(pubKey));

        byte[] encryption = encryptCipher.doFinal(decryptedData.getBytes(StandardCharsets.UTF_8));

        return Base64.getEncoder().encodeToString(encryption);
    }

    // Decryption Method
    public static String decryptor(String encryptedData, String publicKey, String encryptionKey) throws Exception {
        String cipher = "AES/CBC/PKCS5Padding";

        byte[] encKey = sha256(encryptionKey).substring(0, 32).getBytes(StandardCharsets.UTF_8);
        byte[] pubKey = sha256(publicKey).substring(0, 16).getBytes(StandardCharsets.UTF_8);

        Cipher decryptCipher = Cipher.getInstance(cipher);
        decryptCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(encKey, "AES"), new IvParameterSpec(pubKey));

        byte[] decryption = decryptCipher.doFinal(Base64.getDecoder().decode(encryptedData));

        return new String(decryption, StandardCharsets.UTF_8).trim();
    }

    // String Builder method 
    private static String sha256(String input) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));

        StringBuilder hexString = new StringBuilder();
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }

        return hexString.toString();
    }
}

```

{% endtab %}

{% tab title="GO" %}

```go
package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
)

func encryptor(decryptedData string, pub string, enc string) (string, error) {
	cipherBlock, err := aes.NewCipher([]byte(sha256Hash(enc)[:32]))
	if err != nil {
		return "", err
	}

	iv := []byte(sha256Hash(pub)[:16])
	cfb := cipher.NewCFBEncrypter(cipherBlock, iv)
	encryption := make([]byte, len(decryptedData))
	cfb.XORKeyStream(encryption, []byte(decryptedData))

	return base64.StdEncoding.EncodeToString(encryption), nil
}

func decryptor(encryptedData string, pub string, enc string) (string, error) {
	cipherBlock, err := aes.NewCipher([]byte(sha256Hash(enc)[:32]))
	if err != nil {
		return "", err
	}

	iv := []byte(sha256Hash(pub)[:16])
	cfb := cipher.NewCFBDecrypter(cipherBlock, iv)
	decryption := make([]byte, len(encryptedData))
	cfb.XORKeyStream(decryption, base64.StdEncoding.DecodeString(encryptedData))

	return string(decryption), nil
}

func sha256Hash(input string) string {
	hash := sha256.New()
	hash.Write([]byte(input))
	return fmt.Sprintf("%x", hash.Sum(nil))
}

func main() {
	encryptedData := "your_encrypted_data"
	decryptedData := "your_decrypted_data"
	pub := "your_browpay_public_key"
	enc := "your_browpay_encryption_key"

	encryption, err := encryptor(decryptedData, pub, enc)
	if err != nil {
		fmt.Println("Encryption Error:", err)
		return
	}
	fmt.Println("Encrypted:", encryption)

	decryption, err := decryptor(encryption, pub, enc)
	if err != nil {
		fmt.Println("Decryption Error:", err)
		return
	}
	fmt.Println("Decrypted:", decryption)
}

```

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://developer.browpay.com/webhooks/encryption-and-decryption.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
