文件写入和读取,加密解密,xml例

using UnityEngine;
using System.Collections;
using System.IO;
using System;
using System.Text;
using System.Security.Cryptography;
using System.Xml.Serialization;
using System.Xml;


//文件写入读取
public class FileOperation  {


    private FileOperation() { }
    private static FileOperation instance;
    public static FileOperation Instance
    {
        get
        {
            if (instance == null)
                instance = new FileOperation();
            return instance;
        }
    }


    //写文件 
    public static bool WriteFile_(string filePath, string writeSomething)
    {
        string path = Application.dataPath + "//" + filePath;
        FileInfo file = new FileInfo(path);
        StreamWriter stream;


        if (!file.Exists)
            stream = file.CreateText();  //文件名不存在则创建
        else
            stream = file.AppendText();   //文件名存在则追加
        stream.WriteLine(writeSomething);


        stream.Close();
        stream.Dispose();


        return true;
    }


    //读文件 
    public static string ReadFile_(string filePath)
    {
        string path = Application.dataPath + "//" + filePath;
        FileInfo file = new FileInfo(path);
        string fileData;
        if (file.Exists)
        {
            StreamReader stream = file.OpenText();
            //注意:ReadToEnd 解密会出错 ReadLine不会出错
            fileData = stream.ReadToEnd();   //ReadToEnd全部读取  ReadLine读取第一行  ReadBlock读取指定字符个数
            stream.Close();
            stream.Dispose();


            Debug.Log(fileData);
        }
        else
        {
            Debug.Log("it has not this file");
            return null;
        }


        return fileData;
    }


    //写文件 加密
    public static bool WriteFile_(string filePath,string writeSomething,bool isEncryption)
    {
        string path = Application.dataPath + "//" + filePath;
        FileInfo file = new FileInfo(path);
        StreamWriter stream;
        string fileData;        
        //先对字符串加密
        if (isEncryption)
            fileData = Encrypt(writeSomething);
        else
            fileData = writeSomething;


        if (!file.Exists)
            stream = file.CreateText();  //文件名不存在则创建
        else
            stream = file.AppendText();   //文件名存在则追加
        stream.WriteLine(fileData);


        stream.Close();
        stream.Dispose();


        return true;
    }


    //读文件 解密
    public static string ReadFile_(string filePath,bool isEncryption)
    {
        string path = Application.dataPath + "//" + filePath;
        FileInfo file = new FileInfo(path);
        string fileData;
        if(file.Exists)
        {
            StreamReader stream = file.OpenText();
            //注意:ReadToEnd 解密会出错 ReadLine不会出错
            fileData=stream.ReadLine();   //ReadToEnd全部读取  ReadLine读取第一行  ReadBlock读取指定字符个数
            stream.Close();
            //stream.Dispose();           
            if (isEncryption)
               fileData=Decrypt(fileData);


            Debug.Log(fileData);                       
        }
        else
        {
            Debug.Log("it has not this file");
            return null;
        }


        return fileData;
    }


    /// 加密方法  
    /// 描述: 加密和解密采用相同的key,具体值自己填,但是必须为32位  
    private static string Encrypt(string toE)
    {
        byte[] keyArray = Encoding.UTF8.GetBytes("12348578902223367877723456789012");
        RijndaelManaged rDel = new RijndaelManaged();
        rDel.Key = keyArray;
        rDel.Mode = CipherMode.ECB;
        rDel.Padding = PaddingMode.PKCS7;
        ICryptoTransform cTransform = rDel.CreateEncryptor();
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toE);
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);


        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }


    /// 解密方法  
    /// 描述: 加密和解密采用相同的key,具体值自己填,但是必须为32位  
    private static string Decrypt(string toD)
    {
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12348578902223367877723456789012");
        RijndaelManaged rDel = new RijndaelManaged();
        rDel.Key = keyArray;
        rDel.Mode = CipherMode.ECB;
        rDel.Padding = PaddingMode.PKCS7;
        ICryptoTransform cTransform = rDel.CreateDecryptor();
        byte[] toEncryptArray = Convert.FromBase64String(toD);
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);


        return UTF8Encoding.UTF8.GetString(resultArray);
    }






    //XML存储和读取


    public static object XmlWriteAndRead(string filePath,object obj)
    {
        if(obj== null)
        {
            Debug.LogError("type is null");
            return null;
        }


        string path = Application.dataPath + "//" + filePath;
        //转换数据类型
        string s = SerializeObject(obj,obj.GetType());


        //创建XML文件且写入数据
        WriteFile_(filePath, s);


        //读取数据
        try
        {
            string xmlData = ReadFile_(filePath);
            return DeserializeObject(xmlData,obj.GetType());
        }
        catch
        {
            Debug.LogWarning("系统读取XML出现错误,请检查");
        }
        return null;
    }


    //数据对象转换成XML字符串
    private static string SerializeObject(object obj, Type type)
    {
        string XmlizedString = null;
        MemoryStream memoryStream = new MemoryStream();
        XmlSerializer xs = new XmlSerializer(type);
        XmlTextWriter xmlTextWriter=new XmlTextWriter(memoryStream,Encoding.UTF8);
        xs.Serialize(xmlTextWriter,obj);
        memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
        XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
        return XmlizedString;
    }


    /// xml字符串转换数据对象  
    private static object DeserializeObject(string pXmlizedString, Type ty)
    {
        XmlSerializer xs = new XmlSerializer(ty);
        MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
        return xs.Deserialize(memoryStream);
    }
    //UTF8字节数组转字符串  
    private static string UTF8ByteArrayToString(byte[] characters)
    {
        UTF8Encoding encoding = new UTF8Encoding();
        string constructedString = encoding.GetString(characters);
        return (constructedString);
    }


    //字符串转UTF8字节数组  
    private static byte[] StringToUTF8ByteArray(String pXmlString)
    {
        UTF8Encoding encoding = new UTF8Encoding();
        byte[] byteArray = encoding.GetBytes(pXmlString);
        return byteArray;
    }
}
xml加密XML Encryption)是w3c加密xml的标准。这个加密过程包括加密xml文档的元素及其子元素,通过加密xml的初始内容将被替换,但其xml格式仍然被完好的保留。 介绍 我们有3个加密xml的方法 1、仅仅使用对称加密的方法加密xml 这种加密方法只使用一个密钥,也就是说无论是加密xml还是解密xml都使用一个相同的密钥。因为这个密钥不会在被加密xml中保存,所以我们需要在加密和解密的过程中加载这个密钥并保护它不被窃取。 2、使用对称加密和非对称加密相结合的方法来加密xml 这种方法需要一个用于加密数据的对称密钥和一个用于保护这个对称密钥的非对称密钥。被加密的对称密钥和被加密的数据一起保存在xml文档中。当用私有非对称密钥解密密钥的时候要用公开非对称密钥对密钥进行加密。 本文就将使用这种方法。想学到其他更多的方法请参看MSDN等到更多的信息。 (译者注:非对称加密算法需要两个密钥:公开密钥(publickey)和私有密钥(privatekey)。公开密钥与私有密钥是一对,如果用公开密钥对数据进行加密,只有用对应的私有密钥才能解密;如果用私有密钥对数据进行加密,那么只有用对应的公开密钥才能解密。因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。) 3、使用X.509加密xml,这种方法是用X.509作为非对称密钥,它由诸如VeriSign之类的第三方提供。 方法 不管xml加密是如何完成的,保存加密数据总是用两种方法之一。 1、加密后所有的元素都被命名为 2、加密后只有数据被替换,而元素名称仍然是可读的,不会发生变化。
根据提供的引用内容,我了解到Java可以用于加密/解密和密码保护Excel文件。而EasyExcel是一个基于Java的开源框架,可以用于读取写入和操作Excel文件。因此,可以使用EasyExcel来加密/解密Excel文件。 以下是使用EasyExcel加密/解密Excel文件的步骤: 1. 导入EasyExcel依赖 ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.10</version> </dependency> ``` 2. 加密Excel文件 ```java // 加密密码 String password = "123456"; // 加载Excel文件 String fileName = "test.xlsx"; ExcelReader excelReader = new ExcelReader(new FileInputStream(fileName), null, new CustomSheetReadListener()); // 加密Excel文件 ExcelWriter excelWriter = EasyExcel.write(fileName).password(password).build(); List<List<String>> data = excelReader.read(0);excelWriter.write(data); excelWriter.finish(); ``` 3. 解密Excel文件 ```java // 解密密码 String password = "123456"; // 加载Excel文件 String fileName = "test.xlsx"; ExcelReader excelReader = new ExcelReader(new FileInputStream(fileName), null, new CustomSheetReadListener()); // 解密Excel文件 ExcelWriter excelWriter = EasyExcel.write(fileName).password(password).build(); List<List<String>> data = excelReader.read(0); excelWriter.write(data); excelWriter.finish(); ``` 需要注意的是,EasyExcel只能加密/解密整个Excel文件,而不能对单个单元格进行加密/解密。此外,加密后的Excel文件只能在拥有正确密码的情况下进行打开和编辑。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值