加密与解密

原创 2004年07月30日 18:13:00

Imports System.IO
Imports System.Security.Cryptography

'数据加/解密 类
Public Class CryData
    '加密密钥,初始化向量
    Public ReadOnly cryKey As Byte() = {9, 4, 2, 8, 5, 1, 4, 9, 7, 6, 9, 5, 1, 13, 7, 5, 14, 9, 10, 15, 0, 1, 14, 5, 9, 4, 3, 8, 2, 10}
    Public ReadOnly cryIV As Byte() = {7, 1, 8, 8, 2, 8, 7, 1, 4, 5, 6, 3, 5, 6, 7} 


    ' 文件加密
    Public Sub EncryptData(ByVal inName As String, ByVal outName As String, _
                     Optional ByVal rijnKey() As Byte = Nothing, _
                     Optional ByVal rijnIV() As Byte = Nothing)

        If rijnKey Is Nothing Then
            rijnKey = cryKey


        End If
        If rijnIV Is Nothing Then
            rijnIV = cryIV

        End If
        ReDim Preserve rijnKey(31)
        ReDim Preserve rijnIV(15)

        'Create the file streams to handle the input and output files.
        Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read)
        Dim fout As New FileStream(outName, FileMode.OpenOrCreate, FileAccess.ReadWrite)
        fout.SetLength(0)

        'Create variables to help with read and write.
        Dim bin(1024) As Byte 'This is intermediate storage for the encryption.
        Dim rdlen As Long = 0 'This is the total number of bytes written.
        Dim totlen As Long = fin.Length 'Total length of the input file.
        Dim len As Integer 'This is the number of bytes to be written at a time.
        'Creates the default implementation, which is RijndaelManaged.
        Dim rijn As SymmetricAlgorithm = SymmetricAlgorithm.Create()
        Dim encStream As New CryptoStream(fout, _
                                         rijn.CreateEncryptor(rijnKey, rijnIV), CryptoStreamMode.Write)

        ' Console.WriteLine("Encrypting...")

        'Read from the input file, then encrypt and write to the output file.
        While rdlen < totlen
            len = fin.Read(bin, 0, 1024)
            encStream.Write(bin, 0, len)
            rdlen = Convert.ToInt32(rdlen + len)
            '  Console.WriteLine("{0} bytes processed", rdlen)
        End While


        'fout.Seek(0, SeekOrigin.Begin)
        'Dim returnValue As String
        'returnValue = New StreamReader(fout).ReadToEnd()

        encStream.Close()
        fout.Close()
        fin.Close()

    End Sub

    '文件解密

    Public Sub DecryptData(ByVal inName As String, ByVal outName As String, _
                     Optional ByVal rijnKey() As Byte = Nothing, _
                     Optional ByVal rijnIV() As Byte = Nothing)

        If rijnKey Is Nothing Then
            rijnKey = cryKey

        End If

        If rijnIV Is Nothing Then
            rijnIV = cryIV

        End If

        ReDim Preserve rijnKey(31)
        ReDim Preserve rijnIV(15)

        'Create the file streams to handle the input and output files.
        Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read)
        Dim fout As New FileStream(outName, FileMode.OpenOrCreate, _
        FileAccess.ReadWrite)
        fout.SetLength(0)

        'Create variables to help with read and write.
        Dim bin(1024) As Byte 'This is intermediate storage for the encryption.
        Dim rdlen As Long = 0 'This is the total number of bytes written.
        Dim totlen As Long = fin.Length 'Total length of the input file.
        Dim len As Integer 'This is the number of bytes to be written at a time.
        'Creates the default implementation, which is RijndaelManaged.
        Dim rijn As SymmetricAlgorithm = SymmetricAlgorithm.Create()
        Dim encStream As New CryptoStream(fout, _
                                          rijn.CreateDecryptor(rijnKey, rijnIV), CryptoStreamMode.Write)

        '  Console.WriteLine("Encrypting...")

        'Read from the input file, then encrypt and write to the output file.
        While rdlen < totlen
            len = fin.Read(bin, 0, 1024)
            encStream.Write(bin, 0, len)
            rdlen = Convert.ToInt32(rdlen + len)
            ' Console.WriteLine("{0} bytes processed", rdlen)

        End While

        encStream.Close()
        fout.Close()
        fin.Close()

    End Sub
    '文件解密

    Public Function DecryptData(ByVal inName As String, _
                        Optional ByVal rijnKey() As Byte = Nothing, _
                        Optional ByVal rijnIV() As Byte = Nothing) As String

        If rijnKey Is Nothing Then
            rijnKey = cryKey

        End If

        If rijnIV Is Nothing Then
            rijnIV = cryIV

        End If

        ReDim Preserve rijnKey(31)
        ReDim Preserve rijnIV(15)

        'Create the file streams to handle the input and output files.
        Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read)
        '  Dim fout As New FileStream(outName, FileMode.OpenOrCreate, _
        ' FileAccess.ReadWrite)
        '存储流,
        Dim outStream As New MemoryStream() '(arrInByte, True)  '(arrInByte, True)


        'Create variables to help with read and write.
        Dim bin(1024) As Byte 'This is intermediate storage for the encryption.
        Dim rdlen As Long = 0 'This is the total number of bytes written.
        Dim totlen As Long = fin.Length 'Total length of the input file.
        Dim len As Integer 'This is the number of bytes to be written at a time.
        'Creates the default implementation, which is RijndaelManaged.
        While rdlen < totlen
            len = fin.Read(bin, 0, 1024)
            outStream.Write(bin, 0, len)
            rdlen = Convert.ToInt32(rdlen + len)
            ' Console.WriteLine("{0} bytes processed", rdlen)

        End While

        outStream.Seek(0, SeekOrigin.Begin)

        Dim rijn As SymmetricAlgorithm = SymmetricAlgorithm.Create()
        Dim encStream As New CryptoStream(outStream, _
                                          rijn.CreateDecryptor(rijnKey, rijnIV), CryptoStreamMode.Read)

        '  Console.WriteLine("Encrypting...")

        'Read from the input file, then encrypt and write to the output file.


        Dim returnValue As String
        returnValue = New StreamReader(encStream, New System.Text.UnicodeEncoding()).ReadToEnd()


        encStream.Close()
        outStream.Close()
        fin.Close()
        Return returnValue

    End Function

 

 

  '加密
    'in:        inText      待加密原始文本
    'in:        rijnKey     32位密钥
    'in:        rijnIV      16位初始化向量

    'out:       return      加密后的文本(为空则加密失败)

    Public Function Crypt(ByVal inText As String, _
                      Optional ByVal rijnKey() As Byte = Nothing, _
                     Optional ByVal rijnIV() As Byte = Nothing) As String



        'Create the file streams to handle the input and output files.
        '  Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read)
        Dim arrInByte As Byte() = (New System.Text.UnicodeEncoding()).GetBytes(inText)

        Dim len As Long = arrInByte.Length

        If (len Mod 32) > 0 Then
            Dim oldlen As Long = len

            len = oldlen + 32 - oldlen Mod 32

            ReDim Preserve arrInByte(len - 1)

        End If

        If rijnKey Is Nothing Then
            rijnKey = cryKey

        End If
        If rijnIV Is Nothing Then
            rijnIV = cryIV

        End If

        ReDim Preserve rijnKey(31)

        ReDim Preserve rijnIV(15)


        Dim outStream As New MemoryStream()   '(arrInByte, True)  '(arrInByte, True)

        Dim rij As SymmetricAlgorithm = SymmetricAlgorithm.Create()

        Dim encStream As New CryptoStream(outStream, _
                                         rij.CreateEncryptor(rijnKey, rijnIV), _
                                         CryptoStreamMode.Write)

        encStream.Write(arrInByte, 0, len)
        outStream.Seek(0, SeekOrigin.Begin)

        Dim returnValue As String
        returnValue = New StreamReader(outStream, New System.Text.UnicodeEncoding()).ReadToEnd()

        encStream.Close()
        outStream.Close()

        Return returnValue

    End Function

    '--------------------------------------------------------------------------------------------------------
    '解密

    'in:        inText      待解密密文
    'in:        rijnKey     32位解密密钥(须跟加密时的相同)
    'in:        rijnIV      16位解密初始化向量(须跟加密时的相同)

    'out:       return      解密后的文本(为空则解密失败)
    '解密 过程:把密文换成字节写到内存流,再跟据rijnKey和rijnIV创建解密流
    '从解密流中读取所有的数据
    '--------------------------------------------------------------------------------------------------------

    Public Function Decrypt(ByVal inText As String, _
                      Optional ByVal rijnKey() As Byte = Nothing, _
                     Optional ByVal rijnIV() As Byte = Nothing) As String



        '密文转换成字节

        Dim arrInByte As Byte() = (New System.Text.UnicodeEncoding()).GetBytes(inText)

        '存储流,
        Dim outStream As New MemoryStream() '(arrInByte, True)  '(arrInByte, True)

        Dim len As Long = arrInByte.Length
        If rijnKey Is Nothing Then
            rijnKey = cryKey

        End If

        If rijnIV Is Nothing Then
            rijnIV = cryIV

        End If

        ReDim Preserve rijnKey(31)

        ReDim Preserve rijnIV(15)


        Dim rij As SymmetricAlgorithm = SymmetricAlgorithm.Create()

        outStream.Write(arrInByte, 0, len)

        outStream.Seek(0, SeekOrigin.Begin)

        Dim encStream As New CryptoStream(outStream, _
                                         rij.CreateDecryptor(rijnKey, rijnIV), _
                                         CryptoStreamMode.Read)

        Dim returnValue As String
        returnValue = New StreamReader(encStream, New System.Text.UnicodeEncoding()).ReadToEnd()


        encStream.Close()
        outStream.Close()

        Return returnValue

    End Function
End Class

 

 

 ' 加密
    'http://community.csdn.net/Expert/topic/3199/3199494.xml?temp=.982464
    Public Shared Function EncryptText(ByVal strText As String) As String
        Return Encrypt(strText, "&%#@?./)")
    End Function

    '解密
    Public Shared Function DecryptText(ByVal strText As String) As String
        Return Decrypt(strText, "&%#@?./)")
    End Function

    '加密函数
    Private Shared Function Encrypt(ByVal strText As String, ByVal strEncrKey As String) As String
        Dim byKey() As Byte = {}
        Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
        Try
            'byKey = System.Text.Encoding.UTF8.GetBytes(Left(strEncrKey, 8))
            byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8))
            Dim des As New System.Security.Cryptography.DESCryptoServiceProvider
            Dim inputByteArray() As Byte = System.Text.Encoding.UTF8.GetBytes(strText)
            Dim ms As New MemoryStream
            Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
            cs.Write(inputByteArray, 0, inputByteArray.Length)
            cs.FlushFinalBlock()
            Return Convert.ToBase64String(ms.ToArray())
        Catch ex As Exception
            Return ex.Message
        End Try
    End Function

    '解密函数
    Private Shared Function Decrypt(ByVal strText As String, ByVal sDecrKey As String) As String
        Dim byKey() As Byte = {}
        Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
        Dim inputByteArray(strText.Length) As Byte
        Try
            'byKey = System.Text.Encoding.UTF8.GetBytes(Left(sDecrKey, 8))
            byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8))

            Dim des As New DESCryptoServiceProvider
            inputByteArray = Convert.FromBase64String(strText)
            Dim ms As New MemoryStream
            Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
            cs.Write(inputByteArray, 0, inputByteArray.Length)
            cs.FlushFinalBlock()
            Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
            Return encoding.GetString(ms.ToArray())
        Catch ex As Exception
            Return ex.Message
        End Try
    End Function

 

Java加密和解密

概述: 出于安全考虑,网络的传输中经常对传输数据做加密和编码处理,其中涉及以下几种: 1、md5加密,该加密算法是单向加密,即加密的数据不能再通过解密还原。相关类包含在java.securi...
  • xiadaoceshen
  • xiadaoceshen
  • 2013年01月04日 14:27
  • 28178

Java加密解密全解

1 sha加密: 安全哈希算法(Secure Hash Algorithm)主要适用于数字签名标准(Digital Signature Standard DSS)里面定义的数字签名算法(Digital...
  • sinat_29581293
  • sinat_29581293
  • 2016年08月05日 11:31
  • 15828

加密解密技术基础

http://www.cnblogs.com/jasperhsu/p/5107533.html 网络基础 网络通信的实现方案有2套协议家族:OSI、TCP/IP TCP/...
  • lucky_greenegg
  • lucky_greenegg
  • 2016年12月05日 16:49
  • 3006

C++ 简单的文件加密和解密 实例

一段 文件加密的程序,看完之后,明白了它所谓的文件加密,其实原理相当简单:         即是按字节 或 按位 读取一个要加密的文件中的数据,然后与我们自己输入的密码做一些 算法操作,将...
  • educast
  • educast
  • 2014年08月21日 12:57
  • 3708

DES3加密解密类

DES3 加密 解密 算法
  • QZC78
  • QZC78
  • 2015年07月31日 16:44
  • 1716

SQLServer 数据加密解密:常用的加密解密(一)

都是基本示例,更多参考官方文档: 1. Transact-SQL 函数 2. 数据库密钥 3. 证书 4. 非对称密钥 5. 对称密钥 [sql] view plain copy...
  • zy_strive_2012
  • zy_strive_2012
  • 2016年12月05日 11:01
  • 850

加密解密学习分享

现行秘钥体系,根据加密与解密的秘钥是否相同可以分成对称加密和非对称加密。 加密解密秘钥相同或者虽然不同但是可以从其中一个很容易推导出另外一个的称为对称加密;加密与解密秘钥不同,并且不能从一个推导出另外...
  • qqlinxi
  • qqlinxi
  • 2015年12月12日 12:13
  • 825

.net常用加密解密方法

http://www.cnblogs.com/qinweilong/archive/2010/06/30/1768535.html .net常用加密解密方法 UnicodeEncodin...
  • DJ2008
  • DJ2008
  • 2015年10月23日 09:54
  • 1890

js前台加密传输到后台C#解密

源码下载地址:js前台加密传输到后台c#解密 前提条件: 1、添加3个js,在代码crypto文件夹中 2、添加4个类文件,在代码App_Code\Migrated文件夹中 3、两个加...
  • angle_greensky110
  • angle_greensky110
  • 2015年09月08日 17:52
  • 1811

iOS-各种加密/解密算法

随着互联网的迅速发展,我们的隐私越来越少,随之安全也变得极其重要. 在生活中,我们不仅要保护我们的隐私,在虚拟世界,我们也需要保证隐私的安全. 我们移动端,服务于用户,就有责任保护用户的个人信息安全,...
  • Mazy_ma
  • Mazy_ma
  • 2016年11月02日 13:26
  • 1408
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:加密与解密
举报原因:
原因补充:

(最多只允许输入30个字)