DigiSign
Volume Number: | | 10
|
Issue Number: | | 2
|
Column Tag: | | AOCE
|
DigiSign
Real Commercial Grade Digital Signatures For The Masses
By Pablo Calamera, Apple Computer, Inc.
Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.
About the author
Pablo is a nocturnal creature too often found coding against time in his dark and cozy crypt at Apple's R&D Center. You can reach him on either America Online or AppleLink at Calamera.
INTRODUCTION
Apple has integrated commercial grade digital signatures into the operating system as part of System 7 Pro. Specifically, DigiSign is a component of PowerTalk, the client software portion of AOCE (Apples Open Collaboration Environment). DigiSign is comprised of three parts; the Digital Signature Manager and API, Drag and Drop signing in the Finder, and the DigiSign Utility. In this article we will concentrate on the Digital Signature Manager though there may be some references to the other parts to fill things in.
WHAT IS A DIGITAL SIGNATURE?
Ill try not to go into too much gory detail here, but you should understand some of the principles involved. Let me start by telling you what a digital signature is not. It is not a graphic representation of your handwritten signature that your plop onto an electronic page. A digital signature is basically a big encrypted number that is associated with a piece of data. A digital signature serves two purposes, it uniquely identifies the individual or entity that signed the data and it assures the integrity of the data that was signed.
A digital signature can apply to an entire document or any portion of it. In terms of trust, a signature that has been successfully verified can be more trustworthy than a signed and notarized piece of paper since a digital signature can detect any alterations to the signed data and a digital signature can not be forged.
Digital signatures are based on a cryptographic technique called public key cryptography. This general concept was outlined by W. Diffie and M. Hellman in 1976. The method was improved soon afterwards by R. Rivest, A. Shamir and L. Adleman. Their scheme, known as the RSA public key crypto-system, is based on arithmetic algorithms using a pair of large prime numbers. One of these numbers is your private key which you keep a secret, while the other number is your public key. Data encrypted with the private key can only be successfully decrypted with the corresponding public key. It follows then that a successful decryption would assert the identity of the signer since only the holder of the corresponding private key could have signed the data.
The Digital Signature Manager creates what is called a full signature which contains the digital signature itself as well as a certificate set. A digital signature is an encrypted digest. The digest, a 16 byte value similar to a checksum, numerically represents the signed data and insures its integrity. The algorithm used to create the digest is MD5 and its very nearly impossible that any two sets of data that differ in any way could result in the same digest.
When a signature is created, a digest is calculated for the signed data then encrypted using the signers private key. When a signature is verified, the encrypted digest is decrypted using the signers public key. This digest is then compared against a newly calculated digest of the signed data in its current state. Any deviation in the data from when it was signed will be detected. Its important to note that the signed data itself is not encrypted only the digest is.
Verifying a digital signature further requires that the authenticity of the public key be established. The certificate set serves this purpose. The certificate set provides the public key, allows the verification of the keys authenticity, and provides the identity of the signer.
A signers public key is registered with a certifier (which for example can be your company or RSA Data Security Inc.) along with his/her identifying attributes (e.g. name, address, title etc ). This information is placed into what is called a public key certificate. This certificate is itself digitally signed by the certifier. The certifier also has a public key certificate which is in turn signed by its certifier and so on up to the root certifier which in DigiSign is the RSA commercial hierarchy root key. Verifying a digital signature then requires checking the signature for each certificate in the set for authenticity.
There are basically four types of certificates: individual certificates are for people not affiliated with any organization, employee certificates are for people within an organization, title or role certificates pertain to an organizational position, and certifier certificates for organizations that register public keys.
DIGISIGN MAKES IT EASY
In several distinct ways DigiSign makes using digital signature technology easy for the programmer and most importantly, the user.
To get a public key and certificate, an application called DigiSign Utility is provided with PowerTalk. The application creates a Signer file (which contains your private key) and an Approval Request File (for registering your public key). You send the Approval Request File to a certifier who then sends you back an Approval File. The Approval File is then incorporated with your as yet unapproved Signer. This process retrieves the certificate set necessary to make your Signer usable. A demonstration signer is included with PowerTalk so you can start programming right away and a voucher for a free certificate is in the documentation so you can get your own personal Signer.
There are eight easy to use calls that do it all for you from signing to verifying to showing the user who signed the data. To use any of the Digital Signature Manager calls, you start by allocating a SIGContextPtr by calling SIGNewContext. Next you call SIGSignPrepare or SIGVerifyPrepare depending on the desired operation. If signing, the user will be asked to enter in the password which protects the Signers private key. In either case, you follow that with calls to SIGProcessData. SIGProcessData calculates the digest for the signature so you will make repeated calls to it until all the data is processed. Next, you call SIGSign or SIGVerify depending on the operation you are performing. And finally, you free the SIGContextPtr by calling SIGDisposeContext. If you are verifying a signature and SIGVerify returned no error, you can call SIGShowSigner to display the certificate attributes of the person who signed the data.
The Digital Signature Manager and RSAs public key cryptography toolkit (TIPEM) do all the certificate and key handling for you. All you need to do to integrate signatures into your application is; call the appropriate functions, add the supporting user interface elements (e.g. menu items and a signature icon), and handle the storing of the signature with the signed data.
A SOUND BITE YOU CAN TRUST
The sample application SoundByte demonstrates the signing and verifying operations and a simple but friendly user interface which follows Apples Human Interface Guidelines for digital signatures.
SoundBytes function in life, aside from being sample code, is to allow a user to record a sound, enter in a topic for which the sound applies, then sign both those pieces of data. By using SoundByte you cant be misquoted, have your words taken out of context, or have someone hack your words to say something you didnt. You get the idea. While this application only supports one signature per document, you can of course have however many you want. Below, I will explain some of the finer details of the sample code.
Figure 1. A Sound Byte Window
In this application, I have extended the definition of the DialogRecord to include some fields I need to associate with any given document/window. This is defined in the SoundByteWindow structure. Of importance is the state field and the partOfName field. The state is where I keep track of whether or not the signature has been verified. Its type is VerificationState which can be one of three values; kUnkownState, kValidState, kInvalidState. The only reason we care about the state is for purposes of our Human Interface. More on this later. The partOfName field is a Handle containing a string. This string is one of the attributes in the signers certificate (preferably a name or title) which serves as a hint to the user as to whose name is on the signature. This too is an optional user interface element and may not be necessary or desired in your application.
Another aspect of this sample is that we have a progress dialog which allows the user to cancel the current process. This is handled by two generic routines called BeginProcessing and EndProcessing. BeginProcessing takes a parameter of OperationType which allows the routine to insert the correct text based on one of these operation types; kSigningOperation, kVerifyingOperation, kProcessingOperation, kCancelingOperation.
Given the above basics, when a user chooses New from the file menu they get the window shown in Figure 1. After creating and signing a SoundByte, the window inserts the signature icon and name hint next to the By field. This By fields icon is why we track the VerificationState mentioned earlier. If the verification was successful or the signature was just performed, we show the icon kSIGValidSignatureIconResID. If the verification failed, we show the icon kSIGInvalidSignatureIconResID. And finally, if we dont know the state as is the case when you open a document or if the user types in the document which potentially would invalidate the signature, we show the icon kSIGSignatureIconResID. Admittedly, this behavior may not be desired in all applications. You can choose to not show an icon at all or to show only the kSIGSignatureIconResID icon regardless of the signature state. Which ever of these means is appropriate to your application would satisfy the Human Interface Guidelines and you can solicit feedback from Apple on this topic on the AOCE Talk discussion board on AppleLink. The icon ID numbers are defined in DigitalSignature.h.
The calls, SIGSign and SIGVerifyPrepare both take an optional SIGStatusProcPtr which is where you can do things like spin a watch cursor or detect user clicks in a cancel button which is what we do in the sample function SimpleStatusProc.
The function DoProcessData is responsible for making the calls to SIGProcessData to cycle through everything that is being signed. This is when the digest gets computed. Its most efficient to process data in large chunks, but at the same time you want to be able to yield control to the user so they can cancel the operation if desired. For this reason, we process the sound Handle in a for loop giving the user time by calling our SimpleStatusProc. The number of bytes you choose to process each time through the loop is up to you. Take into account factors such as desired user responsiveness, typical size of data to be signed etc
The function AssociateSignersNameAndSoundByte takes a context and SoundByteWindowPtr, retrieves the name of the signer, and stores it in our partOfName field in the SoundByteWindow structure. How this is done is a subtle but important point. Certificates can have multiple attributes of the same types and they are arranged in a sort of hierarchy where the attribute at index 0 is the highest in the tree. To retrieve the name we need to look for the lowest order attribute of type kSIGCommonName. We also need to be able to deal with the fact that this certificate may not have a name at all and may be an organizational role certificate, in which case we want a title. We get the attribute information from the certificate using some of the utility routines provided in the Digital Signature Manager.
Two other points about SoundByte I should mention are, firstly, the drawing of the appropriate icon and name of the signer is handled by the AuthorDrawProc procedure which is a standard dialog user item handler. Secondly, SoundByte stores all data in resources, I trust you will choose the more righteous path and store everything in the data fork as usual.
PARTING THOUGHTS
With respects to the Human Interface, how you choose to represent a signature in your application is pretty much up to you. Apple has provided some guidelines to help you, but different applications will have very different needs. Also, conveying to the user what has been signed in a document, especially when there is more than one signature available, is something you want to plan for. The Human Interface Guidelines for AOCE provides some very good examples and ideas on how you can solve these problems.
I mentioned earlier that the Finder supports Drag and Drop signing. Actually, the Finder uses a set of calls that create what is called a standard signature. A standard signature is one that any application can create or verify by using the supplied calls. So for example, if you sign your document using the SIGSignFile call, any application that supports these calls (including the Finder) can verify that signature by using the SIGVerifyFile call. This is a pretty handy, low overhead way to support signatures. You can detect if such a signature has been applied to your document by calling SIGFileIsSigned.
If you have data in your document that changes without explicit user invocation (e.g. window positions), you should place this data in a nods resource. This resource will not be signed by the standard signature call which means that any standard signature applied to your document by the user will not inadvertently be invalidated.
Finally, its important to note that since DigiSign creates full signatures, no servers are required at any time to sign or verify. Any PowerTalk user can verify a signature, even if they do not have a Signer or server accounts. Similarly, any PowerTalk user can create a signature given a valid Signer file.
Listing: part of SoundByte.h
/* 1 */
enum {
kSigningOperation,
kVerifyingOperation,
kProcessingOperation,
kCancelingOperation
};
typedef unsigned short OperationType;
enum {
kUnkownState,
kValidState,
kInvalidState
};
typedef unsigned short VerificationState;
typedef struct {
BooleanhasSoundInput;
Booleanrunning;
Boolean inBackground;
DialogPtrstatusDialog;
} Environment, *EnvironmentPtr;
typedef struct {
DialogRecord window;
Handle signature;
Handle sound;
Handle partOfName;
short resRef;
VerificationState state;
} SoundByteWindow, *SoundByteWindowPtr;
pascal OSErr PlotIconID(const Rect *theRect, short align,
short transform, short theResID) = {0x303C, 0x0500, 0xABC9};
Listing: parts of SoundByte.c
/* 2 */
pascal Boolean SimpleStatusProc()
{
GrafPtrsavePort;
EventRecordevent;
DialogPtraDialog;
short item;
long ignore;
BooleankeepGoing = true;
GetPort(&savePort);
SetPort(gEnvironment.statusDialog);
if (WaitNextEvent(kProcessingEventMask, &event,
kMinSleep, kNilMouseRgn))
{
// just in case
if (FrontWindow() != gEnvironment.statusDialog)
SelectWindow(gEnvironment.statusDialog);
switch (event.what)
{
case autoKey:
case keyDown:
// poor mans way to cancel,
// see IM VI for localizable way!
if (event.modifiers & cmdKey &&
(event.message & charCodeMask) == .)
keepGoing = false;
break;
default:
SetCursor(&qd.arrow);
if (IsDialogEvent(&event) &&
DialogSelect(&event, &aDialog, &item) &&
aDialog == gEnvironment.statusDialog)
keepGoing = false;
SetCursor(*GetCursor(watchCursor));
}
}
if (keepGoing == false)
{
BeginProcessing(kCancelingOperation);
// delay so user can read the status dialog
Delay(40, &ignore);
}
SetPort(savePort);
return keepGoing;
}
OSErr DoProcessData(SIGContextPtr context,
SoundByteWindowPtr window)
{
short kind;
Handle item;
Rect bounds;
Str255 topic;
Size soundLength;
Size soundOffset= 0;
Size soundChunk = kOurProcessDataSize;
OSErr error = noErr;
do {
// digest the topic field
GetDItem((DialogPtr)window, iTopic, &kind,
&item, &bounds);
GetIText(item, topic);
if (error = SIGProcessData(context, topic, topic[0]))
break;
// see if user wants to cancel
if (SimpleStatusProc() == false)
error = userCanceledErr;
// if there is a sound, process it
// in kOurProcessDataSize chunks
if (window->sound == nil)
break;
soundLength = GetHandleSize(window->sound);
if (soundLength < soundChunk)
soundChunk = soundLength;
HLock(window->sound);
do{
if (error = SIGProcessData(context,
(*window->sound)+soundOffset, soundChunk))
break;
// see if user wants to cancel
if (SimpleStatusProc() == false)
{
error = userCanceledErr;
break;
}
// increment what we just processed
soundOffset+=soundChunk;
// preflight chunk for next pass
if ((soundOffset + soundChunk) > soundLength)
soundChunk = soundLength - soundOffset;
// when we process it all, bail
if (soundChunk <= 0)
break;
} while (true);
HUnlock(window->sound);
} while (0);
return error;
}
OSErr AssociateSignersNameAndSoundByte(SIGContextPtr context,
SoundByteWindowPtr window)
{
SIGCertInfo certInfo;
SIGNameAttributesInfo attrInfo;
unsigned short attrIndex;
OSErr error;
Str255 attrValue= {0};
do {
// get the number of cert attributes
if (error = SIGGetCertInfo(context,
kSIGSignerCertIndex, &certInfo))
break;
// walk the attributes looking for the right
// one to store away
for (attrIndex = 0;
attrIndex < certInfo.certAttributeCount; attrIndex++)
{
if (error = SIGGetCertNameAttributes(context,
kSIGSignerCertIndex, attrIndex, &attrInfo))
break;
// in case there is no name
if (attrInfo.attributeType == kSIGTitle)
BlockMove(&attrInfo.attribute,
&attrValue, sizeof(Str255));
else if (attrInfo.attributeType == kSIGCommonName)
// best thing to display
{
BlockMove(&attrInfo.attribute,
&attrValue, sizeof(Str255));
break;
}
}
if (window->partOfName)
DisposHandle(window->partOfName);
error = PtrToHand(attrValue,
&window->partOfName, attrValue[0] + 1);
} while (0);
return error;
}
void DoVerifying()
{
OSErr error;
SIGContextPtr context = nil;
SoundByteWindowPtrwindow =
(SoundByteWindowPtr)FrontWindow();
do {
window->state = kUnkownState;
BeginProcessing(kVerifyingOperation);
if (error = SIGNewContext(&context))
break;
HLock(window->signature);
error = SIGVerifyPrepare(context,
(SIGSignaturePtr)*window->signature,
GetHandleSize(window->signature),
(SIGStatusProcPtr)SimpleStatusProc);
HUnlock(window->signature);
if (error)
break;
BeginProcessing(kProcessingOperation);
if (error = DoProcessData(context, window))
break;
BeginProcessing(kVerifyingOperation);
error = SIGVerify(context);
if (error && error != kSIGInvalidCredentialErr)
{
window->state = kInvalidState;
break;
}
// refresh name for safety
if (error =
AssociateSignersNameAndSoundByte(context, window))
break;
window->state = kValidState;
EndProcessing();
error = SIGShowSigner(context, kNullPString);
} while (0);
if (context) SIGDisposeContext(context);
EndProcessing();
AlertOSErr(error);
}
void DoSigning()
{
OSErr error;
Size signatureSize;
SIGContextPtr context = nil;
SoundByteWindowPtrwindow =
(SoundByteWindowPtr)FrontWindow();
do {
if (error = SIGNewContext(&context))
break;
if (error = SIGSignPrepare(context, nil,
kNullPString, &signatureSize))
break;
BeginProcessing(kProcessingOperation);
if (window->signature)
SetHandleSize(window->signature, signatureSize);
else
window->signature = NewHandle(signatureSize);
if (error = MemError())
break;
HNoPurge(window->signature);
if (error = DoProcessData(context, window))
break;
BeginProcessing(kSigningOperation);
HLock(window->signature);
error = SIGSign(context,
(SIGSignaturePtr)*window->signature,
(SIGStatusProcPtr)SimpleStatusProc);
HUnlock(window->signature);
if (error)
break;
if (error =
AssociateSignersNameAndSoundByte(context, window))
break;
window->state = kValidState;
} while (0);
if (context) SIGDisposeContext(context);
if (error && window->signature)
{
DisposHandle(window->signature);
window->signature = nil;
}
EndProcessing();
AlertOSErr(error);
}
pascal void AuthorDrawProc(DialogPtr dialog, short itemNumber)
{
short kind;
Handle item;
Rect bounds;
SoundByteWindowPtrwindow = (SoundByteWindowPtr)dialog;
GetDItem(dialog, itemNumber, &kind, &item, &bounds);
if (window->partOfName)
{
EraseRect(&bounds);
MoveTo(bounds.left + 20, bounds.bottom - 4);
DrawString((StringPtr)*window->partOfName);
bounds.bottom -= 1;
bounds.right = bounds.left + 16;
bounds.top = bounds.bottom - 16;
if (window->state == kValidState)
kind = kSIGValidSignatureIconResID;
else if (window->state == kInvalidState)
kind = kSIGInvalidSignatureIconResID;
else
kind = kSIGSignatureIconResID;
PlotIconID(&bounds, 0, 0, kind);
}
else
{
PenPat(qd.gray);
FrameRect(&bounds);
PenNormal();
}
}
void DoRecording()
{
OSErr error;
Point loc = {0, 0};
SoundByteWindowPtrwindow =
(SoundByteWindowPtr)FrontWindow();
LocalToGlobal(&loc);
loc.h += 75;
if (window->sound)
DisposHandle(window->sound);
if ((window->sound = GetTempHandle()) == nil)
error = MemError();
else
error = SndRecord(nil, loc,
siGoodQuality, &window->sound);
if (error == userCanceledErr && window->sound)
{
DisposHandle(window->sound);
window->sound = nil;
}
if (window->state != kUnkownState)
{
window->state = kUnkownState;
DrawDialog((DialogPtr)window);
}
AlertOSErr(error);
}
void DoPlaying()
{
OSErr error;
SoundByteWindowPtrwindow =
(SoundByteWindowPtr)FrontWindow();
error = SndPlay(nil, window->sound, true);
AlertOSErr(error);
}
Boolean Prerequisites()
{
OSErr error;
long value;
Booleanresult = false;
do {
if (NGetTrapAddress(_GestaltDispatch,ToolTrap) ==
NGetTrapAddress(_Unimplemented,ToolTrap))
break;
if (error =
Gestalt(gestaltDigitalSignatureVersion, &value))
break;
result = true;
} while (0);
return result;
}