⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 rijndaelmanagedtransform.cls

📁 这是一个在vb下实现的各种加密程序,可以实现一般的文本加密和文件加密,但是很多算法都是已经被人破解过的.
💻 CLS
📖 第 1 页 / 共 3 页
字号:
VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
  Persistable = 0  'NotPersistable
  DataBindingBehavior = 0  'vbNone
  DataSourceBehavior  = 0  'vbNone
  MTSTransactionMode  = 0  'NotAnMTSObject
END
Attribute VB_Name = "RijndaelManagedTransform"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = True
'    CopyRight (c) 2006 Kelly Ethridge
'
'    This file is part of VBCorLib.
'
'    VBCorLib is free software; you can redistribute it and/or modify
'    it under the terms of the GNU Library General Public License as published by
'    the Free Software Foundation; either version 2.1 of the License, or
'    (at your option) any later version.
'
'    VBCorLib is distributed in the hope that it will be useful,
'    but WITHOUT ANY WARRANTY; without even the implied warranty of
'    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'    GNU Library General Public License for more details.
'
'    You should have received a copy of the GNU Library General Public License
'    along with Foobar; if not, write to the Free Software
'    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
'
'    Module: RijndaelManagedTransform
'

''
' Performs cryptographic operations on data using the Rijndael algorithm.
'
' @remarks Details about the Rijndael algorithm can be found at http://csrc.nist.gov/CryptoToolkit/aes/rijndael
'
Option Explicit
Implements IObject
Implements ICryptoTransform

' We use a structure to ensure the layout of the temp variables
' remain constant so we can manipulate them.
Private Type Temps
    ' we want these to remain in this layout so we can use CopyMemory.
    T0 As Long
    T1 As Long
    T2 As Long
    T3 As Long
    T4 As Long
    T5 As Long
    T6 As Long
    T7 As Long
    
    ' defining a fixed-size array in a struct is like declaring
    ' each element as its own variable in the struct, so accessing
    ' an element requires very little overhead compared to normal arrays.
    s(31) As Byte
End Type

Private mNr                 As Long ' Number of times a block will be mangled.
Private mNb                 As Long ' Number of 4-byte columns in a block.
Private mNk                 As Long ' Number of 4-byte columns in the key.
Private mExpKey()           As Long
Private mBlockSizeBits      As Long
Private mBlockSizeBytes     As Long
Private mInputBlockSize     As Long
Private mOutputBlockSize    As Long
Private mPadding            As PaddingMode
Private mMode               As CipherMode
Private mRgbIV()            As Byte
Private mWorkingIV()        As Byte
Private mTempIV()           As Byte
Private mIsEncrypting       As Boolean
Private mHasLastBlock       As Boolean
Private mLastBlock()        As Byte
Private mKeepLastBlock      As Boolean


' Lookup tables. We use fixed-length arrays to increase the access speed.
Private mT0(0 To 255)   As Long
Private mT1(0 To 255)   As Long
Private mT2(0 To 255)   As Long
Private mT3(0 To 255)   As Long
Private mT4(0 To 255)   As Long
Private mRCon() As Long
Private mSBox() As Byte



' predefined pointers used for quick array access.
Private mTmp            As Temps
Private mSPtr           As Long
Private mTmpPtr         As Long
Private mTempIVPtr      As Long
Private mWorkingIVPtr   As Long


''
' Returns if the current transfrom can be reused after calling TransformFinalBlock.
'
' @return Returns True if it can be reused, False otherwise.
' @remarks This always returns True.
'
Public Property Get CanReuseTransform() As Boolean
    CanReuseTransform = True
End Property

''
' Returns if this transform can process more than one block per TransformBlock call.
'
' @return This always returns True.
'
Public Property Get CanTransformMultipleBlocks() As Boolean
    CanTransformMultipleBlocks = True
End Property

''
' Returns the blocksize in bits.
'
' @return The blocksize in bits.
'
Public Property Get BlockSizeValue() As Long
    BlockSizeValue = mBlockSizeBits
End Property

''
' Returns the size of one block of data that is to be processed.
'
' @return The size of one block of data to be processed.
'
Public Property Get InputBlockSize() As Long
    InputBlockSize = mInputBlockSize
End Property

''
' Returns the size of the resulting block of data after an input block of data has been processed.
'
' @return The size of the resulting block of data after an input block of data has been processed.
'
Public Property Get OutputBlockSize() As Long
    OutputBlockSize = mOutputBlockSize
End Property

''
' Processes a set of data, encrypting or decrypting it.
'
' @param InputBuffer The data to be processed.
' @param InputOffset The index to begin processing from.
' @param InputCount The amount of data to be processed.
' @param OutputBuffer The buffer to place the processed data.
' @param OutputOffset The index to begin placing the processed data.
' @return The number of bytes that were processed.
' @remarks The InputCount must be an exact multiple of the InputBlockSize or an exception will be thrown.
'
Public Function TransformBlock(ByRef InputBuffer() As Byte, ByVal InputOffset As Long, ByVal InputCount As Long, ByRef OutputBuffer() As Byte, ByVal OutputOffset As Long) As Long
    ' During normal transformations, the number of bytes to be worked on must be
    ' an exact multiple of mInputBlockSize. There can be no partial blocks.
    If (InputCount <= 0) Or (InputCount Mod mInputBlockSize <> 0) Then _
        Throw Cor.NewArgumentException("Invalid value.", "InputCount")

    Dim Result As Long
    Result = VerifyArrayRange(SAPtr(InputBuffer), InputOffset, InputCount)
    If Result <> NO_ERROR Then Call ThrowArrayRangeException(Result, "InputBuffer", InputOffset, "InputOffset", InputCount, "InputCount", False)

    ' We can use the InputCount for the number of bytes to be outputted because
    ' this cipher keeps the original number of bytes in the encrypted output, except
    ' for any padding which is not added in this process.
    Result = VerifyArrayRange(SAPtr(OutputBuffer), OutputOffset, InputCount)
    If Result <> NO_ERROR Then Call ThrowArrayRangeException(Result, "OutputBuffer", OutputOffset, "OutputOffset", InputCount, "", False)

    If mIsEncrypting Then
        TransformBlock = EncryptBlock(InputBuffer, InputOffset, InputCount, OutputBuffer, OutputOffset)
    Else
        TransformBlock = DecryptBlock(InputBuffer, InputOffset, InputCount, OutputBuffer, OutputOffset)
    End If
End Function

''
' Processes a set of data adding any padding needed to complete the process.
'
' @param InputBuffer The final data to be processed.
' @param InputOffset The index to begin processing from.
' @param InputCount The amount of data to be processed.
' @return The final block of processed data.
' @remarks Once a final block has been processed, then transform is reset to begin transforming new data.
'
Public Function TransformFinalBlock(ByRef InputBuffer() As Byte, ByVal InputOffset As Long, ByVal InputCount As Long) As Byte()
    If cArray.IsNull(InputBuffer) Then _
        Throw Cor.NewArgumentNullException("InputBuffer cannot be null", "InputBuffer")
    If InputOffset < LBound(InputBuffer) Then _
        Throw Cor.NewArgumentOutOfRangeException(Environment.GetResourceString(ArgumentOutOfRange_LBound), "InputOffset", InputOffset)
    If (cArray.GetLength(InputBuffer) - InputCount < InputOffset) Then _
        Throw Cor.NewArgumentException(Environment.GetResourceString(Argument_InvalidCountOffset))
    
    If mIsEncrypting Then
        TransformFinalBlock = EncryptFinalBlock(InputBuffer, InputOffset, InputCount)
    Else
        TransformFinalBlock = DecryptFinalBlock(InputBuffer, InputOffset, InputCount)
    End If
End Function

''
' Resets the transform so a new set of data can begin to be processed.
'
Public Sub Reset()
    If mMode <> CipherMode.ECB Then
        mWorkingIV = mRgbIV
        mTempIV = mRgbIV
        
        mWorkingIVPtr = VarPtr(mWorkingIV(0))
        mTempIVPtr = VarPtr(mTempIV(0))
    End If
    
    If Not mIsEncrypting Then
        mHasLastBlock = False
        ReDim mLastBlock(0 To mInputBlockSize)
    End If
End Sub

''
' Releases all resources used by the class.
'
Public Sub Clear()
    Erase mRgbIV
    Erase mWorkingIV
    Erase mTempIV
    Erase mLastBlock
    Erase mExpKey
    Erase mTmp.s
End Sub

''
' This function determines if the value passed in is the same
' as the current object instance. Meaning, are the Value and
' this object the same object in memory.
'
' @param Value The value to compare against this instance.
' @return Returns True if the values are the same.
'
Public Function Equals(ByRef Value As Variant) As Boolean
    Equals = Object.Equals(Me, Value)
End Function

''
' Returns a psuedo-unique number used to help identify this
' object in memory. The current method is to return the value
' obtained from ObjPtr. If a different method needs to be impelmented
' then change the method here in this function.
'
' @return Returns a number identifing this instance.
'
Public Function GetHashCode() As Long
    GetHashCode = ObjPtr(CUnk(Me))
End Function

''
' Returns a string representation of this object instance.
' The default method simply returns the application name
' and class name in which this class resides.
'
' @return Returns a string representation of this instance.
'
Public Function ToString() As String
    ToString = Object.ToString(Me, App)
End Function



'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'   Friend Interface
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Friend Sub Init(ByRef RgbKey() As Byte, ByRef RgbIV() As Byte, ByVal Base As SymmetricAlgorithmBase, ByVal IsEncrypting As Boolean)
    mIsEncrypting = IsEncrypting
    
    With Base
        If (.Mode = CipherMode.CTS) Or (.Mode = CipherMode.OFB) Then _
            Throw Cor.NewCryptographicException("Invalid cipher mode.")
        
        mMode = .Mode
        mPadding = .Padding
        mBlockSizeBits = .BlockSize
        mBlockSizeBytes = mBlockSizeBits \ 8
        
        If mMode = CipherMode.CFB Then
            mInputBlockSize = .FeedbackSize \ 8
        Else
            mInputBlockSize = mBlockSizeBytes
        End If
            
        mOutputBlockSize = mInputBlockSize
    End With
    
    mNb = mBlockSizeBits \ 32
    mNk = cArray.GetLength(RgbKey) \ 4
    
    Call InitLookupTables
    Call CalculateNumberOfRounds
    Call CreateExpandedKey(RgbKey)
    
    mRgbIV = RgbIV
    Call Reset
    
    If (mPadding <> PaddingMode.None) And (mPadding <> PaddingMode.Zeros) Then
        mKeepLastBlock = True
        ReDim mLastBlock(0 To mInputBlockSize - 1)
    End If
End Sub


'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'   Private Helpers
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Function EncryptFinalBlock(ByRef InputBuffer() As Byte, ByVal InputOffset As Long, ByVal InputCount As Long) As Byte()
    Dim FullBlocks As Long
    FullBlocks = InputCount \ mInputBlockSize

    ' If we have a number of bytes to encrypt equal to a multiple of mBlockSize then
    ' we will have zero remaining bytes. Any padding will create a new full block instead
    ' of just filling in the last partial block.
    Dim RemainingBytes As Long
    RemainingBytes = InputCount - (FullBlocks * mOutputBlockSize)

    If (mPadding = PaddingMode.None) And (RemainingBytes <> 0) Then _
        Throw Cor.NewCryptographicException("Length of data to be encrypted is incorrect.")

    ' We need enough bytes to hold all the full blocks, 1 padded block produced by us.
    Dim TotalBytes As Long
    TotalBytes = (FullBlocks + 1) * mOutputBlockSize
    
    Dim OutputBuffer() As Byte
    ReDim OutputBuffer(0 To TotalBytes - 1)

    ' We have to copy the data to be encrypted to our output buffer because CryptoAPI
    ' puts the encrypted data back into the working array.
    If InputCount > 0 Then Call CopyMemory(OutputBuffer(0), InputBuffer(InputOffset), InputCount)

    TotalBytes = TotalBytes - CryptoHelper.PadBlock(OutputBuffer, FullBlocks * mOutputBlockSize + RemainingBytes, mPadding, mOutputBlockSize - RemainingBytes, mOutputBlockSize)
   
    If TotalBytes > 0 Then
        If TotalBytes < UBound(OutputBuffer) Then ReDim Preserve OutputBuffer(0 To TotalBytes - 1)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -