代码之家  ›  专栏  ›  技术社区  ›  Alexander Prokofyev

在Excel中加密和解密字符串

  •  12
  • Alexander Prokofyev  · 技术社区  · 15 年前

    我对是否可以使用Excel Visual Basic和一些加密服务提供商进行字符串加密/解密感兴趣。

    我发现了一个演练 Encrypting and Decrypting Strings in Visual Basic 但它似乎只对独立的Visual Basic有效。

    那么,您会建议我使用另一种加密方法还是演示如何在ExcelVisualBasic中采用演练?

    6 回复  |  直到 6 年前
        1
  •  22
  •   CraigTP    15 年前

    您提供的链接显示了如何使用vb.net执行字符串加密和解密,从而使用.NET框架。

    目前,Microsoft Office产品还不能使用 Visual Studio Tools for Applications 组件,它将使Office产品能够访问.NET框架的BCL(基类库),进而访问基础的Windows CSP(加密服务器提供程序),并为这些加密/解密功能提供一个很好的包装。

    目前,办公产品仍停留在原有的VBA上。( Visual Basic for Applications )它基于Visual Basic的旧vb6(及更早版本)版本,而不是基于.NET框架。

    由于所有这些原因,您要么需要调用win32 api来访问csp函数,要么必须在纯vb6/vba代码中“滚动自己的”加密方法,尽管这样可能不太安全。这完全取决于您希望加密的“安全性”。

    如果要“滚动自己的”基本字符串加密/解密例程,请查看以下链接以开始:

    Encrypt a String Easily
    Better XOR Encryption with a readable string
    vb6 - encryption function
    Visual Basic 6 / VBA String Encryption/Decryption Function

    如果要访问Win32 API并使用基础Windows CSP(一个更安全的选项),请参阅以下链接以获取有关如何实现此目的的详细信息:

    How to encrypt a string in Visual Basic 6.0
    Access to CryptEncrypt (CryptoAPI/WinAPI) functions in VBA

    最后一个链接可能是您想要的,包括一个完整的VBA类模块来“包装”Windows CSP函数。

        2
  •  3
  •   Cameron    10 年前

    创建一个名为clscifrado的类模块:


    Option Explicit
    Option Compare Binary
    
    Private clsClave As String
    
    Property Get Clave() As String
        Clave = clsClave
    End Property
    
    Property Let Clave(value As String)
        clsClave = value
    End Property
    
    
    Function Cifrar(Frase As String) As String
    
        Dim Cachos() As Byte
        Dim LaClave() As Byte
        Dim i As Integer
        Dim Largo As Integer
    
        If Frase <> "" Then
            Cachos() = StrConv(Frase, vbFromUnicode)
            LaClave() = StrConv(clsClave, vbFromUnicode)
            Largo = Len(clsClave)
    
            For i = LBound(Cachos) To UBound(Cachos)
                Cachos(i) = (Cachos(i) Xor LaClave(i Mod Largo)) + 34
            Next i
    
            Cifrar = StrConv(Cachos(), vbUnicode)
        Else
            Cifrar = ""
        End If
    
    End Function
    
    Function Descifrar(Frase As String) As String
    
        Dim Cachos() As Byte
        Dim LaClave() As Byte
        Dim i As Integer
        Dim Largo As Integer
    
        If Frase <> "" Then
            Cachos() = StrConv(Frase, vbFromUnicode)
            LaClave() = StrConv(clsClave, vbFromUnicode)
            Largo = Len(clsClave)
    
            For i = LBound(Cachos) To UBound(Cachos)
                Cachos(i) = Cachos(i) - 34
                Cachos(i) = (Cachos(i) Xor LaClave(i Mod Largo))
            Next i
    
            Descifrar = StrConv(Cachos(), vbUnicode)
        Else
            Descifrar = ""
        End If
    
    End Function
    

    现在您可以在代码中使用它:

    密码


    Private Sub btnCifrar_Click()
    
        Dim Texto As String
        Dim cCifrado As clsCifrado
    
        Set cCifrado = New clsCifrado
    
        '---poner la contraseña
        If tbxClave.Text = "" Then
            MsgBox "The Password is missing"
            End Sub
        Else
            cCifrado.Clave = tbxClave.Text
        End If
    
        '---Sacar los datos
        Texto = tbxFrase.Text
    
        '---cifrar el texto
        Texto = cCifrado.Cifrar(Texto)
    
        tbxFrase.Text = Texto
    
     End Sub
    

    解密码


    Private Sub btnDescifrar_Click()
    
        Dim Texto As String
        Dim cCifrado As clsCifrado
    
        Set cCifrado = New clsCifrado
    
        '---poner la contraseña
        If tbxClave.Text = "" Then
            MsgBox "The Password is missing"
            End Sub
        Else
            cCifrado.Clave = tbxClave.Text
        End If
    
        '---Sacar los datos
        Texto = tbxFrase.Text
    
        '---cifrar el texto
        Texto = cCifrado.Descifrar(Texto)
    
        tbxFrase.Text = Texto
    End Sub
    
        3
  •  1
  •   mosh pe3k    8 年前

    您可以通过任何shell脚本调用pipe excel单元数据。 安装GPL BERT( http://bert-toolkit.com/ )Excel的R语言接口。 在Excel中使用下面的r脚本将单元数据传输到bash/perl/gpg/openssl。

     c:\> cat c:\R322\callable_from_excel.R
        CRYPTIT <- function( PLAINTEXT, MASTER_PASS ) {
        system(
          sprintf("bash -c 'echo '%s' |
            gpg --symmetric --cipher-algo blowfish --force-mdc --passphrase '%s' -q  |
            base64 -w 0'",
            PLAINTEXT, MASTER_PASS),
          intern=TRUE)
      }
    
    DECRYPTIT <- function( CRYPTTEXT, MASTER_PASS ) {
        system(
          sprintf("bash -c 'echo '%s'|
            base64 -d |
            gpg --passphrase '%s' -q |
            putclip | getclip' ",CRYPTTEXT,MASTER_PASS),
          intern=TRUE)  
      } 
    

    在Excel中,您可以尝试:c1=密码(a1,a2)和c2=解密(c1,a2) 可选:putclip将解密的文本保存在剪贴板中。 这两种函数类型都是:string->string。 在单引号字符串中转义单引号的常见注意事项。

        4
  •  0
  •   MathKid    10 年前

    下面是一个基本的符号加密/解密示例:

    Sub testit()
        Dim inputStr As String
        inputStr = "Hello world!"
    
        Dim enctrypted As String, decrypted As String
        encrypted = scramble(inputStr)
        decrypted = scramble(encrypted)
        Debug.Print encrypted
        Debug.Print decrypted
    End Sub
    
    
    Function stringToByteArray(str As String) As Variant
        Dim bytes() As Byte
        bytes = str
        stringToByteArray = bytes
    End Function
    
    Function byteArrayToString(bytes() As Byte) As String
        Dim str As String
        str = bytes
        byteArrayToString = str
    End Function
    
    
    Function scramble(str As String) As String
        Const SECRET_PASSWORD As String = "K*4HD%f#nwS%sdf032#gfl!HLKN*pq7"
    
        Dim stringBytes() As Byte, passwordBytes() As Byte
        stringBytes = stringToByteArray(str)
        passwordBytes = stringToByteArray(SECRET_PASSWORD)
    
        Dim upperLim As Long
        upperLim = UBound(stringBytes)
        ReDim scrambledBytes(0 To upperLim) As Byte
        Dim idx As Long
        For idx = LBound(stringBytes) To upperLim
            scrambledBytes(idx) = stringBytes(idx) Xor passwordBytes(idx)
        Next idx
        scramble = byteArrayToString(scrambledBytes)
    End Function
    

    请注意,如果给定的输入字符串长于密码,则此操作将失败。这只是一个开始学习的例子。

        5
  •  0
  •   OGCJN    6 年前

    此代码对我很好(3DES加密/解密):

    我将初始化向量和三重密钥存储为环境变量(明显不同于此处发布的值),并使用vba environ()函数获取它们,因此vba代码中的所有敏感数据(密码)都会加密。

    Option Explicit
    
    Public Const INITIALIZATION_VECTOR = "zlrs$5kd"  'Always 8 characters
    
    Public Const TRIPLE_DES_KEY = ">tlF8adk=35K{dsa" 'Always 16 characters
    
    Sub TestEncrypt()
        MsgBox "This is an encrypted string: -> " & EncryptStringTripleDES("This is an encrypted string:")
        Debug.Print EncryptStringTripleDES("This is an encrypted string:")
    End Sub
    
    Sub TestDecrypt()
        MsgBox "u99CVItCGiMQEVYHf8+S22QbJ5CPQGDXuS5n1jvEIgU= -> " & DecryptStringTripleDES("u99CVItCGiMQEVYHf8+S22QbJ5CPQGDXuS5n1jvEIgU=")
    End Sub
    
    
    Function EncryptStringTripleDES(plain_string As String) As Variant
    
        Dim encryption_object As Object
        Dim plain_byte_data() As Byte
        Dim encrypted_byte_data() As Byte
        Dim encrypted_base64_string As String
    
        EncryptStringTripleDES = Null
    
        On Error GoTo FunctionError
    
        plain_byte_data = CreateObject("System.Text.UTF8Encoding").GetBytes_4(plain_string)
    
        Set encryption_object = CreateObject("System.Security.Cryptography.TripleDESCryptoServiceProvider")
        encryption_object.Padding = 3
        encryption_object.key = CreateObject("System.Text.UTF8Encoding").GetBytes_4(TRIPLE_DES_KEY)
        encryption_object.IV = CreateObject("System.Text.UTF8Encoding").GetBytes_4(INITIALIZATION_VECTOR)
        encrypted_byte_data = _
                encryption_object.CreateEncryptor().TransformFinalBlock(plain_byte_data, 0, UBound(plain_byte_data) + 1)
    
        encrypted_base64_string = BytesToBase64(encrypted_byte_data)
    
        EncryptStringTripleDES = encrypted_base64_string
    
        Exit Function
    
    FunctionError:
    
        MsgBox "TripleDES encryption failed"
    
    End Function
    
    Function DecryptStringTripleDES(encrypted_string As String) As Variant
    
        Dim encryption_object As Object
        Dim encrypted_byte_data() As Byte
        Dim plain_byte_data() As Byte
        Dim plain_string As String
    
        DecryptStringTripleDES = Null
    
        On Error GoTo FunctionError
    
        encrypted_byte_data = Base64toBytes(encrypted_string)
    
        Set encryption_object = CreateObject("System.Security.Cryptography.TripleDESCryptoServiceProvider")
        encryption_object.Padding = 3
        encryption_object.key = CreateObject("System.Text.UTF8Encoding").GetBytes_4(TRIPLE_DES_KEY)
        encryption_object.IV = CreateObject("System.Text.UTF8Encoding").GetBytes_4(INITIALIZATION_VECTOR)
        plain_byte_data = encryption_object.CreateDecryptor().TransformFinalBlock(encrypted_byte_data, 0, UBound(encrypted_byte_data) + 1)
    
        plain_string = CreateObject("System.Text.UTF8Encoding").GetString(plain_byte_data)
    
        DecryptStringTripleDES = plain_string
    
        Exit Function
    
    FunctionError:
    
        MsgBox "TripleDES decryption failed"
    
    End Function
    
    
    Function BytesToBase64(varBytes() As Byte) As String
        With CreateObject("MSXML2.DomDocument").createElement("b64")
            .DataType = "bin.base64"
            .nodeTypedValue = varBytes
            BytesToBase64 = Replace(.Text, vbLf, "")
        End With
    End Function
    
    
    Function Base64toBytes(varStr As String) As Byte()
        With CreateObject("MSXML2.DOMDocument").createElement("b64")
             .DataType = "bin.base64"
             .Text = varStr
             Base64toBytes = .nodeTypedValue
        End With
    End Function
    

    源代码取自此处: https://gist.github.com/motoraku/97ad730891e59159d86c

    注意原始代码和我的代码之间的区别,这是附加选项 encryption_object.padding=3 迫使vba 进行填充。当填充选项设置为3时,与DESIEDE3O-CBCycLyPT算法的C++实现完全一样,结果与此结果一致。 online tool .

        6
  •  0
  •   user3579314    6 年前

    此代码在VBA中工作良好,可以轻松地移到VB.NET

    避免处理非“正常”字符。您可以用allowedchars决定允许哪些字符。

    Public Function CleanEncryptSTR(MyString As String, MyPassword As String, Encrypt As Boolean) As String
    'Encrypts strings chars contained in Allowedchars
    'MyString = String to decrypt
    'MyPassword = Password
    'Encrypt True: Encrypy   False: Decrypt
        Dim i As Integer
        Dim ASCToAdd As Integer
        Dim ThisChar As String
        Dim ThisASC As Integer
        Dim NewASC As Integer
        Dim MyStringEncrypted As String
        Dim AllowedChars As String
    
        AllowedChars = "&0123456789;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    
        If Len(MyPassword) > 0 Then
            For i = 1 To Len(MyString)
    '            ThisASC = Asc(Mid(MyString, i, 1))
    '            ThisASC = IntFromArray(Asc(Mid(MyString, i, 1)), MyVector())
    
                ThisChar = Mid(MyString, i, 1)
                ThisASC = InStr(AllowedChars, ThisChar)
    
                If ThisASC > 0 Then
                    ASCToAdd = Asc(Mid(MyPassword, i Mod Len(MyPassword) + 1, 1))
                    If Encrypt Then
                        NewASC = ThisASC + ASCToAdd
                    Else
                        NewASC = ThisASC - ASCToAdd
                    End If
                    NewASC = NewASC Mod Len(AllowedChars)
                    If NewASC <= 0 Then
                        NewASC = NewASC + Len(AllowedChars)
                    End If
    
                    MyStringEncrypted = MyStringEncrypted & Mid(AllowedChars, NewASC, 1)
                Else
                    MyStringEncrypted = MyStringEncrypted & ThisChar
                End If
            Next i
        Else
            MyStringEncrypted = MyString
        End If
    
        CleanEncryptSTR = MyStringEncrypted
    
    End Function
    
    推荐文章