SMS Encryption and Decryption Script

Introduction to SMSGatewayCenter APIs

Welcome to SMSGatewayCenter’s Developer Hub! This comprehensive resource empowers you to integrate robust messaging into your applications with our powerful message encryption and decryption capabilities. This guide introduces the SMS Encryption and Decryption Scripts, part of our messaging suite, including SMS API for bulk messaging, WhatsApp Business API for customer engagement, Voice Call API for automated alerts, and Two-Way SMS API for interactive communication. Ideal for developers in India, secure your messaging with our SMS gateway at unify.smsgatewaycenter.com/signup/.

Learn how to encrypt and decrypt SMS messages using SMSGatewayCenter’s Encryption API. These scripts provide a secure way to protect sensitive data, ensuring end-to-end encryption for corporate, banking, and priority messages. Use our PHP and Java samples to integrate encryption and decryption into your applications, leveraging our POST-only APIs for maximum security and privacy.

SMS Encryption and Decryption Script in PHP and JAVA
SMS Encryption and Decryption Script in PHP

Encrypt SMS Message API

<?php
	 /**
	 * AesCipher
	 *
	 * Encode/Decode text by password using AES-128-CBC algorithm
	 */
	class AesCipher {

		const CIPHER = 'AES-128-CBC';
		const INIT_VECTOR_LENGTH = 16;

		/**
		 * Encoded/Decoded data
		 *
		 * @var null|string
		 */
		protected $data;

		/**
		 * Initialization vector value
		 *
		 * @var string
		 */
		protected $initVector;

		/**
		 * Error message if operation failed
		 *
		 * @var null|string
		 */
		protected $errorMessage;

		/**
		 * AesCipher constructor.
		 *
		 * @param string $initVector        Initialization vector value
		 * @param string|null $data         Encoded/Decoded data
		 * @param string|null $errorMessage Error message if operation failed
		 */
		public function __construct($initVector, $data = null, $errorMessage = null) {
			$this->initVector = $initVector;
			$this->data = $data;
			$this->errorMessage = $errorMessage;
		}

		/**
		 * Encrypt input text by AES-128-CBC algorithm
		 *
		 * @param string $secretKey 16/24/32 -characters secret password
		 * @param string $plainText Text for encryption
		 *
		 * @return self Self object instance with data or error message
		 */
		public static function encrypt($secretKey, $plainText) {
			try {
				// Check secret length
				if (!static::isKeyLengthValid($secretKey)) {
					throw new \InvalidArgumentException("Secret key's length must be 128, 192 or 256 bits");
				}

				// Get random initialization vector
				$initVector = bin2hex(openssl_random_pseudo_bytes(static::INIT_VECTOR_LENGTH / 2));

				// Encrypt input text
				$raw = openssl_encrypt(
					$plainText, static::CIPHER, $secretKey, OPENSSL_RAW_DATA, $initVector
				);

				// Return base64-encoded string: initVector + encrypted result
				$result = base64_encode($initVector . $raw);

				if ($result === false) {
					// Operation failed
					return new static($initVector, null, openssl_error_string());
				}

				// Return successful encoded object
				return new static($initVector, $result);
			} catch (\Exception $e) {
				// Operation failed
				return new static(isset($initVector), null, $e->getMessage());
			}
		}

		/**
		 * Decrypt encoded text by AES-128-CBC algorithm
		 *
		 * @param string $secretKey  16/24/32 -characters secret password
		 * @param string $cipherText Encrypted text
		 *
		 * @return self Self object instance with data or error message
		 */
		public static function decrypt($secretKey, $cipherText) {
			try {
				// Check secret length
				if (!static::isKeyLengthValid($secretKey)) {
					throw new \InvalidArgumentException("Secret key's length must be 128, 192 or 256 bits");
				}

				// Get raw encoded data
				$encoded = base64_decode($cipherText);
				// Slice initialization vector
				$initVector = substr($encoded, 0, static::INIT_VECTOR_LENGTH);
				// Slice encoded data
				$data = substr($encoded, static::INIT_VECTOR_LENGTH);

				// Trying to get decrypted text
				$decoded = openssl_decrypt(
					$data, static::CIPHER, $secretKey, OPENSSL_RAW_DATA, $initVector
				);

				if ($decoded === false) {
					// Operation failed
					return new static(isset($initVector), null, openssl_error_string());
				}

				// Return successful decoded object
				return new static($initVector, $decoded);
			} catch (\Exception $e) {
				// Operation failed
				return new static(isset($initVector), null, $e->getMessage());
			}
		}

		/**
		 * Check that secret password length is valid
		 *
		 * @param string $secretKey 16/24/32 -characters secret password
		 *
		 * @return bool
		 */
		public static function isKeyLengthValid($secretKey) {
			$length = strlen($secretKey);

			return $length == 16 || $length == 24 || $length == 32;
		}

		/**
		 * Get encoded/decoded data
		 *
		 * @return string|null
		 */
		public function getData() {
			return $this->data;
		}

		/**
		 * Get initialization vector value
		 *
		 * @return string|null
		 */
		public function getInitVector() {
			return $this->initVector;
		}

		/**
		 * Get error message
		 *
		 * @return string|null
		 */
		public function getErrorMessage() {
			return $this->errorMessage;
		}

		/**
		 * Check that operation failed
		 *
		 * @return bool
		 */
		public function hasError() {
			return $this->errorMessage !== null;
		}

		/**
		 * To string return resulting data
		 *
		 * @return null|string
		 */
		public function __toString() {
			return $this->getData();
		}

	}

	// USAGE
	$secretKey = "256c6edda5e945d5";
	$text = "This is a test message";
	$encodedtext = 'ZTNhOWYxOGM0Mzk4OTAxZWfnlVSBVPjyGsaw8fFZqBs9BlVBHi9tJJBObfbPvqYa';
	$encrypted = AesCipher::encrypt($secretKey, $text);
	$decrypted = AesCipher::decrypt($secretKey, $encodedtext);
	//echo $decrypted->getData();
	//$encrypted->hasError(); // TRUE if operation failed, FALSE otherwise
	echo $encrypted; // Encoded result
	echo "<br>";
	echo $decrypted; // Decoded result
SMS Encryption and Decryption Script in JAVA

Decrypt SMS Message API

import java.nio.ByteBuffer;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * AesCipher
 * <p>
 * Encode/Decode text by password using AES-128-CBC algorithm
 * </p>
 */
public class AesCipher {
    public static final int INIT_VECTOR_LENGTH = 16;

    private final static char[] hexArray = "0123456789ABCDEF".toCharArray();

    /**
     * Encoded/Decoded data
     */
    protected String data;
    /**
     * Initialization vector value
     */
    protected String initVector;
    /**
     * Error message if operation failed
     */
    protected String errorMessage;

    private AesCipher() {
        super();
    }

    /**
     * AesCipher constructor.
     *
     * @param initVector   Initialization vector value
     * @param data         Encoded/Decoded data
     * @param errorMessage Error message if operation failed
     */
    private AesCipher(String initVector, String data, String errorMessage) {
        super();

        this.initVector = initVector;
        this.data = data;
        this.errorMessage = errorMessage;
    }

    /**
     * Encrypt input text by AES-128-CBC algorithm
     *
     * @param secretKey 16/24/32 -characters secret password
     * @param plainText Text for encryption
     * @return Encoded string or NULL if error
     */

    private static final Logger logger = LogManager.getLogger("default");

    public static AesCipher encrypt(String secretKey, String plainText) {
        AesCipher aes = new AesCipher();
        String initVector = null;
        try {
            // Check secret length
            if (!isKeyLengthValid(secretKey)) {
                throw new Exception("Secret key's length must be 128, 192 or 256 bits");
            }

            // Get random initialization vector
            SecureRandom secureRandom = new SecureRandom();
            byte[] initVectorBytes = new byte[INIT_VECTOR_LENGTH / 2];
            secureRandom.nextBytes(initVectorBytes);
            initVector = bytesToHex(initVectorBytes);
            initVectorBytes = initVector.getBytes("UTF-8");

            IvParameterSpec ivParameterSpec = new IvParameterSpec(initVectorBytes);
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

            // Encrypt input text
            byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));

            ByteBuffer byteBuffer = ByteBuffer.allocate(initVectorBytes.length + encrypted.length);
            byteBuffer.put(initVectorBytes);
            byteBuffer.put(encrypted);

            // Result is base64-encoded string: initVector + encrypted result
            String result = Base64.encodeToString(byteBuffer.array(), Base64.DEFAULT);

            // Return successful encoded object
            aes = new AesCipher(initVector, result, null);
        } catch (Exception t) {
            logger.error("Exception while decrypt", t);
        }
        return aes;
    }

    /**
     * Decrypt encoded text by AES-128-CBC algorithm
     *
     * @param secretKey  16/24/32 -characters secret password
     * @param cipherText Encrypted text
     * @return Self object instance with data or error message
     */
    public static AesCipher decrypt(String secretKey, String cipherText) {
        AesCipher aes = new AesCipher();

        try {
            // Check secret length
            if (!isKeyLengthValid(secretKey)) {
                throw new Exception("Secret key's length must be 128, 192 or 256 bits");
            }

            // Get raw encoded data
            byte[] encrypted = Base64.decode(cipherText, Base64.DEFAULT);

            // Slice initialization vector
            IvParameterSpec ivParameterSpec = new IvParameterSpec(encrypted, 0, INIT_VECTOR_LENGTH);
            // Set secret password
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

            // Trying to get decrypted text
            String result = new String(
                cipher.doFinal(encrypted, INIT_VECTOR_LENGTH, encrypted.length - INIT_VECTOR_LENGTH));

            // Return successful decoded object
            aes = new AesCipher(bytesToHex(ivParameterSpec.getIV()), result, null);
        } catch (Exception e) {
            logger.error("Exception while decrypt", e);
        }
        return aes;
    }

    /**
     * Check that secret password length is valid
     *
     * @param key 16/24/32 -characters secret password
     * @return TRUE if valid, FALSE otherwise
     */
    public static boolean isKeyLengthValid(String key) {
        return key.length() == 16 || key.length() == 24 || key.length() == 32;
    }

    /**
     * Convert Bytes to HEX
     *
     * @param bytes Bytes array
     * @return String with bytes values
     */
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    /**
     * Get encoded/decoded data
     */
    public String getData() {
        return data;
    }

    /**
     * Get initialization vector value
     */
    public String getInitVector() {
        return initVector;
    }

    /**
     * Get error message
     */
    public String getErrorMessage() {
        return errorMessage;
    }

    /**
     * Check that operation failed
     *
     * @return TRUE if failed, FALSE otherwise
     */
    public boolean hasError() {
        return this.errorMessage != null;
    }

    /**
     * To string return resulting data
     *
     * @return Encoded/decoded data
     */
    public String toString() {
        return getData().trim();
    }

    public static void main(String[] args) {

        // USAGE
        String secretKey = "256c6edda5e945d5";
        String text = "Hello";

        AesCipher encrypted = AesCipher.encrypt(secretKey, text);
        //		AesCipher decrypted = AesCipher.decrypt(secretKey,text);

        System.out.println(encrypted.getData().trim());
        // Encoded/Decoded result
        // decrypted.* has identical methods
    }
}							
Unlock Real-Time Messaging – Integrate Today!

Unlock Real-Time Messaging – Integrate Today!

Try Our API in a Sandbox Environment Before Going Live!

Join Thousands of Developers – Try Our API Now!

Get in touchSign up

Testimonials

Why do Great Businesses Trust SMS Gateway Center?

K

Kurlon IT

2022-08-04

We have tied up with other SMS providers also, but SMS GatewayCenter is quite good. Good Service from the team. We are very happy with the service be it accounts related or technical issue. We always get good response.

I

INOX Air Products

2018-02-09

We have an excellent experience with SMS Gateway Center. The services and support has been of very high standard.

R

Rohit Singh Rawat

2017-06-05

It is the best SMS gateway to send bulk messages. It's the best and easiest way to reach out to your goals... Planning is everything to attain goal and adding SMS Gateway Center in that plan will definitely help in accomplishing goals... Thanks to the developers...

A

Anil Singh

2018-02-09

We have an excellent experience with SMS Gateway Center. The services and support has been of very high standard.