AES在android上解密

AES在android上解密,android,aes,compatibility,encryption,fileinputstream,Android,Aes,Compatibility,Encryption,Fileinputstream,我在android和pc上使用相同的解密代码和相同的文件,但在android上不起作用。 当我使用正常工作的简单字符串解密函数时: 字符串解密示例(在两个系统上工作): PC代码: String key = "12345678"; Crypto encrypter = new Crypto(key); OutputStream output = new OutputStream() { private St

我在android和pc上使用相同的解密代码和相同的文件,但在android上不起作用。 当我使用正常工作的简单字符串解密函数时:

字符串解密示例(在两个系统上工作):

PC代码:

        String key = "12345678";
        Crypto encrypter = new Crypto(key);

        OutputStream output = new OutputStream()
        {
            private StringBuilder string = new StringBuilder();
            @Override
            public void write(int b) throws IOException {
                this.string.append((char) b );
            }
            public String toString(){
                return this.string.toString();
            }
        };

        encrypter.decrypt(new FileInputStream("C:/temp/asset.xml.secure"), output);
        System.out.println(output.toString());
Android代码:

        String key = "12345678";
        Crypto encrypter = new Crypto(key); 
        OutputStream output = new OutputStream()
        {
            private StringBuilder string = new StringBuilder();
            @Override
            public void write(int b) throws IOException {
                this.string.append((char) b );
            }
            public String toString(){
                return this.string.toString();
            }
        };
        InputStream input = this.getResources().getAssets().open("asset.xml.secure");
        encrypter.decrypt(input , output);
加密类:

        public class Crypto {
Cipher ecipher;
Cipher dcipher;

/**
* Input a string that will be md5 hashed to create the key.
* @return void, cipher initialized
*/

public Crypto(){
    try{
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        this.setupCrypto(kgen.generateKey());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public Crypto(String key){
    SecretKeySpec skey = new SecretKeySpec(getMD5(key), "AES");
    this.setupCrypto(skey);
}

private void setupCrypto(SecretKey key){
    // Create an 8-byte initialization vector
    byte[] iv = new byte[]
    {
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
    };

    AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
    try
    {
        ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        // CBC requires an initialization vector
        ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

// Buffer used to transport the bytes from one stream to another
byte[] buf = new byte[1024];

public void encrypt(InputStream in, OutputStream out){
    try {
        // Bytes written to out will be encrypted
        out = new CipherOutputStream(out, ecipher);

        // Read in the cleartext bytes and write to out to encrypt
        int numRead = 0;
        while ((numRead = in.read(buf)) >= 0){
            out.write(buf, 0, numRead);
        }
        out.close();
    }
    catch (java.io.IOException e){
        e.printStackTrace();
    }
}

/**
* Input is a string to encrypt.
* @return a Hex string of the byte array
*/
public String encrypt(String plaintext){
    try{
        byte[] ciphertext = ecipher.doFinal(plaintext.getBytes("UTF-8"));
        return this.byteToHex(ciphertext);
    } catch (Exception e){
         e.printStackTrace();
        return null;
    }

}

public void decrypt(InputStream in, OutputStream out){
    try {
        // Bytes read from in will be decrypted
        in = new CipherInputStream(in, dcipher);

        // Read in the decrypted bytes and write the cleartext to out
        int numRead = 0;
        while ((numRead = in.read(buf)) >= 0) {
            out.write(buf, 0, numRead);
        }
        out.close();
    } catch (java.io.IOException e) {
         e.printStackTrace();
    }
}

/**
* Input encrypted String represented in HEX
* @return a string decrypted in plain text
*/
public String decrypt(String hexCipherText){
    try{
        String plaintext = new String(dcipher.doFinal(this.hexToByte(hexCipherText)), "UTF-8");
        return  plaintext;
    } catch (Exception e){
        e.printStackTrace();
        return null;
    }
}

public String decrypt(byte[] ciphertext){
    try{
        String plaintext = new String(dcipher.doFinal(ciphertext), "UTF-8");
        return  plaintext;
    } catch (Exception e){
        e.printStackTrace();
        return null;
    }
}

private static byte[] getMD5(String input){
    try{
        byte[] bytesOfMessage = input.getBytes("UTF-8");
        MessageDigest md = MessageDigest.getInstance("MD5");
        return md.digest(bytesOfMessage);
    }  catch (Exception e){
         return null;
    }
}

static final String HEXES = "0123456789ABCDEF";

public static String byteToHex( byte [] raw ) {
    if ( raw == null ) {
      return null;
    }
    final StringBuilder hex = new StringBuilder( 2 * raw.length );
    for ( final byte b : raw ) {
      hex.append(HEXES.charAt((b & 0xF0) >> 4))
         .append(HEXES.charAt((b & 0x0F)));
    }
    return hex.toString();
}

public static byte[] hexToByte( String hexString){
    int len = hexString.length();
    byte[] ba = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        ba[i/2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i+1), 16));
    }
    return ba;
}
公共类加密{
密码译码器;
密码机;
/**
*输入一个字符串,该字符串将被md5哈希以创建密钥。
*@return void,密码已初始化
*/
公开密码{
试一试{
KeyGenerator kgen=KeyGenerator.getInstance(“AES”);
kgen.init(128);
this.setupCrypto(kgen.generateKey());
}捕获(例外e){
e、 printStackTrace();
}
}
公开密码(字符串密钥){
SecretKeySpec skey=新的SecretKeySpec(getMD5(key),“AES”);
这就是加密设置(skey);
}
私有void setupCrypto(SecretKey密钥){
//创建一个8字节的初始化向量
字节[]iv=新字节[]
{
0x00、0x01、0x02、0x03、0x04、0x05、0x06、0x07、0x08、0x09、0x0a、0x0b、0x0c、0x0d、0x0e、0x0f
};
AlgorithmParameterSpec paramSpec=新的IvParameterSpec(iv);
尝试
{
ecipher=Cipher.getInstance(“AES/CBC/PKCS5Padding”);
dcipher=Cipher.getInstance(“AES/CBC/PKCS5Padding”);
//CBC需要一个初始化向量
ecipher.init(Cipher.ENCRYPT_模式,密钥,paramSpec);
dcipher.init(Cipher.DECRYPT_模式,key,paramSpec);
}
捕获(例外e)
{
e、 printStackTrace();
}
}
//用于将字节从一个流传输到另一个流的缓冲区
字节[]buf=新字节[1024];
公共void加密(输入流输入,输出流输出){
试一试{
//写入输出的字节将被加密
out=新密码输出流(out,ecipher);
//读入明文字节并写入以加密
int numRead=0;
而((numRead=in.read(buf))>=0){
out.write(buf,0,numRead);
}
out.close();
}
捕获(java.io.ioe异常){
e、 printStackTrace();
}
}
/**
*输入是要加密的字符串。
*@返回字节数组的十六进制字符串
*/
公共字符串加密(字符串明文){
试一试{
byte[]ciphertext=ecipher.doFinal(明文.getBytes(“UTF-8”);
返回此.byteToHex(密文);
}捕获(例外e){
e、 printStackTrace();
返回null;
}
}
公共无效解密(输入流输入,输出流输出){
试一试{
//从中读取的字节将被解密
in=新的CipherInputStream(in,dcipher);
//读入解密的字节并将明文写入输出
int numRead=0;
而((numRead=in.read(buf))>=0){
out.write(buf,0,numRead);
}
out.close();
}捕获(java.io.ioe异常){
e、 printStackTrace();
}
}
/**
*输入用十六进制表示的加密字符串
*@返回以纯文本解密的字符串
*/
公共字符串解密(字符串六进制密文){
试一试{
字符串纯文本=新字符串(dcipher.doFinal(this.hexToByte(hexCipherText)),“UTF-8”);
返回纯文本;
}捕获(例外e){
e、 printStackTrace();
返回null;
}
}
公共字符串解密(字节[]密文){
试一试{
字符串明文=新字符串(dcipher.doFinal(密文),“UTF-8”);
返回纯文本;
}捕获(例外e){
e、 printStackTrace();
返回null;
}
}
私有静态字节[]getMD5(字符串输入){
试一试{
byte[]bytesOfMessage=input.getBytes(“UTF-8”);
MessageDigest md=MessageDigest.getInstance(“MD5”);
返回md.digest(bytesOfMessage);
}捕获(例外e){
返回null;
}
}
静态最终字符串HEXES=“0123456789ABCDEF”;
公共静态字符串byteToHex(字节[]原始){
如果(原始==null){
返回null;
}
最终StringBuilder十六进制=新StringBuilder(2*原始长度);
for(最终字节b:raw){
十六进制追加(十六进制字符((b&0xF0)>>4))
.append(十六进制字符((b&0x0F));
}
返回hex.toString();
}
公共静态字节[]hexToByte(字符串hextString){
int len=hexString.length();
字节[]ba=新字节[len/2];
对于(int i=0;i        public class Crypto {
Cipher ecipher;
Cipher dcipher;

/**
* Input a string that will be md5 hashed to create the key.
* @return void, cipher initialized
*/

public Crypto(){
    try{
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        this.setupCrypto(kgen.generateKey());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public Crypto(String key){
    SecretKeySpec skey = new SecretKeySpec(getMD5(key), "AES");
    this.setupCrypto(skey);
}

private void setupCrypto(SecretKey key){
    // Create an 8-byte initialization vector
    byte[] iv = new byte[]
    {
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
    };

    AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
    try
    {
        ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        // CBC requires an initialization vector
        ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

// Buffer used to transport the bytes from one stream to another
byte[] buf = new byte[1024];

public void encrypt(InputStream in, OutputStream out){
    try {
        // Bytes written to out will be encrypted
        out = new CipherOutputStream(out, ecipher);

        // Read in the cleartext bytes and write to out to encrypt
        int numRead = 0;
        while ((numRead = in.read(buf)) >= 0){
            out.write(buf, 0, numRead);
        }
        out.close();
    }
    catch (java.io.IOException e){
        e.printStackTrace();
    }
}

/**
* Input is a string to encrypt.
* @return a Hex string of the byte array
*/
public String encrypt(String plaintext){
    try{
        byte[] ciphertext = ecipher.doFinal(plaintext.getBytes("UTF-8"));
        return this.byteToHex(ciphertext);
    } catch (Exception e){
         e.printStackTrace();
        return null;
    }

}

public void decrypt(InputStream in, OutputStream out){
    try {
        // Bytes read from in will be decrypted
        in = new CipherInputStream(in, dcipher);

        // Read in the decrypted bytes and write the cleartext to out
        int numRead = 0;
        while ((numRead = in.read(buf)) >= 0) {
            out.write(buf, 0, numRead);
        }
        out.close();
    } catch (java.io.IOException e) {
         e.printStackTrace();
    }
}

/**
* Input encrypted String represented in HEX
* @return a string decrypted in plain text
*/
public String decrypt(String hexCipherText){
    try{
        String plaintext = new String(dcipher.doFinal(this.hexToByte(hexCipherText)), "UTF-8");
        return  plaintext;
    } catch (Exception e){
        e.printStackTrace();
        return null;
    }
}

public String decrypt(byte[] ciphertext){
    try{
        String plaintext = new String(dcipher.doFinal(ciphertext), "UTF-8");
        return  plaintext;
    } catch (Exception e){
        e.printStackTrace();
        return null;
    }
}

private static byte[] getMD5(String input){
    try{
        byte[] bytesOfMessage = input.getBytes("UTF-8");
        MessageDigest md = MessageDigest.getInstance("MD5");
        return md.digest(bytesOfMessage);
    }  catch (Exception e){
         return null;
    }
}

static final String HEXES = "0123456789ABCDEF";

public static String byteToHex( byte [] raw ) {
    if ( raw == null ) {
      return null;
    }
    final StringBuilder hex = new StringBuilder( 2 * raw.length );
    for ( final byte b : raw ) {
      hex.append(HEXES.charAt((b & 0xF0) >> 4))
         .append(HEXES.charAt((b & 0x0F)));
    }
    return hex.toString();
}

public static byte[] hexToByte( String hexString){
    int len = hexString.length();
    byte[] ba = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        ba[i/2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i+1), 16));
    }
    return ba;
}