How to implement AES encryption in Ruby - java

guys
Here's a snippet of code of Java about AES encrypt:
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
...
public static String encrypt(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] byteContent = content.getBytes("utf-8");
byte[] result = cipher.doFinal(byteContent);
return Base64.encode(result);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
Now I try to implement it in Ruby(not work):
def self.aes128_encrypt(password, content)
cipher = OpenSSL::Cipher.new('AES-128-ECB')
cipher.encrypt
cipher.key = password
result = cipher.update(content) + cipher.final
Base64.encode64(result).chomp
end
After some research, I think the problem is the cipher#key: In Java, it's generate by securerandom with password as seed, But in Ruby, I use the password directly.
So I want to generate key like Java. But I find the random number generator used by Java is NativePRNG, which I do not find the same implementation so far.
Now, I want to ask help from guys familiar with Ruby and Java:
How can I implement the same AES encrypt in Ruby?
Or how to generate random string in Ruby with NativePRNG.
Any advice is welcome, and Thank you very much for each reply.

Related

Getting the Hex String from cipherText in Net Core

Currently doing a encryption in java which takes
API Secret. Perform Secret key hash algorithm by using SHA256. The resulted hash algorithm would be Encrypted Key = SHA256 (API Secret)
Request Raw Parameter(param) in JSon format encrypted using the Encrypted Key trough the AES/ECB/PKCS5Padding algorithm, and the ciphertext is converted into hexadecimal characters to be the value of the Encrypted data
Encrypted Data = aesEcbPkcs5Padding (param, Encrypted key)
Here are the codes in Java
public static byte[] aesEcbPkcs5PaddingEncrypt(String content, String key) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] aesKey = digest.digest(key.getBytes());
SecretKey secretKey = new SecretKeySpec(aesKey,"AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(content.getBytes("utf-8"));
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
I Need to do the same encryption but using Net Core and C#.This is the code in C# Net Core
All i can do is something like this.
public static byte[] aesEcbPkcs5PaddingEncrypt(String content, string secretKey)
{
byte[] hashBytes = Encoding.UTF8.GetBytes(secretKey);
byte[] cipher_content = Encoding.UTF8.GetBytes(content);
using (AesManaged aes = new AesManaged())
{
byte[] encrypted = Encrypt(raw, aes.Key, aes.IV);
// Print encrypted string
Console.WriteLine($ "Encrypted data: {System.Text.Encoding.UTF8.GetString(encrypted)}");
// Decrypt the bytes to a string.
string decrypted = Decrypt(encrypted, aes.Key, aes.IV);
}
SHA256 sha256 = SHA256Managed.Create();
byte[] cryptPassword = sha256.ComputeHash(hashBytes);
}
Is there any better solution/Correct solution in net core which will resulted with the same result as Java?

Java AES decryption with passphrase

I'm new to Java and encryption. I'm tying to figure out how to decrypt a base64 string using a 36bit GUID string as the secret. As I understand it, I need to convert the GUID passphrase into a 256bit key in order for this to work? Could someone point me in the right direction on how to do this? I've tried some standard AES decryption code like the below but I get a javax.crypto.BadPaddingException: Given final block not properly padded error.
public static String decrypt(String strToDecrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)), "UTF-8");
}
catch (Exception e)
{
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
public static void setKey(String myKey)
{
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
UPDATE
So after more digging the string is encrypted using the crypto-js library with the default AES encryption function. This question has an example to decrypt this and a good explanation of how crypto-js encrypts with AES.

Why does encrypting in one Java class and decrypting in another causes BadPaddingError?

I have a test function that returns a byte[] in one Java class, FirstClass:
public static byte[] testA(){
CipherClass crypto = new CipherClass();
byte[] a = crypto.encrypt("helloWorld");
return a;
}
Where CipherClass contains my java.crypto.Cipher methods to encrypt and decrypt inputs.
In another Java class, SecondClass, I instantiate my previous FirstClass and call its testA() method which I save to a byte[] variable and then try to decrypt it:
FirstClass fc = new FirstClass();
byte[] b = fc.testA();
System.out.println(crypto.decrypt(b)); //Outputs BadPaddingError
Why does encrypting a String in one Java file and then passing the resulting byte[] into another Java file to decrypt it causes a BadPaddingError?
What can be done to fix a way around this?
Why does the Cipher only work if both encryption and decryption are in the same class as follows?:
CipherClass crypto = new CipherClass();
byte[] a = crypto.encrypt("helloWorld"); //Outputs [B#5474c6c
byte[] b = a;
System.out.println(crypto.decrypt(b)); //Outputs "helloWorld"
EDIT: My CipherClass code as requested below.
SecretKey and IVParameterSpec generator:
public List<KeyGenerator> getKeyGenerator(){
List<KeyGenerator> list = new ArrayList<KeyGenerator>();
KeyGenerator keyGenerator;
int keyBitSize = 128;
try
{
SecureRandom secureRandom = new SecureRandom();
keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(keyBitSize, secureRandom);
list.add(keyGenerator);
return list;
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return list;
}
public List<SecretKey> getSecretKey(List<KeyGenerator> keygen) {
List<SecretKey> list = new ArrayList<SecretKey>();
KeyGenerator keyGenerator;
SecretKey secretKey;
keyGenerator = keygen.get(0);
secretKey = keyGenerator.generateKey();
list.add(secretKey);
return list;
}
public List<IvParameterSpec> getIvSpec(List<SecretKey> secretKey) {
List<IvParameterSpec> list = new ArrayList<IvParameterSpec>();
Cipher cipher;
byte[] iv;
try
{
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
iv = new byte[cipher.getBlockSize()];
IvParameterSpec ivSpec = new IvParameterSpec(iv);
list.add(ivSpec);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
return list;
}
List<KeyGenerator> kgList = getKeyGenerator();
List<SecretKey> skList = getSecretKey(kgList); //skList.get(0) is the SecretKey
List<IvParameterSpec> ivList = getIvSpec(skList); //ivList.get(0) is the IVParameterSpec
My encrypt() method:
public byte[] encrypt(String inputStr) {
Cipher cipher;
SecretKey secretKey = skList.get(0);
IvParameterSpec ivSpec = ivList.get(0);
byte[] plainText;
byte[] cipherText = new byte[]{};
try
{
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
try
{
secretKey = skList.get(0);
ivSpec = ivList.get(0);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
try
{
plainText = inputStr.getBytes("UTF-8");
cipherText = cipher.doFinal(plainText);
return cipherText;
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
catch (InvalidAlgorithmParameterException e1)
{
e1.printStackTrace();
}
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
return cipherText;
}
My decrypt() method:
public String decrypt(byte[] cipherText){
Cipher cipherDe;
SecretKey secretKey = skList.get(0);
IvParameterSpec ivSpec = ivList.get(0);
byte[] deciByte;
String decryptText = "";
try
{
cipherDe = Cipher.getInstance("AES/CBC/PKCS5Padding");
try
{
secretKey = skList.get(0);
ivSpec = ivList.get(0);
cipherDe.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
try
{
//De-cryption
deciByte = cipherDe.doFinal(cipherText);
decryptText = new String(deciByte);
return decryptText;
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
//De-cryption
catch (InvalidAlgorithmParameterException e1)
{
e1.printStackTrace();
}
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
return decryptText;
}

Decryption returns an empty string when encrypting text in Android

I'm trying to save few text fields securely. For that I'm trying to encrypt and decrypt the content. This is the code:
public class SecureStorage {
public String getPassword() {
if(!isRooted()) {
String password = pref.getPassword("");
System.out.println("pass getPass: " + password);
return password.isEmpty() ? password : new String(decrypt(Base64.decode(password, Base64.DEFAULT)));
} else
return "";
}
public void setPassword(String passwordStr) {
if(!isRooted()) {
byte[] password = encrypt(passwordStr.getBytes());
pref.setPassword(password == null ? "" : Base64.encodeToString(password, Base64.DEFAULT));
}
}
private SecretKey generateKey() {
// Generate a 256-bit key
final int outputKeyLength = 256;
try {
SecureRandom secureRandom = new SecureRandom();
// Do *not* seed secureRandom! Automatically seeded from system entropy.
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(outputKeyLength, secureRandom);
return keyGenerator.generateKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
private byte[] getRawKey(byte[] key) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", "Crypto");
secureRandom.setSeed(key);
keyGenerator.init(128, secureRandom); // 192 and 256 bits may not be available
SecretKey secretKey = keyGenerator.generateKey();
byte[] rawKey = secretKey.getEncoded();
return rawKey;
}
/** The method that encrypts the string.
#param toEncrypt The string to be encrypted.
#return The encrypted string in bytes. */
//****************************************
private byte[] encrypt(byte[] toEncrypt) {
byte[] encryptedByte = new String().getBytes();
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(getRawKey(Utils.generateUID().getBytes()), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
encryptedByte = cipher.doFinal(toEncrypt);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return encryptedByte;
}
//**************************************
/** The method that decrypts the string.
#param encryptedByte The string to be encrypted.
#return The decrypted string in bytes. */
//****************************************
private byte[] decrypt(byte[] encryptedByte) {
byte[] decryptedByte = new String().getBytes();
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(getRawKey(Utils.generateUID().getBytes()), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
decryptedByte = cipher.doFinal(encryptedByte);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return decryptedByte;
}
}
I'm able to encrypt the Text.
I'm using SharedPreferences to store the encrypted text and getting the sharedprefs to decrypt the text and give it to a TextView. But in the getPassword() I'm getting the SharedPreference value and trying to decrypt if there is any value in the SharedPrefs. I'm getting the SharedPrefs into a string (password) and trying to decrypt it, but I'm unable to! I'm getting an empty String!
CBC mode needs an initialization vector (IV) in order to operate. The IV is there to randomize the ciphertext and prevent an attacker from determining whether previous plaintexts had the same prefix as the current one.
Since you're not generating any IV, it will be generated for you. A wrong IV only affects the first block (first 16 bytes for AES). If your plaintext is shorter than a block, then this will lead to completely different decryption and then the padding cannot be removed with a probability of roughly 255/256.
The IV is not supposed to be secret. It is common to prepend it to the ciphertext and slice it off before decryption.
public byte[] encrypt(byte[] toEncrypt) throws Exception {
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(getRawKey(Utils.generateUID().getBytes()), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] iv = cipher.getIV();
byte[] ct = cipher.doFinal(toEncrypt);
byte[] result = new byte[ct.length + iv.length];
System.arraycopy(iv, 0, result, 0, iv.length);
System.arraycopy(ct, 0, result, iv.length, ct.length);
return result;
} catch(...) {...}
return new byte[0];
}
public byte[] decrypt(byte[] encryptedByte) throws Exception {
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(getRawKey(Utils.generateUID().getBytes()), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = new byte[cipher.getBlockSize()];
byte[] ct = new byte[encryptedByte.length - cipher.getBlockSize()];
System.arraycopy(encryptedByte, 0, iv, 0, cipher.getBlockSize());
System.arraycopy(encryptedByte, cipher.getBlockSize(), ct, 0, ct.length);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(iv));
return cipher.doFinal(ct);
} catch (...) {...}
return new byte[0];
}
The problem with this might be that the ciphertext is bigger than anticipated (16 bytes additionally for the IV). If you can make sure that an attacker doesn't get any useful information from determining that previous plaintexts had the same prefix, then you could use a static IV. But be aware that this is usually not that great of an idea and should only be done if you really need that space.
private static final byte[] IV = new byte[16];
...
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(IV));
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(IV));

Encrypt and Decrypt a String with RSA

I am a new bee to Java Security and Crypto. Below code does not return me the correct decryption.
Also please let me know any recommendation for using an algorithm to make a strong key.
Below code has two methods one is for encryption a String and the other is for decryption.
public class TestSecurityDiscussions {
public static byte[] encryptData(KeyPair keys){
String rawData = "Hi how are you>?";
Cipher cipher = Cipher.getInstance("RSA");
try {
cipher.init(Cipher.ENCRYPT_MODE, keys.getPublic());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] encrypted = cipher.doFinal(rawData.getBytes());
return encrypted;
}
public static String decryptData(byte[] encrypted,KeyPair keys) {
Cipher cipher = Cipher.getInstance("RSA");
try {
cipher.init(Cipher.DECRYPT_MODE, keys.getPrivate());
} catch (Exception e) {
e.printStackTrace();
}
byte[] deycrypted = cipher.doFinal(encrypted);
return deycrypted.toString();
}
public static void main(String[] args) {
KeyPair keys = KeyPairGenerator.getInstance("RSA").generateKeyPair();
byte[] keydata = encryptData(keys);
System.out.println("======>"+decryptData(keydata,keys));
}
}
I think your problem is this line:
return decrypted.toString();
Byte Strings will give a memory location via the toString(). You should do this:
return new String(decrypted);

Categories

Resources