programing

문자열 암호화/암호화

oldcodes 2023. 9. 6. 22:17
반응형

문자열 암호화/암호화

Excel Visual Basic과 일부 암호화 서비스 업체를 이용하여 문자열 암호화/복호화를 할 수 있는지 궁금합니다.

Visual Basic에서 문자열 암호화암호 해독 워크스루를 찾았지만 독립 실행형 Visual Basic에만 유효한 것 같습니다.

그래서 다른 암호화 방법을 제안해 주시거나 Excel Visual Basic에 워크스루를 채택할 수 있는 방법을 보여주시겠습니까?

제공하는 링크에는 VB를 사용하여 문자열 암호화 및 복호화를 수행하는 방법이 나와 있습니다.NET을 사용합니다.NET Framework.

현재 Microsoft Office 제품은 아직 Visual Studio Tools for Applications 구성 요소를 사용할 수 없으며, 이를 통해 Office 제품이 에 액세스할 수 있습니다.NET 프레임워크의 BCL(기본 클래스 라이브러리)은 다시 기본 Windows CSP(암호화 서버 공급자)에 액세스하여 암호화/복호화 기능에 대한 멋진 래퍼를 제공합니다.

당분간 Office 제품은 COM을 기반으로 하는 VB6(이전 버전)의 Visual Basic(Visual Basic for Applications)을 기반으로 하는 이전 버전의 VBA(Visual Basic for Applications)에 묶여 있습니다.NET Framework.

이 모든 것 때문에 CSP 기능에 액세스하기 위해 Win32 API를 호출하거나, 안전성이 떨어질 가능성이 높지만 순수한 VB6/VBA 코드로 암호화 방법을 "롤 유어셀프"해야 합니다.이 모든 것은 암호화를 얼마나 "안전하게" 유지하느냐에 달려 있습니다.

기본 문자열 암호화/복호화 루틴을 "롤유어셀프"하려면 다음 링크를 참조하여 시작하십시오.

쉽게 문자열 암호화
읽기 쉬운 문자열로 XOR 암호화 개선

vb6 - 암호화 기능
Visual Basic 6 / VBA 문자열 암호화/복호화 기능

Win32 API에 액세스하여 기본 Windows CSP(훨씬 더 안전한 옵션)를 사용하려면 다음 링크를 참조하여 이를 달성하는 방법에 대한 자세한 정보를 확인하십시오.

Visual Basic 6.0에서 문자열을 암호화하는 방법

VBA의 CryptoAPI/WinAPI(암호화/윈API) 기능에 대한 액세스

이 마지막 링크는 Windows CSP 기능을 "랩핑"할 수 있는 완전한 VBA Class 모듈이 포함되어 있습니다.

이 코드는 제게 적합합니다(3DES 암호화/복호화).

저는 INITIALITY_VECTOR와 TRIPL_DES_KEY를 환경 변수(여기에 게시된 값과 분명히 다른 값)로 저장하고 VBA Environment() 함수를 사용하여 이를 얻으므로 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를 주목하십시오.VBA가 패딩을 수행하지 않도록 하는 패딩 = 3.패딩 옵션을 3으로 설정하면 DES_ede3_cbc_encrypt 알고리즘의 C++ 구현에서와 동일한 결과를 얻을 수 있고 이 온라인 도구에 의해 생성되는 것과 일치합니다.

이 코드는 VBA에서 잘 작동하며 쉽게 VB.NET으로 이동할 수 있습니다.

"정상"이 아닌 문자는 처리하지 않습니다.허용된 문자에서 허용할 문자를 결정합니다.

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

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

pipe excel cell data는 셸 스크립트를 통해 호출할 수 있습니다.GPL Bert 설치 (http://bert-toolkit.com/) Excel용 R language interface )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=CWIT(A1,A2) 및 C2=CWIT(C1,A2) 옵션: putclip은 복호화된 텍스트를 클립보드에 저장합니다.두 함수 유형 모두 String -> String입니다.작은 따옴표 문자열에서 작은 따옴표를 피하는 것에 대한 일반적인 주의 사항입니다.

기본적인 대칭 암호화/복호화 예는 다음과 같습니다.

Sub testit()
    Dim inputStr As String
    inputStr = "Hello world!"

    Dim encrypted 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

지정된 입력 문자열이 SECRET_PASSET보다 길면 충돌이 발생합니다.이것은 단지 시작하기 위한 예시일 뿐입니다.

언급URL : https://stackoverflow.com/questions/1470939/string-encryption-decryption

반응형