Decrypt AES256 encrypted bytes

后端 未结 2 1746
星月不相逢
星月不相逢 2021-01-03 16:56

I\'ve never worked with encryption before. Actually I know nothing about encryption. I have a file encrypted with openssl tool using params:

openssl a

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-03 17:27

    Here's class I have written to decrypt a string encoded with params above (if I remmeber it correct):

    public class CipherUtils {
        public static byte[] getKey(String password, byte[] salt) {
            try {
                byte[] passwordSalt = EncodingUtils.getAsciiBytes(password);
                passwordSalt = concatenateByteArrays(passwordSalt, salt);
    
                byte[] hash1 = getHashForHash(null, passwordSalt);
                byte[] hash2 = getHashForHash(hash1, passwordSalt);
                byte[] key = concatenateByteArrays(hash1, hash2);
    
                return key;
            } catch (Exception e) {
                return null;
            }
    
        }
    
        public static byte[] getIV(String password, byte[] salt) {
            try {
                byte[] passwordSalt = EncodingUtils.getAsciiBytes(password);
                passwordSalt = concatenateByteArrays(passwordSalt, salt);
                byte[] hash1 = getHashForHash(null, passwordSalt);
                byte[] hash2 = getHashForHash(hash1, passwordSalt);
                byte[] hash3 = getHashForHash(hash2, passwordSalt);
                return hash3;
            } catch (Exception e) {
                return null;
            }
    
        }
    
        private static byte[] getHashForHash(byte[] hash, byte[] passwordSalt) {
            try {
                byte[] hashMaterial = concatenateByteArrays(hash, passwordSalt);
                MessageDigest md = MessageDigest.getInstance("MD5");
                return md.digest(hashMaterial);
            } catch (Exception e) {
                return null;
            }
        }
    
        private static byte[] concatenateByteArrays(byte[] a, byte[] b) {
            if (a == null)
                return b;
            if (b == null)
                return a;
            byte[] result = new byte[a.length + b.length];
            System.arraycopy(a, 0, result, 0, a.length);
            System.arraycopy(b, 0, result, a.length, b.length);
            return result;
        }
    }
    

    Salt is an empty bytearray in this case. It uses apache-commons-compress.jar.

    Here's usage example:

    byte[] key = CipherUtils.getKey(password, null);
    byte[] IV = CipherUtils.getIV(password, null);
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"),
            new IvParameterSpec(IV));
    cis = new CipherInputStream(is, cipher);
    

    Where is is an InputStream of encrypted data.

提交回复
热议问题