Skip to content

Instantly share code, notes, and snippets.

@mauriballes
Created September 6, 2019 16:44
Show Gist options
  • Save mauriballes/9075c005bec13ae3745de5f3751bda35 to your computer and use it in GitHub Desktop.
Save mauriballes/9075c005bec13ae3745de5f3751bda35 to your computer and use it in GitHub Desktop.
Encrypt (Ruby) and Decrypt (Java Android)

Encrypt

require 'openssl'
require 'json'
require 'base64'

def encrypt(string, pwd)
    salt = OpenSSL::Random.random_bytes(16)

    # prepare cipher for encryption
    e = OpenSSL::Cipher.new('AES-128-CBC')
    e.encrypt

    # next, generate a PKCS5-based string for your key + initialization vector
    key_iv = OpenSSL::PKCS5.pbkdf2_hmac_sha1(pwd, salt, 1024, e.key_len+e.iv_len)
    key = key_iv[0, e.key_len]
    iv  = key_iv[e.key_len, e.iv_len]

    # now set the key and iv for the encrypting cipher
    e.key = key
    e.iv  = iv

    # encrypt the data!
    encrypted = '' << e.update(string) << e.final
    [encrypted, iv, salt].map {|v| ::Base64.strict_encode64(v)}.join("--")
 end

Decrypt

import android.util.Base64;

import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class Utils {
    public static String decrypt(String encrypted, String pwd) throws Exception {

        String[] parts = encrypted.split("--");
        if (parts.length != 3) return null;

        byte[] encryptedData = Base64.decode(parts[0], Base64.DEFAULT);
        byte[] iv = Base64.decode(parts[1], Base64.DEFAULT);
        byte[] salt = Base64.decode(parts[2], Base64.DEFAULT);

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(pwd.toCharArray(), salt, 1024, 128);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey aesKey = new SecretKeySpec(tmp.getEncoded(), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));

        byte[] result = cipher.doFinal(encryptedData);
        return new String(result, "UTF-8");
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment