forum.vdsworld.com Forum Index forum.vdsworld.com
Visit VDSWORLD.com
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 


AES encryption
Goto page 1, 2  Next
 
Post new topic   Reply to topic    forum.vdsworld.com Forum Index -> General Help
View previous topic :: View next topic  
Author Message
Aslan
Valued Contributor
Valued Contributor


Joined: 31 May 2001
Posts: 589
Location: Memphis, TN USA

PostPosted: Thu Dec 24, 2009 8:18 pm    Post subject: AES encryption Reply with quote

Anyone know of a DLL or DSU that will do at least 128bit AES encryption. I need this capability to create a FIPS compliant app.

Thanks in advance
Back to top
View user's profile Send private message Send e-mail
vdsalchemist
Admin Team


Joined: 23 Oct 2001
Posts: 1448
Location: Florida, USA

PostPosted: Fri Dec 25, 2009 1:27 am    Post subject: *Update* with correct version of DSU Reply with quote

Yes I have a DSU that does this. It uses the Microsoft Crypto API to achieve it. Below is the incomplete code. There is a lot to the Crypto API but I have built a demo that can encrypt files and strings.

Code:

#---------------------------------------------------------------------------------------#
#                                                                                       #
# Description: DSU wrapper for the Microsoft Crypto API                                 #
#                                                                                       #
# Copyright: Copyright © 2009 DragonSphere Software All Rights Reserved.                #
#                                                                                       #
#---------------------------------------------------------------------------------------#
#
# This DSU uses the following Windows Crypto functions.
#DEFINE COMMAND,CSPDISCONNECT
#DEFINE FUNCTION,CSPCONNECT,CSPDETAILS,CSPENCRYPTDATA,CSPDECRYPTDATA,CSPBASE64

:CSPConnect
# Aquire a Crypto provider handle
# %1 = The key container name choosen by the user.
%%KEY_CONTAINER = @chr(34)%1@chr(34)

# Returns handle to the Crypto provider in %R
# If a handle cannot be secured %R is null and @OK() is set to false
%R =

# Name of the Crypto service provider that this unit uses.
# For backwards compatibility we are making Windows use it's v1.0 provider this may change later.
#%%SERVICE_PROVIDER = "Microsoft Base Cryptographic Provider v1.0"
%%PROV_RSA_FULL = 1
%%PROV_RSA_AES = 24

%%PP_NAME = 4
%%PP_VERSION = 5
%%PP_CONTAINER = 6
%%CRYPT_NEWKEYSET = 8
# %%CRYPT_VERIFYCONTEXT =
#%%ALG_CLASS_DATA_ENCRYPT = 24576
#%%ALG_CLASS_HASH = 32768
#%%ALG_TYPE_ANY = 0
#%%ALG_TYPE_STREAM = 2048
#%%ALG_TYPE_BLOCK = 1536
#%%ALG_SID_AES_128 = 14
#%%ALG_SID_AES_192 = 15
#%%ALG_SID_AES_256 = 16
#%%ALG_SID_AES = 17
#%%ALG_SID_RC4 = 1
#%%ALG_SID_MD5 = 3
#%%ALG_SID_SHA1 = 4
#%%CALG_MD5 = ((%%ALG_CLASS_HASH Or %%ALG_TYPE_ANY) Or %%ALG_SID_MD5)
%%CALG_MD5 = 32771
%%CALG_SHA1 = 32772
#%%CALG_SHA_512 = 32782
#%%CALG_RC4 = ((%%ALG_CLASS_DATA_ENCRYPT Or %%ALG_TYPE_STREAM) Or %%ALG_SID_RC4)
%%CALG_RC4 = 26625
#%%CALG_AES_128 = (%%ALG_CLASS_DATA_ENCRYPT|%%ALG_TYPE_BLOCK|%%ALG_SID_AES_128)
#%%CALG_AES_128 = 26126
#%%CALG_AES_192 = (%%ALG_CLASS_DATA_ENCRYPT|%%ALG_TYPE_BLOCK|%%ALG_SID_AES_192)
#%%CALG_AES_192 = 26127
#%%CALG_AES_256 = (%%ALG_CLASS_DATA_ENCRYPT|%%ALG_TYPE_BLOCK|%%ALG_SID_AES_256)
%%CALG_AES_256 = 26128

#%%CALG_3DES = 26115

#%%CRYPT_VERIFYCONTEXT = $F0000000
%%CRYPT_NEWKEYSET = 8
%%CRYPT_DELETEKEYSET = $00000010
#%%CRYPT_MACHINE_KEYSET = $00000020
#%%CRYPT_SILENT = $00000040
#%%CRYPT_EXPORTABLE = $00000001
#%%CRYPT_USER_PROTECTED = $00000002
#%%CRYPT_CREATE_SALT = $00000004
#%%CRYPT_UPDATE_KEY = $00000008
#%%CRYPT_NO_SALT = $00000010
#%%CRYPT_PREGEN = $00000040
#%%CRYPT_RECIPIENT = $00000010
#%%CRYPT_INITIATOR = $00000040
#%%CRYPT_ONLINE = $00000080
#%%CRYPT_SF = $00000100
#%%CRYPT_CREATE_IV = $00000200
#%%CRYPT_KEK = $00000400
#%%CRYPT_DATA_KEY = $00000800
#%%CRYPT_VOLATILE = $00001000
#%%CRYPT_SERVER = $00000400

# Base64, with certificate beginning and ending headers
#%%CRYPT_STRING_BASE64HEADER = 0
# Base64, without headers
%%CRYPT_STRING_BASE64 = 1
# Pure binary copy
%%CRYPT_STRING_BINARY = 2
# Base64, with request beginning and ending headers
#%%CRYPT_STRING_BASE64REQUESTHEADER = 3
# Hexadecimal only
%%CRYPT_STRING_HEX = 4
# Hexadecimal, with ASCII character display
#%%CRYPT_STRING_HEXASCII = 5
# Base64, with X.509 CRL beginning and ending headers
#%%CRYPT_STRING_BASE64X509CRLHEADER = 9
# Hexadecimal, with address display
#%%CRYPT_STRING_HEXADDR = 10
# Hexadecimal, with ASCII character and address display
#%%CRYPT_STRING_HEXASCIIADDR = 11
# A raw hexadecimal string.
# Windows Server 2003, Windows XP:  This value is not supported. 
#%%CRYPT_STRING_HEXRAW = 12




#%%CRYPT_DECRYPT_RSA_NO_PADDING_CHECK = $00000020

#%%NUMBER_ENCRYPT_PASSWORD = "´o¸sçPQ]"
%%PROVIDER_TYPE =
# %2 = The provider type can be RSA_FULL or RSA_AES for now.
If @Equal(%2,RC4)
  %%ENCRYPT_ALGORITHM = %%CALG_RC4
  %%KEYLENGTH = $00800000
  %%ENCRYPT_BLOCK_SIZE = 8
  %%PROVIDER_TYPE = %%PROV_RSA_FULL
  %%HASH_ALGORITHM = %%CALG_MD5
ElsIf @Equal(%2,AES)
  %%ENCRYPT_ALGORITHM = %%CALG_AES_256
  %%KEYLENGTH = $01000000
  %%ENCRYPT_BLOCK_SIZE = 16
  %%PROVIDER_TYPE = %%PROV_RSA_AES
  %%HASH_ALGORITHM = %%CALG_SHA1
Else
  %%ENCRYPT_ALGORITHM = %%CALG_RC4
  %%KEYLENGTH = $00800000 
  %%PROVIDER_TYPE = %%PROV_RSA_FULL
  %%HASH_ALGORITHM = %%CALG_MD5 
End

LoadLib kernel32.dll
LoadLib advapi32.dll
LoadLib crypt32.dll
%H = @BINARY(DWORD,0)
%A = @lib(advapi32,CryptAcquireContextA,BOOL:,INT:@ADDR("%H"),STR:%%KEY_CONTAINER,NIL:,INT:%%PROVIDER_TYPE,INT:%%CRYPT_NEWKEYSET)
If @Zero(%A)
  %A = @lib(advapi32,CryptAcquireContextA,BOOL:,INT:@ADDR("%H"),STR:%%KEY_CONTAINER,NIL:,INT:%%PROVIDER_TYPE,INT:0)
  If @Zero(%A)
   %A = @lib(advapi32,CryptAcquireContextA,BOOL:,INT:@ADDR("%H"),NIL:,NIL:,INT:%%PROVIDER_TYPE,INT:0)
   If @Zero(%A)
     error -1
   End
  Else
    %R = @val(%H)
  End
Else
  %R = @val(%H)
End
Exit %R

:CSPDisconnect
  #Release the Crypto provider handle.
  If @unequal(%1,0)
    If @Equal(@chr(34)%2@chr(34),%%KEY_CONTAINER)
      %A = @lib(advapi32,CryptAcquireContextA,BOOL:,INT:%1,STR:%%KEY_CONTAINER,NIL:,INT:%%PROVIDER_TYPE,INT:%%CRYPT_DELETEKEYSET)
    End
    %A = @lib(advapi32,CryptReleaseContext,BOOL:,INT:%1,INT:0)
    If @equal(%A,0)
      error -1
    End
  Else
    error -1
  End
Exit

:CSPDetails
  # Get details on the Crypto provider.
  %R =
  #%Z =
  If @unequal(%1,0)

    %c = 1
    %d = @succ(@len(%2))
    Repeat
      %l = @BINARY(DWORD,1000)   
      %y =
      %y = @fill(@VAL(%l),,Z)
      %p = @substr(%2,%c,%c)
      If @Equal(%p,P)
        %a = @lib(advapi32,CryptGetProvParam,BOOL:,INT:%1,INT:%%PP_NAME,INT:@ADDR("%y"),INT:@ADDR("%l"),INT:0)
        If @unequal(%a,0)
         
          %t = @val(%l)
          If @Greater(%t,0)
            If %R
              %R = %R@fsep()@Substr(@ADJUST(%y),1,%t)
            Else
              %R = @Substr(@ADJUST(%y),1,%t)
            End
          End
        Else
          Warn Error $@hex(@lib(kernel32,GetLastError,INT:),8) reading provider name.
        End
      ElsIf @Equal(%p,C)
        %a = @lib(advapi32,CryptGetProvParam,BOOL:,INT:%1,INT:%%PP_CONTAINER,INT:@ADDR("%y"),INT:@ADDR("%l"),INT:0)
        If @unequal(%a,0)
          %t = @val(%l)
          If @Greater(%t,0)
            If %R
              %R = %R@fsep()@Substr(@ADJUST(%y),1,%t)
            Else
              %R = @substr(@ADJUST(%y),1,%t)
            End
          End
        Else
          Warn Error $@hex(@lib(kernel32,GetLastError,INT:),8) reading container name.
        End
      ElsIf @Equal(%p,V)
        %y = @BINARY(DWORD,0)
        %l = @BINARY(DWORD,4)
        %a = @lib(advapi32,CryptGetProvParam,BOOL:,INT:%1,INT:%%PP_VERSION,INT:@addr("%y"),INT:@ADDR("%l"),INT:0)
        If @unequal(%a,0)
          %t = @val(%l)
          %u = @val(%y)
          If @Greater(%t,0)
            If %R
              %R = %R@fsep()$@Hex(%u,8)
            Else
              %R = $@Hex(%u,8)
            End
          End
        Else
          Warn Error $@hex(@lib(kernel32,GetLastError,INT:),8) reading version info.
        End
      End
      %c = @succ(%c)
    Until @Equal(%c,%d)
  End
  %R = @Trim(%R)
Exit %R

:CSPEncryptData
  %5 = True
  Gosub CSPEncryptDecrypt
  %R = %%CSPRet
Exit %R

:CSPDecryptData
  %5 = False
  Gosub CSPEncryptDecrypt
  %R = %%CSPRet
Exit %R

:CSPExportKey
  %R =
 
Exit %R

:CSPBASE64
  # Base64 encodes or decodes data
  # %2 = the @addr() of the data to operate on.
  # %3 = the length of the data that %2 points too.
  %R =
  If @Equal(%1,ENCODE)
    %l = @binary(DWORD,%3)
    %z = @val(%l)
    %A = @lib(crypt32,CryptBinaryToStringA,BOOL:,INT:%2,INT:%z,INT:%%CRYPT_STRING_BASE64,NIL:,INT:@Addr("%l"))
    %R = @fill(@Val(%l),,Z)
    %A = @lib(crypt32,CryptBinaryToStringA,BOOL:,INT:%2,INT:%z,INT:%%CRYPT_STRING_BASE64,INT:@Addr("%R"),INT:@Addr("%l"))
  ElsIf @Equal(%1,DECODE)
    #%t = %3
    %l = @BINARY(DWORD,0)
    %y = @BINARY(DWORD,0)
    %A = @lib(crypt32,CryptStringToBinaryA,BOOL:,INT:%2,INT:%3,INT:%%CRYPT_STRING_BASE64,NIL:,INT:@Addr("%l"),NIL:,INT:@Addr("%y"))
    %R = @fill(@Val(%l),,Z)
    %A = @lib(crypt32,CryptStringToBinaryA,BOOL:,INT:%2,INT:%3,INT:%%CRYPT_STRING_BASE64,INT:@Addr("%R"),INT:@Addr("%l"),NIL:,INT:@Addr("%y"))   
  End
Exit %R


:CSPEncryptDecrypt
  %R =
  %%CSPRet =
  %h = @BINARY(DWORD,0)
  %k = @BINARY(DWORD,0)
  If @unequal(%1,0)
    #--------------------------------------------------------------------
    #The data will be encrypted with a session key derived from the
    #password.
    #The session key will be recreated when the data is decrypted
    #only if the password used to create the key is available.
    #--------------------------------------------------------------------
   
    #Create a hash object.
    %A = @lib(advapi32,CryptCreateHash,INT:,INT:%1,INT:%%HASH_ALGORITHM,INT:0,INT:0,INT:@addr("%h"))
    If @unequal(%A,0)
      %h = @val(%h)
      #salt the password...
      #%p = %2@chr(1)@chr(1)@chr(1)@chr(1)
      %p = %2
     
      #Hash the password.
      %z = @lib(advapi32,CryptHashData,INT:,INT:%h,STR:%p,INT:@LEN(%p),INT:0)
      If @unequal(%z,0)
        #Derive a session key from the hash object.
       
        %A = @lib(advapi32,CryptDeriveKey,INT:,INT:%1,INT:%%ENCRYPT_ALGORITHM,INT:%h,INT:%%KEYLENGTH,INT:@addr("%k"))
        If @unequal(%A,0)
          %k = @val(%k)
          If @Equal(%4,BINARY)
            %4 = %%CRYPT_STRING_BINARY
          ElsIf @Equal(%4,HEX)
            %4 = %%CRYPT_STRING_HEX
          ElsIf @Equal(%4,BASE64)
            %4 = %%CRYPT_STRING_BASE64
          Else
            %4 = %%CRYPT_STRING_BASE64
          End
          #Do the work
          If @Equal(%5,1)@Equal(%5,True)
            #Encrypt data.
            %o = @len(%3)
            #If @Equal(%%ENCRYPT_ALGORITHM,%%CALG_RC4)
           
            #Else
            if @Greater(%o,1000)
              %%blocklength = @diff(1000,@mod(1000,%%ENCRYPT_BLOCK_SIZE))
            Else
              %%blocklength = @diff(%o,@mod(%o,%%ENCRYPT_BLOCK_SIZE))
            End
            If @Greater(%%ENCRYPT_BLOCK_SIZE,1)
              %%length = @sum(%%blocklength,%%ENCRYPT_BLOCK_SIZE)
            Else
              %%length = %%blocklength
            End
            # Info %o @len(%3)@CR()length is %%length@CR()block length is %%blocklength
            %n =
            %c = 1
            %%iterations = @fround(@fdiv(%o,%%blocklength))
            # Info iterations = %%iterations
            %%cnt = 0
            %%eof = 0
            %%cntlength = %%blocklength
            Repeat
              if @greater(%%cntlength,%o)
                %%stsize = @succ(@diff(%o,%c))
                %t = @substr(%3,%c,%o)
                #Info @len(%t)
              Else
                %%stsize = %%blocklength
                %t = @substr(%3,%c,@sum(%c,@pred(%%blocklength)))
              End
              If @less(%%stsize,%%blocklength)
               %t = %t@fill(@diff(%%blocklength,%%stsize),,Z)
               #%%eof = 1
              End
              # %l = @BINARY(DWORD,%%stsize)
              #Else
               %l = @BINARY(DWORD,%%blocklength)
              #End
              #Info @len(%t)@CR()length is %%length@CR()block length is %%blocklength
              #If @Equal(%%cnt,@pred(%%iterations))
              #  %%eof = 1
              #End
              #%A = @lib(advapi32,CryptEncrypt,INT:,INT:%k,INT:0,INT:0,INT:0,NIL:,INT:@Addr("%l"),INT:%%length)           
              %A = @lib(advapi32,CryptEncrypt,BOOL:,INT:%k,INT:0,INT:%%eof,INT:0,INT:@Addr("%t"),INT:@Addr("%l"),INT:%%length)
              If @Not(%A)
                Warn Error $@hex(@lib(kernel32,GetLastError,INT:),8) returning value
                %%cnt = %%iterations
              End
              If @Greater(@len(%n),0)
                %n = %n@substr(%t,1,@val(@substr(%l,1,4)))
              Else
                %n = %t
              End
              %c = @sum(%c,%%blocklength)
              %%cntlength = @sum(%%cntlength,%%blocklength)
              %%cnt = @succ(%%cnt)
            Until @Equal(%%cnt,@succ(%%iterations))
            # End
            If %A
              #If @equal(%4,%%CRYPT_STRING_BINARY)
              #  %R = %n
              #Else
                %l = @binary(DWORD,@len(%n))
                %n = @BINARY(DWORD,%o)%n
                %z = @val(@substr(%l,1,4))
                %A = @lib(crypt32,CryptBinaryToStringA,BOOL:,INT:@Addr("%n"),INT:%z,INT:%4,NIL:,INT:@Addr("%l"))
                %R = @fill(@Val(@substr(%l,1,4)),,Z)
                %A = @lib(crypt32,CryptBinaryToStringA,BOOL:,INT:@Addr("%n"),INT:%z,INT:%4,INT:@Addr("%R"),INT:@Addr("%l"))
              #End
              #%R = @substr(%R,1,@val(%l))
              If @Equal(%4,%%CRYPT_STRING_BASE64)
                %R = @Adjust(%R)
              End
            Else
              Warn Error $@hex(@lib(kernel32,GetLastError,INT:),8) returning value
            End
          Else
            #Decrypt data.
            %t = %3
            %l = @BINARY(DWORD,0)
            %y = @BINARY(DWORD,0)
            If @Equal(%4,%%CRYPT_STRING_HEX)
              %t = @Trim(%t)
            End
            #If @equal(%4,%%CRYPT_STRING_BINARY)
            #  %A = 1
            #Else
              %A = @lib(crypt32,CryptStringToBinaryA,BOOL:,INT:@Addr("%t"),INT:@len(%t),INT:%4,NIL:,INT:@Addr("%l"),NIL:,INT:@Addr("%y"))
            #End
            If %A
              #If @equal(%4,%%CRYPT_STRING_BINARY)
              #  %A = 1
              #  %n = %t
              #Else
                %n = @fill(@val(@substr(%l,1,4)),,Z)
                %A = @lib(crypt32,CryptStringToBinaryA,BOOL:,INT:@Addr("%t"),INT:@len(%t),INT:%4,INT:@Addr("%n"),INT:@Addr("%l"),NIL:,INT:@Addr("%y"))
              #End
              If %A
                %%blength =
                %%stsize = @val(@substr(%l,1,4))
                %o = @diff(%%stsize,4)
                If @Greater(%o,1000)
                  %%blength = @diff(1000,@mod(1000,%%ENCRYPT_BLOCK_SIZE))
                Else
                  #%%modo = @mod(%o,%%ENCRYPT_BLOCK_SIZE)
                  #Info @diff(%o,%%modo)
                  %%blength = @diff(%o,@mod(%o,%%ENCRYPT_BLOCK_SIZE))
                End
               
                If @Greater(%%ENCRYPT_BLOCK_SIZE,1)
                  %%length = @sum(%%blength,%%ENCRYPT_BLOCK_SIZE)
                Else
                  %%length = %%blength
                End
                %%iterations = @fround(@fdiv(%o,%%blength))               
               
                %%orgsize = @val(@substr(%n,1,4))
                %t = @strdel(%n,1,4)
                #Info %%orgsize@CR()%o@CR()%%stsize
                # Info @len(%3)@CR()length is %%length@CR()block length is %%blocklength
                %n =
                %c = 1
               
                %%cnt = 0
                %d = 0
                %%cntlength = %%blength
                Repeat
                  if @greater(%%cntlength,%o)
                    %%stsize = @succ(@diff(%o,%c))
                    %n = @substr(%t,%c,%o)
                    #Info @len(%n)
                  Else
                    %%stsize = %%blength
                    %n = @substr(%t,%c,@sum(%c,@pred(%%blength)))
                  End
                  If @less(%%stsize,%%blength)
                   %n = %n@fill(@diff(%%blength,%%stsize),,Z)
                  End
                  # %d = 1
                  # %l = @BINARY(DWORD,%%blength)
                  #Else
                   %l = @BINARY(DWORD,%%blength)
                  #End
                  #Info @len(%n)@CR()length is %%length@CR()block length is %%blocklength
                 
                  #If @Equal(%%cnt,@pred(%%iterations))
                  #  %%eof = 1
                  #End
                  #%A = @lib(advapi32,CryptEncrypt,INT:,INT:%k,INT:0,INT:0,INT:0,NIL:,INT:@Addr("%l"),INT:%%length)           
                  %A = @lib(advapi32,CryptDecrypt,BOOL:,INT:%k,INT:0,INT:%d,INT:0,INT:@Addr("%n"),INT:@addr("%l"))
                  If @Null(%A)
                    Warn Error $@hex(@lib(kernel32,GetLastError,INT:),8) returning value
                    %%cnt = %%iterations
                  End                 
                  If @Greater(@len(%R),0)
                    %R = %R%n
                  Else
                    %R = %n
                  End
                  %c = @sum(%c,%%blength)
                  %%cntlength = @sum(%%cntlength,%%blength)
                  %%cnt = @succ(%%cnt)
                Until @Equal(%%cnt,@succ(%%iterations))
               
                #%t = @substr(%n,1,%%length)
                #%l = @BINARY(DWORD,%%length)
                #%A = @lib(advapi32,CryptDecrypt,INT:,INT:%k,INT:0,INT:0,INT:0,INT:@Addr("%n"),INT:@addr("%l"))
                #Info A = %A
                If %A
                  #%l = @val(%l)
                  %R = @substr(%R,1,%%orgsize)
                  # copy %n to %r the user will have to delete the extra bytes if any.
                Else
                  #Warn Error $@hex(@lib(kernel32,GetLastError,INT:),8) returning value
                  %R =
                End
              End
            End
          End
          #Destroy session key.
          If @unequal(%k,0)
            %A = @lib(advapi32,CryptDestroyKey,INT:,INT:%k)
          End

          #Destroy hash object.
          If @unequal(%h,0)
            %A = @lib(advapi32,CryptDestroyHash,INT:,INT:%h)
          End
        Else
          Warn Error $@hex(@lib(kernel32,GetLastError,INT:),8) deriving a session key
        End
      Else
        Warn Error $@hex(@lib(kernel32,GetLastError,INT:),8) hashing the password.
      End
    Else
      Warn Error $@hex(@lib(kernel32,GetLastError,INT:),8) getting handle to a hash object.
    End
  End
  %%CSPRet = %R
Exit %%CSPRet



Below is an example that uses this DSU.

Code:

#---------------------------------------------------------------------------------------#
#                                                                                       #
# Description: This demo is a simple example using the VDSCryptoAPI.dsu to              #
#              Encrypt string data with AES 256 encryption standard.                    #
#                                                                                       #
# Copyright: Copyright © 2009 DragonSphere Software All Rights Reserved.                #
#                                                                                       #
#---------------------------------------------------------------------------------------#

# To use include the VDSCryptoAPI.dsu VDS unit
OPTION DECIMALSEP,.
#INCLUDE VDSCryptoAPI.dsc
# next define the commands and functions in the dsu above
#DEFINE COMMAND,CSPDISCONNECT
#DEFINE FUNCTION,CSPCONNECT,CSPDETAILS,CSPENCRYPTDATA,CSPDECRYPTDATA


:DEMO
Title VDSCryptoAPI Demo

# Connect to CSP
# Argument1 = The name of the key store container.  If not defined VDSCryptoAPI will use the users default container
# which is probably not what you want.
#
# Argument2 = This determines the encryption algorythm VDSCryptoAPI uses.
#             Can be one of the following.
#             RC4 = 128 bit RSA_RC4  This is the default if not specified.
#             AES = 256 bit RSA_AES
#
# Returns a connection handle to the key store container else returns VDS NULL
%%hCryptProv = @CSPConnect(VDSCryptoAPI Key Container,AES)
If %%hCryptProv
  # To get details about the provider,container,provider version call @CSPDetails() function
  # Argument1 = Connection Handle returned by @CSPConnect() function.
  #
  # Argument2 = Flags that determine the type of details below
  #             P = Crypto provider name
  #             C = Container name; If all went well with the
  #                 connection this should match the container
  #                 name specified in Argument1 of @CSPConnect() function above.
  #             V = Version of the Crypto provider being used.
  PARSE "%%Provider;%%Container;%%Version",@CSPDetails(%%hCryptProv,PCV)
  Info %%hCryptProv is the handle to the %%Container@CR()Using the %%Provider v@SubStr(%%Version,7,7).@SubStr(%%Version,8,9)
 
  %%Password = @Input(Please enter a password,,PASSWORD)
  If @Ok()
    #%%Source_lst = @New(LIST)
    #List LoadFile,%%Source_lst,@Path(%0)VDSCryptoAPI.dsc
    # To encrypt data Call @CSPEncryptData() function.
    # Argument1 = Connection Handle returned by @CSPConnect() function.
    #
    # Argument2 = User defined word or pharse of any length. This is required at this time.
    #
    # Argument3 = This is the data to be encrypted.  This can be anything that VDS can read into a variable.
    #             including binary data from a file.
    #
    # Argument4 = determines the format of the return value. Can be one of the following values.
    #             BASE64 = The encrypted data is base64 encoded upon return. This is the default.
    #             HEX = Returns each byte as two digit hex like the values below. Similar to a hex editor format.
    #             BINARY = No atempt is made to convert the data.
    #
    # Returns the data in Argument3 encrypted using the algorythm specified in
    %S = This is a demo of encrypting simple string data with the VDSCryptoAPI.dsu
    %S = @CSPEncryptData(%%hCryptProv,%%Password,%S,BASE64)
    Info Encrypted string@CR()%S
    %S = @CSPDecryptData(%%hCryptProv,%%Password,%S,BASE64)
    Info Original string@CR()%S
  End
  # Disconnect CSP
  CSPDisconnect %%hCryptProv,VDSCryptoAPI Key Container
  If @OK()
    Info Crypto Provider disconnected.
  End
End
Stop


Enjoy... Smile

_________________
Home of

Give VDS a new purpose!


Last edited by vdsalchemist on Sat Dec 26, 2009 4:48 pm; edited 1 time in total
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
Aslan
Valued Contributor
Valued Contributor


Joined: 31 May 2001
Posts: 589
Location: Memphis, TN USA

PostPosted: Fri Dec 25, 2009 7:49 pm    Post subject: Reply with quote

Thanks vdsalchemist:-)

I get a Non-Numeric value error at line 331 in the VDSCryptoAPI.dsc when using your example.
Offending line:
Code:
%%iterations = @fround(@fdiv(%l,%%length))


I'm using VDS 6 on Win7 x64.

You did say it was incomplete so I'm trying to rummage through it. Maybe it's because I'm on Win7.

I will try it with an earlier version of Windows when I can.


But for now it's time to go indulge in some gluttony Outta Here
Back to top
View user's profile Send private message Send e-mail
vdsalchemist
Admin Team


Joined: 23 Oct 2001
Posts: 1448
Location: Florida, USA

PostPosted: Sat Dec 26, 2009 5:06 pm    Post subject: Reply with quote

Aslan, Sorry I had posted the wrong version of the DSU. I updated the code above with the correct version of the DSU. Enjoy.
_________________
Home of

Give VDS a new purpose!
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
Aslan
Valued Contributor
Valued Contributor


Joined: 31 May 2001
Posts: 589
Location: Memphis, TN USA

PostPosted: Sat Dec 26, 2009 5:14 pm    Post subject: Reply with quote

Ahh.... Very Kool vdsalchemist Cool
This saves me alot of work Very Happy
Back to top
View user's profile Send private message Send e-mail
vdsalchemist
Admin Team


Joined: 23 Oct 2001
Posts: 1448
Location: Florida, USA

PostPosted: Sat Dec 26, 2009 5:20 pm    Post subject: Reply with quote

Did it work? I have not tested this code on Windows 7. I have tested it on Vista, Windows XP, and Wine in Ubuntu but not Windows 7. Also I have not tested under a 64bit OS so if someone would be so kind as to test this code under 64bit that would be appreciated. I have other demos but would like to wait until I can make this work with keys/key files instead of just pass phrases before releasing them.
_________________
Home of

Give VDS a new purpose!
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
Aslan
Valued Contributor
Valued Contributor


Joined: 31 May 2001
Posts: 589
Location: Memphis, TN USA

PostPosted: Sat Dec 26, 2009 9:27 pm    Post subject: Reply with quote

Yes, it worked on Win7 x64.
Quote:
Using Microsoft Enhanced RSA and AES Cryptographic Provider v2.00

Keep in mind that my testing has been limited to a PC that has VDS6 installed in compatibility mode. I haven't tried it on a system that this was redistributed to... Yet.
I will have a distribution pool available to me next week. I will do more testing then.

Thanks again for your hard work Worship

P.S. For others reading this post VDS6 is required with this code as it is currently written.
Back to top
View user's profile Send private message Send e-mail
vdsalchemist
Admin Team


Joined: 23 Oct 2001
Posts: 1448
Location: Florida, USA

PostPosted: Sat Dec 26, 2009 11:59 pm    Post subject: Reply with quote

Yes VDS 6 is required for this to work however the final version will have this limitation removed. Since using the MS Crypto API is not an easy thing to program I used VDS 6 specific commands/functions to make sure my code is correct for simplicities sake.
_________________
Home of

Give VDS a new purpose!
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
vdsalchemist
Admin Team


Joined: 23 Oct 2001
Posts: 1448
Location: Florida, USA

PostPosted: Mon Jan 25, 2010 8:08 pm    Post subject: Reply with quote

Aslan, Below is the 2nd demo that shows you how to encrypt and decrypt a binary file. The demo encrypts and decrypts my gadgetX.dll. Once decrypted it then loads the DLL to show that the file is intact.

Code:

#
# This demo is a simple example using the VDSCryptoAPI.dsu to
# Encrypt string data with AES 256 encryption standard.

# Copyright: Copyright © 2009 DragonSphere Software All Rights Reserved.

# To use include the VDSCryptoAPI.dsu VDS unit
#INCLUDE VDSCryptoAPI.dsc
# next define the commands and functions in the dsu above
#DEFINE COMMAND,CSPDISCONNECT
#DEFINE FUNCTION,CSPCONNECT,CSPDETAILS,CSPENCRYPTDATA,CSPDECRYPTDATA

:DEMO
Title VDSCryptoAPI Demo 2

# Connect to CSP
# Argument1 = The name of the key store container.  If not defined VDSCryptoAPI will use the users default container
# which is probably not what you want.
#
# Argument2 = This determines the encryption algorythm VDSCryptoAPI uses.
#             Can be one of the following.
#             RC4 = 128 bit RSA_RC4  This is the default if not specified.
#             AES = 256 bit RSA_AES
#
# Returns a connection handle to the key store container else returns VDS NULL
%%hCryptProv = @CSPConnect(VDSCryptoAPI Key Container,AES)
If %%hCryptProv
  # To get details about the provider,container,provider version call @CSPDetails() function
  # Argument1 = Connection Handle returned by @CSPConnect() function.
  #
  # Argument2 = Flags that determine the type of details below
  #             P = Crypto provider name
  #             C = Container name; If all went well with the
  #                 connection this should match the container
  #                 name specified in Argument1 of @CSPConnect() function above.
  #             V = Version of the Crypto provider being used.
  PARSE "%%Provider;%%Container;%%Version",@CSPDetails(%%hCryptProv,PCV)
  Info %%hCryptProv is the handle to the %%Container@CR()Using the %%Provider v@SubStr(%%Version,7,7).@SubStr(%%Version,8,9)
 
  %%Password = @Input(Please enter a password,,PASSWORD)
  If @Ok()
    # If you have ran this example once before we need to delete the files that will be created
    File delete,@Path(%0)gadgetx_dll.enc
    File delete,@Path(%0)new_gadgetx.dll
   
    %%Fsize = @File(@Path(%0)gadgetx.dll,Z) 
    %%SourceFile_handle = @New(FILE,@Path(%0)gadgetx.dll,R)
    %%DestFile_handle = @New(FILE,@Path(%0)gadgetx_dll.enc,W)
    # To encrypt data Call @CSPEncryptData() function.
    # Argument1 = Connection Handle returned by @CSPConnect() function.
    #
    # Argument2 = User defined word or pharse of any length. This is required at this time.
    #
    # Argument3 = This is the data to be encrypted.  This can be anything that VDS can read into a variable.
    #             including binary data from a file.
    #
    # Argument4 = determines the format of the return value. Can be one of the following values.
    #             BASE64 = The encrypted data is base64 encoded upon return. This is the default.
    #             HEX = Returns each byte as two digit hex like the values below. Similar to a hex editor format.
    #             BINARY = No atempt is made to convert the data.
    #
    # Returns the data in Argument3 encrypted using the algorythm specified in

    %%Data = @Read(%%SourceFile_handle,%%Fsize)
   
    Info I have read all the data from the source file.
    %S = @CSPEncryptData(%%hCryptProv,%%Password,%%Data,BINARY)
    Info Source file is encrypted.
    Write %%DestFile_handle,%S
    Info Destination file is written to.
    CLOSEFILE %%SourceFile_handle
    CLOSEFILE %%DestFile_handle
   
    # Now we will attempt to decrypt the encrypted file to a new file
    %%EncFsize = @File(@Path(%0)gadgetx_dll.enc,Z) 
    %%SourceFile_handle = @New(FILE,@Path(%0)gadgetx_dll.enc,R)
    %%DestFile_handle = @New(FILE,@Path(%0)new_gadgetx.dll,W)

    %%Data = @Read(%%SourceFile_handle,%%EncFsize)
   
    Info I have read all the data from the source file
    %S = @CSPDecryptData(%%hCryptProv,%%Password,%%Data,BINARY)
    Info Source file is decrypted.
    Write %%DestFile_handle,%S
    Info Destination file is written to.
    CLOSEFILE %%SourceFile_handle
    CLOSEFILE %%DestFile_handle
    Info The original and new file sizes should be identical@CR()Original FileSize %%Fsize@CR()New FileSize @File(@Path(%0)new_gadgetx.dll,Z)
   
    External @Path(%0)new_gadgetx.dll,6
    #DEFINE FUNCTION,GADGETX
    %A = @GadgetX(Version)
    Info Output from the GadgetX version command below@CR()@CR()%A@CR()
   
  End
  # Disconnect CSP
  CSPDisconnect %%hCryptProv,VDSCryptoAPI
  If @OK()
    Info Crypto Provider disconnected.
  End
End
Stop


Enjoy....

This should work with Text files as well. Also it shows an easy way to use the new VDS 6 I/O commands/functions to read/write files. Large files you will want to read/write in chunks and append the data to a single variable then send that variable to the encryption function or you can send small chunks to the encription function and try to stich it back together upon output. Either way does not matter.

_________________
Home of

Give VDS a new purpose!
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
vdsalchemist
Admin Team


Joined: 23 Oct 2001
Posts: 1448
Location: Florida, USA

PostPosted: Tue Jan 26, 2010 2:56 pm    Post subject: Reply with quote

In reference to Chris's last question in the following thread http://forum.vdsworld.com/viewtopic.php?t=4977&postdays=0&postorder=asc&start=15

I did not think there was a limit to the length of the passphrase?

Chris,
How long is the passphrase. There is still a lot I don't know about how the Crypto API works so this is all still very much beta but should be stable with resonable passphrases of about 10 words or so. I personally would not make it that long since you would not get any better encryption than what you would get with a shorter passphrase that varies case, numbers, and special characters. Also you should not use binary characters only characters that work in simple edit boxes after all I am using VDS here to handle these things. Wink As for re-entrant... are you disconnecting from the CSP before you try to encrypt another string or are you staying connected?

_________________
Home of

Give VDS a new purpose!
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
vdsalchemist
Admin Team


Joined: 23 Oct 2001
Posts: 1448
Location: Florida, USA

PostPosted: Tue Jan 26, 2010 4:18 pm    Post subject: Reply with quote

Everyone, Just so you know this encryption DSU was an exercise for me which had the following goals in mind.



  1. Can VDS use the built in Windows API's for encryption.
  2. Learn how the Windows encryption API's work.
  3. Can I make it simple to use.
  4. Must be made to work with strings and/or files.
  5. Give the VDS community high end encryption without the need for a VDS DLL to minimize 'man in the middle' and/or 'brute force' attacks.


At this point, short of you placing the pass phrase in the code and someone extracting the VDS code the last item above is achieved. To keep the pass phrase out of the VDS code ask the user for a pass phrase. Then don't save the user's pass phrase anywhere. This means that if the user losses their pass phrase the data is lost forever so make sure you warn the user. If your application is a background application you could use environmental information (ie... UserName, MachineName, Size of C drive, Time of day, or some combination of these). This means that the data would not be able to be transfered to another machine. Note this encryption DSU is only as safe as you and Microsoft's encryption API's are so your mileage may vary.

_________________
Home of

Give VDS a new purpose!
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
LiquidCode
Moderator Team


Joined: 05 Dec 2000
Posts: 1753
Location: Space and Time

PostPosted: Tue Jan 26, 2010 9:01 pm    Post subject: Reply with quote

The password I used is only 9 letters and numbers. If I use a 4 letter PW it seems to work ok. I do stay connected until I am finished will all the encryption/decryption is done. I connect once at start up to read the PW and text. Then connect again on exit to encrypt.
_________________
Chris
Http://theblindhouse.com
Back to top
View user's profile Send private message Send e-mail Visit poster's website
vdsalchemist
Admin Team


Joined: 23 Oct 2001
Posts: 1448
Location: Florida, USA

PostPosted: Wed Jan 27, 2010 3:00 am    Post subject: Reply with quote

You should connect before you try to encrypt anything then stay connected until you are finished encrypting or decrypting what you want. I usually connect to the CSP when the program starts then disconnect when the program ends. I tried it with a password of 9 characters/numbers and it worked for me. The only thing I can think of is that you may be trimming the encrypted base64 data. Be careful not to trim any characters from the return of the @CSPEncryptData() function this could cause the last 64 byte chunk to be truncated remember this is base 64 so the strings are base64 decoded in 64 byte chunks at a time and if you truncate the data then you will miss the last part of it. Also if I could get some samples that would help me fix the problem quicker then just guessing at what is going on.
_________________
Home of

Give VDS a new purpose!
Back to top
View user's profile Send private message Visit poster's website AIM Address Yahoo Messenger MSN Messenger
Aslan
Valued Contributor
Valued Contributor


Joined: 31 May 2001
Posts: 589
Location: Memphis, TN USA

PostPosted: Wed Jan 27, 2010 4:02 am    Post subject: Reply with quote

Again nice work!

Originally, just the string encryption was all I needed but your timing was perfect on this one as I just started a new project that will require file encryption.

Thanks again Oh Great One Worship


Chris, I'm not sure why you're having an issue with this DSU. It has worked flawlessly for me for almost two months now on verying Windows OSs. Some of my beta users are using an actual phrase instead of just a password.
Maybe if you would be willing to post just the encryption/decryption part of your code we could take a look at it. Just a thought even though I know you'll probably figure it out eventually.
Back to top
View user's profile Send private message Send e-mail
LiquidCode
Moderator Team


Joined: 05 Dec 2000
Posts: 1753
Location: Space and Time

PostPosted: Wed Jan 27, 2010 7:50 pm    Post subject: Reply with quote

I think I am using the @trim() function. That may be why it's not working. I'll take a look at the code today and I'll get back to you.
_________________
Chris
Http://theblindhouse.com
Back to top
View user's profile Send private message Send e-mail Visit poster's website
Display posts from previous:   
Post new topic   Reply to topic    forum.vdsworld.com Forum Index -> General Help All times are GMT
Goto page 1, 2  Next
Page 1 of 2

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You can attach files in this forum
You can download files in this forum

Twitter@vdsworld       RSS

Powered by phpBB © 2001, 2005 phpBB Group