//Sample code file: var/ndk/webBuildengine/tmp/viewable_samples/ce523e3a-5871-4fa6-9227-e51b7969ef46/GenerateCSR.cpp

//Warning: This code has been marked up for HTML

/***************************************************************************
 Copyright (c) 1998-2002 Novell, Inc.  All Rights Reserved.

 THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND
 TREATIES.  USE AND REDISTRIBUTION OF THIS WORK IS SUBJECT TO THE 
 LICENSE AGREEMENT ACCOMPANYING THE SOFTWARE DEVELOPMENT KIT (SDK)
 THAT CONTAINS THIS WORK.

 Pursuant to the SDK License Agreement, Novell hereby grants to 
 Developer a royalty-free, non-exclusive license to include the
 sample code AES.C and derivative binaries in its product.
 Novell grants to Developer worldwide distribution rights to market,
 distribute or sell the sample code AES.C and derivative
 binaries as a component of Developer's product(s).  Novell shall 
 have no obligations to Developer or Developer's customers with 
 respect to this code.

DISCLAIMER:

   Novell, Inc. makes no representations or warranties with respect
to the contents or use of this code, and specifically disclaims any
express or implied warranties of merchantability or fitness for any
particular purpose.  Further, Novell, Inc. reserves the right to revise
this publication and to make changes to its content, at any time,
without obligation to notify any person or entity of such revisions or
changes.

   Further, Novell, Inc. makes no representations or warranties with
respect to any software, and specifically disclaims any express or
implied warranties of merchantability or fitness for any particular
purpose.  Further, Novell, Inc. reserves the right to make changes to
any and all parts of the software, at any time, without obligation to
notify any person or entity of such changes.                          

***************************************************************************/
#ifdef WIN32
#   include <windows.h>
#endif

#include <stdio.h>
#include "npki.h"
#include "pkierr.h"

NWRCODE GenerateCSR(void)
{
   NWRCODE            ccode = PKI_SUCCESS;
   NPKIContext         myPKI = NPKI_INVALID_CONTEXT;
   nuint32             signatureAlgorithms;
   nuint32             keyGenerationAlgorithms;
   nuint32             caOperational;
   nuint8 const       *csr = NULL;
   nuint32             maxSignKeySize;
   nuint32             maxKeyEncryptKeySize;
   nuint32             maxKeySize;
   nuint32             csrSize = 0;

   // user/system infomation

   unicode            myTree[]   = {'T','E','S','T',0};
   unicode            myUser[]   = {'A','d','m','i','n','.','n','o','v','e','l','l',0};
   char               password[]   = {'t','e','s','t',0};
   char*               startIPAddress = "192.168.0.2";
   unicode            serverDN[] = {'T','e','s','t','5','1','.','n','o','v','e','l','l',0};
   unicode            myCSRCertificateName[] = {'E','x','t','e','r','n','a','l',0};
   
   // certificate info

   NPKI_Extension    keyUsage;
   nuint16             sslKeyUsage = X509_KEY_USAGE_DIGITAL_SIGNATURE | X509_KEY_USAGE_KEY_ENCIPHERMENT;
   NPKI_Extension    NovellAttr = {PKI_EXTENSION_DONT_INCLUDE,0};
   
   
   ccode = NPKICreateContext(&myPKI);
   if (ccode != PKI_SUCCESS)
   {
      goto ERR_EXIT;
   }
   
   // Set the tree name, this is the tree we will make all calls to.

     ccode = NPKISetTreeName(myPKI, myTree);    
   if (ccode != PKI_SUCCESS)
   {
      goto ERR_EXIT;
   }
   ccode = NPKIConnectToIPAddress(myPKI, 0, 0, startIPAddress,   NULL,   NULL);
   
   // Login in

   ccode = NPKIDSLogin(myPKI, myUser, password);
   if (ccode != PKI_SUCCESS)
   {
      goto ERR_EXIT;
   }

   ccode = NPKIGetServerInfo
   (
      myPKI, 
      serverDN, 
      PKI_SERVER_INFO, 
      &keyGenerationAlgorithms, 
      &signatureAlgorithms,
      NULL,
      NULL,
      &caOperational,
      NULL,
      NULL,
      NULL,
      NULL
   );
   if (ccode != PKI_SUCCESS)
   {
      goto ERR_EXIT;
   }
   
   if (!(keyGenerationAlgorithms & PKI_RSA_ALGORITHM)) 
   {                                                    
      ccode = PKI_E_ALGORITHM_NOT_SUPPORTED;
      goto ERR_EXIT;
   }
   
   if (!(signatureAlgorithms & PKI_SIGN_WITH_RSA_AND_SHA1))   // (other algorithms could be used)

   {
      ccode = PKI_E_ALGORITHM_NOT_SUPPORTED;
      goto ERR_EXIT;
   }

   ccode = NPKIGetAlgorithmInfo
   (
      myPKI,
      PKI_RSA_ALGORITHM, 
      &maxKeyEncryptKeySize,
      &maxSignKeySize,
      NULL,                    
      NULL,                    
      NULL    
   );
   if (ccode != PKI_SUCCESS)
   {
      goto ERR_EXIT;
   }
   
   maxKeySize = maxSignKeySize;
   if (maxKeyEncryptKeySize < maxKeySize)
      maxKeySize = maxKeyEncryptKeySize; 
      
#ifndef HI_LO_MACH_TYPE // The key usage needs to be in Big Endian so swap

   {                     // the byte ordering if we are not on a HI LO machine type

      nuint16   newValue = 0;
      nuint8   *oldValuePtr = (nuint8 *)&sslKeyUsage;
      nuint8   *newValuePtr = (nuint8 *)&newValue;
      
      newValuePtr[0] = oldValuePtr[1];
      newValuePtr[1] = oldValuePtr[0];
      sslKeyUsage = newValue;
   }
#endif

   keyUsage.flags = PKI_EXTENSION_INCLUDE;  // This key usage must match what key usages the external CA will 

   keyUsage.length = sizeof(sslKeyUsage);     // put on the actual certificate.

   keyUsage.value = (nuint8 *)&sslKeyUsage;
   
   ccode = NPKICreateServerCertificate   
   (                                       // This just creates a PKCS #10 CSR

      myPKI,
      serverDN,
      NULL, // This must be NULL

      myCSRCertificateName, 
      PKI_RSA_ALGORITHM,
      maxKeySize,
      NULL, 
      PKI_SIGN_WITH_RSA_AND_SHA1,
      DEFAULT_YEAR_ENCODING, 
      0, 
      0,
      PUBLIC_KEY_EXTERNAL_CA,
      PRIVATE_KEY,
      &keyUsage, 
      NULL,
      NULL, 
      &NovellAttr,
      NULL,
      NULL,
      NULL
   );
   if (ccode != PKI_SUCCESS)
   {
      goto ERR_EXIT;
   }

   ccode = NPKICSRInfo
   (
      myPKI,
      &csrSize,
      &csr
   );
   if (ccode != PKI_SUCCESS)
   {
      goto ERR_EXIT;
   }
   
   // use the csr or save it for later use (i.e. send it to the CA to create the certificate)

   {
      FILE      *stream = NULL;
      size_t   size = 0;
      
      stream = fopen("serverCSR.b64", "wb");
      if (stream != NULL)
      {
         size = fwrite(csr, sizeof(char), csrSize, stream);
         fclose(stream);   
      }
   }

ERR_EXIT:
   NPKIDSLogout(myPKI);

   if (myPKI != NPKI_INVALID_CONTEXT)
      NPKIFreeContext(myPKI);

   return ccode;
}