Sunday, 30 July 2017

Cryptography - VBA code for Wikipedia's RSA example

So, following on from studying some cryptography I can give some VBA code which implements RSA or at least the example given on the RSA Wikipedia article. So the two primes p and q are given; calculating n is easy (multiply); we can use worksheet function lcm for the totient;e is given;I hunted around for some logic for "module multiplicative inverse" and finally we have the components for the private and public keys.

Also shown is some code to encrypt a message (very short one character "A" represented by ASCII 65) and decrypt it back to the original. To encrypt a larger message needs an arithmetic vehicle larger that that available in VBA, you'll see I'm declaring variables as Currency to get as many bits as possible but even this has limits when raising a number to a very high power exponentional.

Anyway, simple version that allows VBA programmer to step through the wikipedia example is given here ...

Option Explicit
Option Private Module

Private Type udtPublicKey
    n As Currency
    e As Currency
End Type

Private Type udtPrivateKey
    n As Currency
    d As Currency
End Type

'***************************************************
'               .__
'  _____ _____  |__| ____
' /     \\__  \ |  |/    \
'|  Y Y  \/ __ \|  |   |  \
'|__|_|  (____  /__|___|  /
'      \/     \/        \/
'***************************************************

Private Sub Main()

    Dim p As Currency
    Dim q As Currency
    Dim n As Currency
    Dim lambda_n As Currency
    Dim e As Currency
    Dim d As Currency


    p = 61
    q = 53
    n = p * q
    lambda_n = Application.Lcm(p - 1, q - 1)
    e = 17
    Debug.Assert IsCoPrime(e, lambda_n)
    
    d = ModularMultiplicativeInverse(e, lambda_n)
    Debug.Assert e <> d

    Dim uPrivate As udtPrivateKey
    uPrivate.d = d
    uPrivate.n = n
    
    Dim uPublic As udtPublicKey
    uPublic.e = e
    uPublic.n = n
        
    '* m is the message to encrypt, it needs to be a number
    '* 65 is ASCII for "A"
    Dim m As Currency
    m = 65
    
    '* c is the encrypted message
    Dim c As Currency
    c = Encrypt(m, uPublic)
    
    '* m2 is the decrypted message
    Dim m2 As Currency
    m2 = Decrypt(c, uPrivate)
    
    '* and the decrypted message should match the original
    Debug.Assert m2 = m
     
End Sub


Private Function Encrypt(ByVal m As Currency, _
                    ByRef uPublic As udtPublicKey) As Currency
    If m > uPublic.n Then Err.Raise vbObjectError, , _
            "#text is bigger than modulus, no way to decipher!"
    
    Dim lLoop As Long
    Dim lResult As Currency
    lResult = 1
    For lLoop = 1 To uPublic.e
    
        lResult = ((lResult Mod uPublic.n) * (m Mod uPublic.n)) Mod uPublic.n
    Next lLoop
    Encrypt = lResult
End Function

Private Function Decrypt(ByVal c As Currency, _
                    ByRef uPrivate As udtPrivateKey) As Currency
    If c > uPrivate.n Then Err.Raise vbObjectError, , _
            "#text is bigger than modulus, no way to decipher!"
    Dim lLoop As Long
    Dim lResult As Currency
    lResult = 1
    For lLoop = 1 To uPrivate.d
        lResult = ((lResult Mod uPrivate.n) * (c Mod uPrivate.n)) Mod uPrivate.n
    Next lLoop

    
    Decrypt = lResult
End Function

Private Function IsCoPrime(ByVal a As Currency, ByVal b As Currency) As Boolean
    IsCoPrime = (Application.Gcd(a, b) = 1)
End Function

Private Function ModularMultiplicativeInverse(ByVal e As Currency, _
                    ByVal lambda_n As Currency)
    Dim lLoop As Currency
    For lLoop = 1 To lambda_n
        If lLoop <> e Then
            Dim lComp As Currency
            lComp = lLoop * e Mod lambda_n
            If lComp = 1 Then
                ModularMultiplicativeInverse = lLoop
                Exit Function
            End If
        End If
    Next
SingleExit:
End Function




Friday, 14 July 2017

Cryptography - Glossary

Cryptography is a massive subject and there is tons of stuff on the Internet. However, I'd love a little notebook of terms. So here I will begin my own personal list. I'll use HTML anchors to each entry for extras URL granularity.

AD CS abbr. Active Directory Certificate Services, provides customizable services for creating and managing public key certificates used in software security systems employing public key technologies.

AES abbr. Advanced Encryption Standard, also referenced as Rijndael .

affine cipher n. a type of monoalphabetic substitution cipher. Each letter is enciphered with the function (ax + b) mod 26, where b is the magnitude of the shift.

alphabet n. a collection of symbols, also referred to as characters.

ANSI abbr. American National Standards Institute is a private non-profit organization that oversees the development of voluntary consensus standards for products, services, processes, systems, and personnel in the United States.

assymetric adj. describes cryptosystems where the encryption key differs from decryption key.

BF abbr. Blowfish, is a symmetric block cipher. (USA)

bijection n. In mathematics, a bijection, bijective function or one-to-one correspondence is a function between the elements of two sets, where each element of one set is paired with exactly one element of the other set, and each element of the other set is paired with exactly one element of the first set. There are no unpaired elements.

bit n. a character 0 or 1 of the binary alphabet.

block cipher n. a cipher which acts on the plaintext in blocks of symbols.

CA abbr. certification authority.

Camellia n. Camellia (cipher), is a symmetric key block cipher.

Cast n. CAST-128, is a symmetric key block cipher.

CBC abbr. cipher block chaining is a mode of operation for a block cipher.

certification authority n. a certificate authority or certification authority (CA) is an entity that issues digital certificates.

Caesar cipher n. a translation cipher for which b=3, used by Julius Caesar.

CFB abbr. Ciphertext Feedback is a mode of operation for a block cipher.

character n. an element of an alphabet.

cipher n. 1. a map from a space of plaintext to a space of ciphertext.
               2. a pair of algorithms, one for encryption and one for decryption.

ciphertext n. the disguised message.

CMVP abbr. cryptographic module validation program.

CMS abbr. cryptographic message syntax is the IETF's standard for cryptographically protected messages.

CNG abbr. Windows Cryptography API: Next Generation (CNG) replaces CryptoAPI 1.0 as the recommended Windows API cryptographic suite.

coprime adj. No common factors other than 1. Also called "relatively prime" or "mutually prime".

CRL abbr. certificate revocation list.

cryptanalysis n. the science (complementary to cryptography) concerned with the methods to defeat cryptographic techniques.

cryptographic hash function n. a special class of hash function that has certain properties which make it suitable for use in cryptography.

cryptographic nonce n. In cryptography, a nonce is an arbitrary number that may only be used once.

cryptography n. the study of mathematical techniques for all aspects of information security.

cryptology n. the study of cryptography and cryptanaylsis.

CSP abbr.Cryptographic Service Providers

CTR abbr. Counter-mode encryption, a block cipher mode of operation that uses incrementing IV counter for the key stream source.

cryptosystem n.
1. a suite of cryptographic algorithms needed to implement a particular security service, most commonly for achieving confidentiality (encryption).
2. (Mathematics) can formally be defined by a collection of sets, "plaintext space","ciphertext space","key space","set of encryption functions","set of decryption functions". See Cryptosystem.

decipher v.tr. to convert ciphertext into plaintext.

decode v.tr. to convert the encoded message back to its original alphabet and original form.

DRBG abbr. Deterministic Random Bit Generators

DES abbr. Data Encryption Standard is a symmetric-key block cipher published by the NIST.

digital certificate n. A digital certificate uses public-key cryptography to sign data and to verify the integrity of the certificate itself. Public key cryptography is a system based on pairs of keys called public key and private key.

DH abbr. Diffie Hellman.

DSA abbr. Digital Signature Algorithm.

ECB abbr. Electronic Code Book is a mode of operation for a block cipher.

ECC abbr. elliptic curve cryptography.

ECDH abbr. elliptic curve Diffie–Hellman , an ECC algorithm endorsed by NIST for key exchange.

ECDSA abbr. Elliptic Curve Digital Signature Algorithm , an ECC algorithm endorsed by NIST for digital signature.

EDE abbr. encrypt decrypt encrypt.

EFS abbr. Encrypting File System on Microsoft Windows is a feature introduced in version 3.0 of NTFS[1] that provides filesystem-level encryption.

elliptic curve cryptography n. is an approach to public-key cryptography based on the algebraic structure of elliptic curves over finite fields. ECC requires smaller keys compared to non-ECC cryptography (based on plain Galois fields) to provide equivalent security.

encipher v.tr. to convert plaintext into ciphertext.

encode v.tr. to convert a message into a representation in a standard alphabet, such as to the alphabet {A, . . . , Z} or to numerical alphabet.

encryption n. the process of disguising a message so as to hide the information it contains; this process can include both encoding and enciphering .

FIPS abbr. Federal Information Processing Standard.

FIPS 140-2 Publication 140-2, (FIPS PUB 140-2),[1][2] is a U.S. government computer security standard used to approve cryptographic modules. The title is Security Requirements for Cryptographic Modules.

GCM abbr. Galois Counter Mode is an efficient and performant mode of operation for symmetric key cryptographic block ciphers.

GMAC abbr. Galois Message Authentication Code, see GCM.

GCD n. greatest common divisor.

hash function n. any function that can be used to map data of arbitrary size to data of fixed size.

HMAC n. the Keyed-Hash Message Authentication Code (HMAC)

IDEA n. International Data Encryption Algorithm is a symmetric-key block cipher

IETF abbr. Internet Engineering Task Force.

injection n. (Mathematics) a one-to-one mapping.

injective adj. (Mathematics) of the nature of or relating to an injection or one-to-one mapping. See Injective function.

IPSec abbr. Internet Protocol security (IPSec) is a framework of open standards for helping to ensure private, secure communications over Internet Protocol (IP) networks through the use of cryptographic security services.

IV abbr. Initialization vector, also call "salt","nonce" (number used once), used to ensure uniqueness of the key stream.

KAT abbr. Known Answer Test.

Kerboros n. is a computer network authentication protocol that builds on symmetric key cryptography and optionally may use public-key cryptography during certain phases of authentication.

keystream n. a stream of random or pseudorandom characters that are combined with a plaintext message to produce an encrypted message (the ciphertext).

MAC abbr. Message Authentication Code sometimes known as a tag, is a short piece of information used to authenticate a message—in other words, to confirm that the message came from the stated sender (its authenticity) and has not been changed.

message digest n. a cryptographic hash function containing a string of digits created by a one-way hashing formula.

MD5 abbr. a message digest. MD5 is considered (by some) essentially "cryptographically broken and unsuitable for further use".

MIC abbr. Message Integrity Code, substitute for MAC and sometimes message digest.

NIST abbr. National Institute of Standards and Technology (USA)

NSA abbr. National Security Agency. (USA)

OAEP abbr. Optimal asymmetric encryption padding is a padding scheme often used together with RSA encryption.

OCSP abbr. Online Certificate Status Protocol

OFB abbr. output feedback is a mode of operation for a block cipher.

OpenSSL OpenSSL is a general purpose cryptography library that provides an open source implementation of the Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols.

Passphrase n. A passphrase is a sequence of words or other text used to control access to a computer system, program or data. A passphrase is similar to a password in usage, but is generally longer for added security.

PEM abbr. Privacy-enhanced Electronic Mail. PEM is a de facto file format for storing and sending cryptography keys, certificates, and other data, based on a set of 1993 IETF standards defining "privacy-enhanced mail.".

permute v. submit to a process of alteration, rearrangement, or permutation.

PKCS abbr. Public-Key Cryptography Standards

PKI abbr. Public Key Infrastructure (PKI) is a set of roles, policies, and procedures needed to create, manage, distribute, use, store, and revoke digital certificates and manage public-key encryption.

plaintext n. the message to be transmitted or stored.

post-quantum cryptography n. refers to cryptographic algorithms (usually public-key algorithms) that are thought to be secure against an attack by a quantum computer.

protocol n. an algorithm, defined by a sequence of steps, precisely specifying the actions of multiple parties in order to achieve an objective.

public key n. A public key is created in public key encryption cryptography that uses asymmetric-key encryption algorithms. Public keys are used to convert a message into an unreadable format. Decryption is carried out using a different, but matching, private key. Public and private keys are paired to enable secure communication.

RC2 n. RC2 (from Ron's Code) is a symmetric-key block cipher.

Rijndael n. Portmanteau of Belgian cryptographers Vincent Rijmen and Joan Daemen and a synonym for AES.

RIPEMD abbr. RACE Integrity Primitives Evaluation Message Digest.

RSA abbr. RSA is one of the first practical public-key cryptosystems and is widely used for secure data transmission. RSA is made of the initial letters of the surnames of Ron Rivest, Adi Shamir, and Leonard Adleman.

Salt n. In cryptography, a salt is random data that is used as an additional input to a one-way function that "hashes" a password or passphrase. Salts are closely related to the concept of nonce. The primary function of salts is to defend against dictionary attacks or against its hashed equivalent, a pre-computed rainbow table attack.

SEED abbr. SEED is a block cipher developed by South Korea.

SHA abbr. secure hash algorithm (SHA) .

S/MIME abbr. Secure/Multipurpose Internet Mail Extensions (S/MIME).

SSL abbr. SSL (Secure Sockets Layer) is the standard security technology for establishing an encrypted link between a web server and a browser. This link ensures that all data passed between the web server and browsers remain private and integral.

symmetric adj. describes cryptosystems where the encryption key is the same as the decryption key.

stream cipher n. a cipher which acts on the plaintext one symbol at a time.

string n. a finite sequence of characters in some alphabet.

substitution cipher n. a stream cipher which acts on the plaintext by making a substitution of the characters with elements of a new alphabet or by a permutation of the characters in the plaintext alphabet.

suite B n. is a set of cryptographic algorithms promulgated by the National Security Agency as part of its Cryptographic Modernization Program.

TLS abbr. TLS (Transport Layer Security) is a successor to Secure Sockets Layer protocol, or SSL. TLS provides secure communications on the Internet for such things as e-mail, Internet faxing, and other data transfers. There are slight differences between SSL 3.0 and TLS 1.0, but the protocol remains substantially the same.

TPM abbr. Trusted Platform Module is an international standard for a secure cryptoprocessor.

translation cipher n. an affine cipher for which a=1.

transposition cipher n. a block cipher which acts on the plaintext by permuting the positions of the characters in the plaintext.

Triple DES n. a symmetric-key block cipher, which applies the Data Encryption Standard (DES) cipher algorithm three times to each data block.

TRNG abbr. True Random Number Generator, based on a pure source of entropy ("noise").

X.509 abbr. X.509 is a standard that defines the format of public key certificates.




Links


Introduction to Cryptography

Handbook of Applied Cryptography (HAC)

Maths is fun - injective-surjective-bijective

RSA Laboritories : WHAT IS EXHAUSTIVE KEY SEARCH?

Data Encryption Standard

OpenSSL Cookbook Ivan Ristić Free Chapters

NIST Digital Signatures

Basic Blockchain Programming - keys as property

CodeGuru: Windows Cryptography API: Next Generation (CNG)

Windows Dev Center: Cryptography

Windows Dev Center: Cryptography API: Next Generation

MSDN: .NET Framework: System.Security.Cryptography

TechTarget SearchSecurity

How to choose an AES encryption mode (CBC ECB CTR OCB CFB)?

crackstation.net


Thursday, 13 July 2017

Sharepoint Excel Services for server-side Excel calculations

For many years Excel was limited to client-side, i.e. desktop installation, operation. However, I did work on many projects where we launched an instance of Excel on a server as a calculation agent despite Microsoft recommending against because this option is fraught with unforeseen consequences. For example, message boxes get thrown but on a server there is no user to see and dismiss them. Microsoft invented Sharepoint for clients who really want to run Excel on the server.

The downsides of Sharepoint are cost, it is not cheap in itself and also it requires a Windows Server licence. If your employer is pro-Unix then this will be a deal-breaker. The other downside of Sharepoint is that your VBA code will not run and will have to be converted to C# or some other managed .NET language.

Nevertheless, the Sharepoint 'market share' of the Excel solution space will grow and a blog on Excel Development should address it.

I've yet to reach recommendations for this technology so this first blog post will solely be a collection of links for more reading.

Wikipedia is always good place to start, here is article on Excel Services
Office Support: Getting Started with Excel Services and Excel Web Access
Book: Wrox - Professional Excel Services
Technet: Overview of Excel Services in SharePoint Server 2013
Technet: Administer Excel Services in SharePoint Server 2013
safaribooksonline: Chapter 1. An Introduction to Excel Services
Technet Forums: VBA won't work for workbooks rendered in a browser from a Sharepoint server (Excel Services)
Office Dev Center: Understanding Excel Services UDFs
Office Dev Center: Walkthrough: Developing a Managed-Code UDF
MSDN: Creating Custom Solutions with Excel Services

Some sample C# code for a server-side Excel Services UDF.

// From https://dev.office.com/sharepoint/docs/general-development/step-2-creating-a-managed-code-udf
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Excel.Server.Udf;

namespace SampleUdf
{
    [UdfClass]
    public class Class1
    {
        [UdfMethod]
        public double MyDouble(double d)
        {
            return d * 9;
        }  

        [UdfMethod(IsVolatile = true)]
        public DateTime ReturnDateTimeToday()
        {
            return (DateTime.Today);
        }
    }
}


However, if you thought getting a UDF to run on both the client and the server in a unified code base would be a breeze then check out this web page which shows how to do it. It seems a major undertaking requiring C#, C++/CLI (formerly Managed C++), creating code to handle a managed Add-in and a custom shim. I expect many to be dissuaded from using SharePoint because of the complexity there but I also expect Microsoft to unify the client side and server interfaces in the future.

Whilst I have yet to reach recommendations on Sharepoint and Excel Services one has to wonder why rendering a workbook in a browser which requires a Windows Server, Sharepoint Server and Internet Information Server is better than keeping a workbook of a network file server (running on Linux) and opening in Excel. I guess the question boils down to client licences versus server licences.

Sunday, 2 July 2017

Digital Signatures - a succinct maths formula/symbolic description

I cam across this beautifully succinct description of how digital signatures work written in maths formula/symbolic terms. Original thread is here.

  1. Alice publishes her public key PK and keeps her private key K safe.
  2. Alice produces an original bitstring S.
  3. Alice computes S'=f(S, K), which is a fixed-length bitstring.
  4. Alice publishes S+S'.
  5. If Carol wants to know if Alice is in fact the author of S, all she needs to do is compute g(S, S', PK), which returns true if S is the bitstring that was signed with S' and if it was K that was used to produce the signature. Assuming that only Alice knows K, this is enough to prove Alice's authorship of S.
  6. If Bob wants to impersonate Alice, stealing S' is useless because S' can only be used to authenticate S. Stealing PK is also useless because it can only be used to authenticate, not to sign. Altering S or S' doesn't work because it will cause the authentication to fail. Bob's only option is to steal or attempt to crack K.