Java 解密在android上加密的桌面数据

Java 解密在android上加密的桌面数据,java,android,encryption,aes,desktop,Java,Android,Encryption,Aes,Desktop,我有一个应用程序,它对一些文本字符串进行加密,然后将它们写入一个文件。 应用程序的桌面版本正在读取文件并解密数据。问题是,每当我在桌面版本上解密时,我都会得到一个“javax.crypto.BadPaddingException:给定的最后一个块没有正确填充” 应用程序和桌面都使用相同的代码: import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; impo

我有一个应用程序,它对一些文本字符串进行加密,然后将它们写入一个文件。 应用程序的桌面版本正在读取文件并解密数据。问题是,每当我在桌面版本上解密时,我都会得到一个“javax.crypto.BadPaddingException:给定的最后一个块没有正确填充”

应用程序和桌面都使用相同的代码:

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class SSL {

    private final static String HEX = "0123456789ABCDEF";

    public static String encrypt(Session current, String cleartext) throws Exception {
        byte[] rawKey = getRawKey(current.getCurrentSession().getBytes());
        byte[] result = encrypt(rawKey, cleartext.getBytes());
        return toHex(result);
    }

    public static String decrypt(Session current, String encrypted) throws Exception {
        byte[] rawKey = getRawKey(current.getCurrentSession().getBytes());
        byte[] enc = toByte(encrypted);     
        byte[] result = decrypt(rawKey, enc);
        return new String(result);
    }

    private static byte[] getRawKey(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
        kgen.init(128, sr); // 192 and 256 bits may not be available
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        return raw;
    }


    private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }

    private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }

    public static String toHex(String txt) {
        return toHex(txt.getBytes());
    }
    public static String fromHex(String hex) {
        return new String(toByte(hex));
    }

    public static byte[] toByte(String hexString) {
        int len = hexString.length()/2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++)
            result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
        return result;
    }

    public static String toHex(byte[] buf) {
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2*buf.length);
        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }

    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
    }
}
导入java.security.SecureRandom;
导入javax.crypto.Cipher;
导入javax.crypto.KeyGenerator;
导入javax.crypto.SecretKey;
导入javax.crypto.spec.SecretKeySpec;
公共类SSL{
私有最终静态字符串HEX=“0123456789ABCDEF”;
公共静态字符串加密(当前会话,字符串明文)引发异常{
byte[]rawKey=getRawKey(current.getCurrentSession().getBytes());
byte[]result=encrypt(rawKey,cleartext.getBytes());
返回到hex(结果);
}
公共静态字符串解密(会话当前,字符串加密)引发异常{
byte[]rawKey=getRawKey(current.getCurrentSession().getBytes());
字节[]enc=toByte(加密);
字节[]结果=解密(rawKey,enc);
返回新字符串(结果);
}
私有静态字节[]getRawKey(字节[]种子)引发异常{
KeyGenerator kgen=KeyGenerator.getInstance(“AES”);
SecureRandom sr=SecureRandom.getInstance(“SHA1PRNG”);
高级种子(种子);
kgen.init(128,sr);//192和256位可能不可用
SecretKey skey=kgen.generateKey();
字节[]原始=skey.getEncoded();
返回原材料;
}
私有静态字节[]加密(字节[]原始,字节[]清除)引发异常{
SecretKeySpec skeySpec=新SecretKeySpec(原始,“AES”);
Cipher Cipher=Cipher.getInstance(“AES”);
cipher.init(cipher.ENCRYPT_模式,skeySpec);
字节[]加密=cipher.doFinal(清除);
返回加密;
}
私有静态字节[]解密(字节[]原始,字节[]加密)引发异常{
SecretKeySpec skeySpec=新SecretKeySpec(原始,“AES”);
Cipher Cipher=Cipher.getInstance(“AES”);
cipher.init(cipher.DECRYPT_模式,skeySpec);
字节[]解密=cipher.doFinal(加密);
返回解密;
}
公共静态字符串toHex(字符串txt){
返回到hex(txt.getBytes());
}
公共静态字符串fromHex(字符串十六进制){
返回新字符串(toByte(hex));
}
公共静态字节[]toByte(字符串hexString){
int len=hexString.length()/2;
字节[]结果=新字节[len];
对于(int i=0;i>4)和0x0f)).append(十六进制字符(b和0x0f));
}
}
为什么我不能解密桌面版本上的数据?Android SDK和java 1.7中的加密实现是否不同


注意:如果我在android上解密加密的android数据,它会工作。如果我在桌面上加密和解密,它也可以工作。问题似乎介于这两者之间。

您的代码中至少有两个问题会影响其在不同平台上的功能:

  • 调用
    getBytes()
    新字符串(…)
    时,必须指定字符集。否则,如果您的平台具有不同的默认字符集,结果将不同

  • 您必须完全指定加密算法,例如将
    “AES”
    替换为
    “AES/CBC/PKCS5Padding”
    ,以避免提供商之间的差异


  • 我终于找到了整个解决办法

    有一些主要的问题,我想在这里解释一下,以便更多的用户能够找到答案。首先,邓肯指出的两件事需要修正

    在解决了这些问题之后,我仍然有同样的问题,并且发现使用伪随机数来创建原始密钥在不同的平台/操作系统中是不同的。如果您希望具有跨平台独立性,请不要将SHA1PRNG用作关键算法。相反,使用PBEWITHSA256和256BITAES CBC BC。我使用的是BouncyCastle的实现,完整的加密代码见下文

    import java.io.UnsupportedEncodingException;
    import java.security.Security;
    import java.security.spec.KeySpec;
    import java.util.Random;
    
    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;
    
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    
    public class SSL {
    
        private final static String HEX = "0123456789ABCDEF";
        private final static String ENC = "US-ASCII";
        private final static int ITERATION = 1337;
    
        private static final String RANDOM_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC";
        private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
        private static final String SECRET_KEY_ALGORITHM = "AES";
    
        private static IvParameterSpec ips;
    
        public static void init(byte[] iv) {
            if(iv == null) {
                iv = new byte[16];
    
                Random random = new Random();
                random.nextBytes(iv);
            }
    
            ips = new IvParameterSpec(iv);
    
            Security.addProvider(new BouncyCastleProvider());
        }
    
        public static byte[] getCertificate() {
            return ips.getIV();
        }
    
        public static String encrypt(Session current, String cleartext) throws Exception {
            byte[] rawKey = getRawKey(current.getCurrentSession().toCharArray());
            byte[] result = encrypt(rawKey, cleartext.getBytes(ENC));
            return toHex(result);
        }
    
        public static String decrypt(Session current, String encrypted) throws Exception {
            byte[] rawKey = getRawKey(current.getCurrentSession().toCharArray());
            byte[] enc = toByte(encrypted);     
            byte[] result = decrypt(rawKey, enc);
            return new String(result, ENC);
        }
    
        private static byte[] getRawKey(char[] seed) throws Exception {
            KeySpec keySpec = new PBEKeySpec(seed, ips.getIV(), ITERATION);
    
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(RANDOM_ALGORITHM);
            byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
            SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
    
            return secretKey.getEncoded();
        }
    
    
        private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
            SecretKeySpec skeySpec = new SecretKeySpec(raw, SECRET_KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ips);
            byte[] encrypted = cipher.doFinal(clear);
            return encrypted;
        }
    
        private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
            SecretKeySpec skeySpec = new SecretKeySpec(raw, SECRET_KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ips);
            byte[] decrypted = cipher.doFinal(encrypted);
            return decrypted;
        }
    
        public static String toHex(String txt) throws UnsupportedEncodingException {
            return toHex(txt.getBytes(ENC));
        }
        public static String fromHex(String hex) throws UnsupportedEncodingException {
            return new String(toByte(hex), ENC);
        }
    
        public static byte[] toByte(String hexString) {
            int len = hexString.length()/2;
            byte[] result = new byte[len];
            for (int i = 0; i < len; i++)
                result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
            return result;
        }
    
        public static String toHex(byte[] buf) {
            if (buf == null)
                return "";
            StringBuffer result = new StringBuffer(2*buf.length);
            for (int i = 0; i < buf.length; i++) {
                appendHex(result, buf[i]);
            }
            return result.toString();
        }
    
        private static void appendHex(StringBuffer sb, byte b) {
            sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
        }
    }
    
    import java.io.UnsupportedEncodingException;
    导入java.security.security;
    导入java.security.spec.KeySpec;
    导入java.util.Random;
    导入javax.crypto.Cipher;
    导入javax.crypto.SecretKey;
    导入javax.crypto.SecretKeyFactory;
    导入javax.crypto.spec.IvParameterSpec;
    导入javax.crypto.spec.PBEKeySpec;
    导入javax.crypto.spec.SecretKeySpec;
    导入org.bouncycastle.jce.provider.BouncyCastleProvider;
    公共类SSL{
    私有最终静态字符串HEX=“0123456789ABCDEF”;
    专用最终静态字符串ENC=“US-ASCII”;
    私有最终静态int迭代=1337;
    私有静态最终字符串随机_算法=“pbewithsha256和256biates CBC BC”;
    私有静态最终字符串密码\u算法=“AES/CBC/PKCS5Padding”;
    私有静态最终字符串密钥算法=“AES”;
    专用静态IvParameterSpec ips;
    公共静态void init(字节[]iv){
    如果(iv==null){
    iv=新字节[16];
    随机=新随机();
    随机。下一字节(iv);
    }
    ips=新的IvParameterSpec(iv);
    addProvider(新的BouncyCastleProvider());
    }
    公共静态字节[]getCertificate(){
    返回ips.getIV();
    }
    公共静态字符串加密(当前会话,字符串明文)引发异常{
    字节[]rawKey=getRawKey(cur