C#与android使用DES加密图片文件互通

C#代码如下:

    /// <summary>

    /// 对图片的加密和解密
    /// </summary>
    public class DEncrypt4ImageHelper
    {
        public DEncrypt4ImageHelper() { }
        #region 加密方法 图片加密
        #region 加密方法 图片加密
        /// <summary>
        /// 图片加密
        /// </summary>
        /// <param name="filePath">源文件</param>
        /// <param name="savePath">保存为文件名称</param>
        /// <param name="keyStr">密钥</param>
        public static void EncryptFile(string filePath, string savePath, string keyStr)
        {
            //通过des加密
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            //通过流打开文件
            FileStream fs = File.OpenRead(filePath);
            //获取文件二进制字符
            byte[] inputByteArray = new byte[fs.Length];
            //读流文件
            fs.Read(inputByteArray, 0, (int)fs.Length);
            //关闭流
            fs.Close();
            //获得加密字符串二进制字符
            des.Key = ASCIIEncoding.ASCII.GetBytes(keyStr);
            des.IV = ASCIIEncoding.ASCII.GetBytes(keyStr);   
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            fs = File.OpenWrite(savePath);
            foreach (byte b in ms.ToArray())
            {
                fs.WriteByte(b);
            }
            fs.Close();
            cs.Close();
            ms.Close();
        }
        #endregion

        #region 解密方法  图片解密
        /// <summary>
        /// 图片解密
        /// </summary>
        /// <param name="filePath">源文件</param>
        /// <param name="savePath">保存文件</param>
        /// <param name="keyStr">密钥</param>
        public static void DecryptFile(string filePath, string savePath, string keyStr)
        {
            //通过des解密
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();


            //通过流读取文件
            FileStream fs = File.OpenRead(filePath);
            //获取文件二进制字符
            byte[] inputByteArray = new byte[fs.Length];
            //读取流文件
            fs.Read(inputByteArray, 0, (int)fs.Length);
            //关闭流
            fs.Close();
            //密钥数组
            
            des.Key = ASCIIEncoding.ASCII.GetBytes(keyStr);
            des.IV = ASCIIEncoding.ASCII.GetBytes(keyStr);   
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            fs = File.OpenWrite(savePath);
            foreach (byte b in ms.ToArray())
            {
                fs.WriteByte(b);
            }
            fs.Close();
            cs.Close();
            ms.Close();
        }
        #endregion
        private static void DecryptData(String inName, String outName, byte[] desKey, byte[] desIV)
        {
            FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
            FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
            fout.SetLength(0);
            byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
            long rdlen = 0;              //This is the total number of bytes written.
            long totlen = fin.Length;    //This is the total length of the input file.
            int len;                     //This is the number of bytes to be written at a time.
            DES des = new DESCryptoServiceProvider();
            CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
            //Read from the input file, then encrypt and write to the output file.
            while (rdlen < totlen)
            {
                len = fin.Read(bin, 0, 100);
                encStream.Write(bin, 0, len);
                rdlen = rdlen + len;
            }
            encStream.Close();
            fout.Close();
            fin.Close();
        }

    }

android代码如下:

package com.example.ftptest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.*;
import java.security.spec.InvalidKeySpecException;


import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;


import android.content.Context;
import android.widget.Toast;


public class DESCoder {
private static String encoding = "UTF-8";
// 密钥
private String sKey = "";
public DESCoder(String sKey) {
this.sKey = sKey;
}

/**
* 对称加密字节数组并返回

* @param byteSource
*            需要加密的数据
* @return 经过加密的数据
* @throws Exception
*/
public byte[] symmetricEncrypto(byte[] byteSource) throws Exception {
try {
int mode = Cipher.ENCRYPT_MODE;
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
byte[] keyData = sKey.getBytes();
DESKeySpec keySpec = new DESKeySpec(keyData);
Key key = keyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(mode, key);


byte[] result = cipher.doFinal(byteSource);
return result;
} catch (Exception e) {
throw e;
} finally {
}
}


/**
* 对称解密字节数组并返回

* @param byteSource
*            需要解密的数据
* @return 经过解密的数据
* @throws Exception
*/
public byte[] symmetricDecrypto(byte[] byteSource) throws Exception {
try {
int mode = Cipher.DECRYPT_MODE;
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
byte[] keyData = sKey.getBytes();
DESKeySpec keySpec = new DESKeySpec(keyData);
Key key = keyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(mode, key);
byte[] result = cipher.doFinal(byteSource);
return result;
} catch (Exception e) {
throw e;
} finally {


}
}


/**
* 散列算法

* @param byteSource
*            需要散列计算的数据
* @return 经过散列计算的数据
* @throws Exception
*/
public static byte[] hashMethod(byte[] byteSource) throws Exception {
try {
MessageDigest currentAlgorithm = MessageDigest.getInstance("SHA-1");
currentAlgorithm.reset();
currentAlgorithm.update(byteSource);
return currentAlgorithm.digest();
} catch (Exception e) {
throw e;
}
}


/**
* 对文件srcFile进行加密输出到文件distFile

* @param srcFile
*            明文文件
* @param distFile
*            加密后的文件
* @throws Exception
*/
public void EncryptFile(String srcFile, String distFile) throws Exception {
InputStream is = null;
OutputStream out = null;
CipherInputStream cis = null;
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
DESKeySpec desKeySpec = new DESKeySpec(sKey.getBytes(encoding));
SecretKey key = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(sKey.getBytes(encoding));
// Cipher cipher = Cipher.getInstance("DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
out = new FileOutputStream(distFile);
is = new FileInputStream(srcFile);
cis = new CipherInputStream(is, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = cis.read(buffer)) > 0) {
out.write(buffer, 0, r);
}


} catch (Exception e) {
throw e;
} finally {
cis.close();
is.close();
out.close();
}
}


/**
* 解密文件srcFile到目标文件distFile

* @param srcFile
*            密文文件
* @param distFile
*            解密后的文件
* @throws Exception
*/
public void DecryptFile(String srcFile, String distFile) throws Exception {


InputStream is = null;
OutputStream out = null;
CipherOutputStream cos = null;
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
DESKeySpec desKeySpec = new DESKeySpec(sKey.getBytes(encoding));
SecretKey key = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(sKey.getBytes(encoding));
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] buffer = new byte[1024];
is = new FileInputStream(srcFile);
out = new FileOutputStream(distFile);
cos = new CipherOutputStream(out, cipher);


int r;
while ((r = is.read(buffer)) >= 0) {
cos.write(buffer, 0, r);
}


} catch (Exception e) {
throw e;
} finally {
cos.close();
is.close();
out.close();
}
}
}

全部测试通过

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值