summaryrefslogtreecommitdiffstats
path: root/pki/base/symkey/src/com
diff options
context:
space:
mode:
Diffstat (limited to 'pki/base/symkey/src/com')
-rw-r--r--pki/base/symkey/src/com/netscape/symkey/Base.h44
-rw-r--r--pki/base/symkey/src/com/netscape/symkey/Buffer.cpp183
-rw-r--r--pki/base/symkey/src/com/netscape/symkey/Buffer.h173
-rw-r--r--pki/base/symkey/src/com/netscape/symkey/EncryptData.cpp244
-rw-r--r--pki/base/symkey/src/com/netscape/symkey/SessionKey.cpp1728
-rw-r--r--pki/base/symkey/src/com/netscape/symkey/SessionKey.java136
-rw-r--r--pki/base/symkey/src/com/netscape/symkey/SymKey.cpp1132
-rw-r--r--pki/base/symkey/src/com/netscape/symkey/SymKey.h45
8 files changed, 3685 insertions, 0 deletions
diff --git a/pki/base/symkey/src/com/netscape/symkey/Base.h b/pki/base/symkey/src/com/netscape/symkey/Base.h
new file mode 100644
index 000000000..cdcf72bcf
--- /dev/null
+++ b/pki/base/symkey/src/com/netscape/symkey/Base.h
@@ -0,0 +1,44 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+#ifndef BASE_H
+#define BASE_H
+#include <nspr.h>
+
+typedef unsigned char BYTE;
+
+enum nsNKeyMsgEnum {
+ VRFY_FAILURE,
+ VRFY_SUCCESS,
+ ENCODE_DER_PUBKEY_FAILURE,
+ B64ENCODE_FAILURE,
+ VFY_BEGIN_FAILURE,
+ VFY_UPDATE_FAILURE,
+ HTTP_REQ_EXE_FAILURE,
+ HTTP_ERROR_RCVD,
+ BASE64_DECODE_FAILURE,
+ REQ_TO_CA_SUCCESS,
+ MSG_INVALID
+};
+
+struct ReturnStatus {
+ PRStatus status;
+ nsNKeyMsgEnum statusNum;
+};
+
+#endif /* BASE_H */
diff --git a/pki/base/symkey/src/com/netscape/symkey/Buffer.cpp b/pki/base/symkey/src/com/netscape/symkey/Buffer.cpp
new file mode 100644
index 000000000..5c687c5f5
--- /dev/null
+++ b/pki/base/symkey/src/com/netscape/symkey/Buffer.cpp
@@ -0,0 +1,183 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+#include <memory.h>
+#include <assert.h>
+#include <stdio.h>
+#include <cstdarg>
+#include <string>
+
+#include "Buffer.h"
+
+Buffer::Buffer(const BYTE *buf_, unsigned int len_) : len(len_), res(len_)
+{
+ buf = new BYTE[len];
+ memcpy(buf, buf_, len);
+}
+
+Buffer::Buffer(const Buffer& cpy)
+{
+ buf = 0;
+ *this = cpy;
+}
+
+Buffer::Buffer(unsigned int len_) : len(len_), res(len_)
+{
+ buf = new BYTE[res];
+ memset(buf, 0, len_);
+}
+
+Buffer::Buffer(unsigned int len_, BYTE b) : len(len_), res(len_)
+{
+ buf = new BYTE[res];
+ memset(buf, b, len);
+}
+
+Buffer::~Buffer()
+{
+ delete [] buf;
+}
+
+bool
+Buffer::operator==(const Buffer& cmp) const
+{
+ if( len != cmp.len ) return false;
+ for( unsigned int i=0; i < len; ++i ) {
+ if( buf[i] != cmp.buf[i] ) {
+ return false;
+ }
+ }
+ return true;
+}
+
+Buffer&
+Buffer::operator=(const Buffer& cpy)
+{
+ if( this == &cpy ) return *this;
+ len = cpy.len;
+ delete [] buf;
+ buf = new BYTE[len];
+ memcpy(buf, cpy.buf, len);
+ res = len;
+
+ return *this;
+}
+
+void
+Buffer::zeroize()
+{
+ if( len > 0 ) {
+ memset( buf, 0, len );
+ }
+}
+
+Buffer
+Buffer::operator+(const Buffer& addend) const
+{
+ Buffer result(len + addend.len);
+ memcpy(result.buf, buf, len);
+ memcpy(result.buf+len, addend.buf, addend.len);
+ return result;
+}
+
+Buffer&
+Buffer::operator+=(const Buffer& addend)
+{
+ unsigned int oldLen = len;
+ resize(len + addend.len);
+ memcpy(buf+oldLen, addend.buf, addend.len);
+ return *this;
+}
+
+Buffer&
+Buffer::operator+=(BYTE b)
+{
+ resize(len+1);
+ buf[len-1] = b;
+ return *this;
+}
+
+void
+Buffer::reserve(unsigned int n)
+{
+ if( n > res ) {
+ BYTE *newBuf = new BYTE[n];
+ memcpy(newBuf, buf, len);
+ delete [] buf;
+ buf = newBuf;
+ res = n;
+ }
+}
+
+void
+Buffer::resize(unsigned int newLen)
+{
+ if( newLen == len ) {
+ return;
+ } else if( newLen < len ) {
+ len = newLen;
+ } else if( newLen <= res ) {
+ assert( newLen > len );
+ memset(buf+len, 0, newLen-len);
+ len = newLen;
+ } else {
+ assert( newLen > len && newLen > res );
+ BYTE *newBuf = new BYTE[newLen];
+ memcpy(newBuf, buf, len);
+ memset(newBuf+len, 0, newLen-len);
+ delete [] buf;
+ buf = newBuf;
+ len = newLen;
+ res = newLen;
+ }
+}
+
+Buffer
+Buffer::substr(unsigned int i, unsigned int n) const
+{
+ assert( i < len && (i+n) <= len );
+ return Buffer( buf+i, n );
+}
+
+void
+Buffer::replace(unsigned int i, const BYTE* cpy, unsigned int n)
+{
+ if (len > i+n) {
+ resize( len);
+ }else {
+ resize( i+n );
+ }
+ memcpy(buf+i, cpy, n);
+}
+
+void
+Buffer::dump() const
+{
+ unsigned int i;
+
+ for( i=0; i < len; ++i ) {
+ printf("%02x ", buf[i]);
+ if( i % 16 == 15 ) printf("\n");
+ }
+ printf("\n");
+}
+
+static const char hextbl[] = {
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
+};
diff --git a/pki/base/symkey/src/com/netscape/symkey/Buffer.h b/pki/base/symkey/src/com/netscape/symkey/Buffer.h
new file mode 100644
index 000000000..2e0256d87
--- /dev/null
+++ b/pki/base/symkey/src/com/netscape/symkey/Buffer.h
@@ -0,0 +1,173 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+#ifndef BUFFER_H
+#define BUFFER_H
+
+#include <stdio.h>
+#include "Base.h"
+
+/**
+ * This class represents a byte array.
+ */
+class Buffer {
+
+ private:
+ BYTE *buf;
+ unsigned int len;
+ unsigned int res;
+
+ public:
+ /**
+ * Creates an empty Buffer.
+ */
+ Buffer() : buf(0), len(0), res(0) { }
+
+ /**
+ * Creates a Buffer of length 'len', with each byte initialized to 'b'.
+ */
+ Buffer(unsigned int len, BYTE b);
+
+ /**
+ * Creates a Buffer of length 'len', initialized to zeroes.
+ */
+ explicit Buffer(unsigned int len);
+
+ /**
+ * Creates a Buffer of length 'len', initialized from 'buf'. 'buf' must
+ * contain at least 'len' bytes.
+ */
+ Buffer(const BYTE* buf, unsigned int len);
+
+ /**
+ * Copy constructor.
+ */
+ Buffer(const Buffer& cpy);
+
+ /**
+ * Destructor.
+ */
+ ~Buffer();
+
+ /**
+ * Assignment operator.
+ */
+ Buffer& operator=(const Buffer& cpy);
+
+ /**
+ * Returns true if the two buffers are the same length and contain
+ * the same byte at each offset.
+ */
+ bool operator==(const Buffer& cmp) const;
+
+ /**
+ * Returns ! operator==(cmp).
+ */
+ bool operator!=(const Buffer& cmp) const { return ! (*this == cmp); }
+
+ /**
+ * Concatenation operator.
+ */
+ Buffer operator+(const Buffer&addend) const;
+
+ /**
+ * Append operators.
+ */
+ Buffer& operator+=(const Buffer&addend);
+ Buffer& operator+=(BYTE b);
+
+ /**
+ * Returns a pointer into the Buffer. This also enables the subscript
+ * operator, so you can say, for example, 'buf[4] = b' or 'b = buf[4]'.
+ */
+ operator BYTE*() { return buf; }
+ operator const BYTE*() const { return buf; }
+
+ /**
+ * The length of buffer. The actual amount of space allocated may be
+ * higher--see capacity().
+ */
+ unsigned int size() const { return len; }
+
+ /**
+ * The amount of memory allocated for the buffer. This is the maximum
+ * size the buffer can grow before it needs to allocate more memory.
+ */
+ unsigned int capacity() const { return res; }
+
+ /**
+ * Sets all bytes in the buffer to 0.
+ */
+ void zeroize();
+
+ /**
+ * Changes the length of the Buffer. If 'newLen' is shorter than the
+ * current length, the Buffer is truncated. If 'newLen' is longer, the
+ * new bytes are initialized to 0. If 'newLen' is the same as size(),
+ * this is a no-op.
+ */
+ void resize(unsigned int newLen);
+
+ /**
+ * Ensures that capacity() is at least 'reserve'. Allocates more memory
+ * if necessary. If 'reserve' is <= capacity(), this is a no-op.
+ * Does not affect size().
+ */
+ void reserve(unsigned int reserve);
+
+ /**
+ * Returns a new Buffer that is a substring of this Buffer, starting
+ * from offset 'start' and continuing for 'len' bytes. This Buffer
+ * must have size() >= (start + len).
+ */
+ Buffer substr(unsigned int start, unsigned int len) const;
+
+ /**
+ * Replaces bytes i through i+n in this Buffer using the values in 'cpy'.
+ * This Buffer is resized if necessary. The 'cpy' argument can be a
+ * Buffer.
+ */
+ void replace(unsigned int i, const BYTE* cpy, unsigned int n);
+
+ /**
+ * returns a hex version of the buffer
+ */
+ char *toHex();
+
+ /**
+ * Dumps this Buffer to the given file as formatted hex: 16 bytes per
+ * line, separated by spaces.
+ */
+ void dump(FILE* file) const;
+
+ /**
+ * returns a null-terminated string of the buf.
+ * should be called only by callers that are certain that buf
+ * is entirely representable by printable characters and wants
+ * a string instead.
+ */
+ char *string();
+
+ /**
+ * dump()s this Buffer to stdout.
+ */
+ void dump() const;
+
+};
+
+#endif
diff --git a/pki/base/symkey/src/com/netscape/symkey/EncryptData.cpp b/pki/base/symkey/src/com/netscape/symkey/EncryptData.cpp
new file mode 100644
index 000000000..fd037ce67
--- /dev/null
+++ b/pki/base/symkey/src/com/netscape/symkey/EncryptData.cpp
@@ -0,0 +1,244 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+#include "pk11func.h"
+#include "nspr.h"
+#ifdef __cplusplus
+#include <jni.h>
+#include <assert.h>
+#include <string.h>
+
+}
+#endif
+#include <memory.h>
+#include <assert.h>
+#include <stdio.h>
+#include <cstdarg>
+#include <string>
+#include <stdlib.h>
+#include "Buffer.h"
+#include "SymKey.h"
+#define DES2_WORKAROUND
+
+PRFileDesc *d = NULL;
+
+/**
+ * Encrypt 'cc_len' bytes of data in 'input' with key kek_key.
+ * Result goes into buffer 'output'
+ * Returns PR_FAILURE if there was an error
+ */
+PRStatus EncryptData(const Buffer &kek_key, jbyte * input,int cc_len, Buffer &output)
+{
+ PRStatus rv = PR_FAILURE;
+
+ PK11SymKey *master = NULL;
+ PK11SlotInfo *slot = PK11_GetInternalKeySlot();
+ PK11Context *context = NULL;
+ int i;
+ SECStatus s = SECFailure;
+ int len;
+ static SECItem noParams = { siBuffer, 0, 0 };
+#ifdef DES2_WORKAROUND
+ unsigned char masterKeyData[24];
+#else
+ unsigned char masterKeyData[16];
+#endif
+ SECItem masterKeyItem = {siBuffer, masterKeyData, sizeof(masterKeyData) };
+ unsigned char result[8];
+
+// convert 16-byte to 24-byte triple-DES key
+ memcpy(masterKeyData, kek_key, 16);
+#ifdef DES2_WORKAROUND
+ memcpy(masterKeyData+16, kek_key, 8);
+#endif
+
+ master = PK11_ImportSymKeyWithFlags(slot, CKM_DES3_ECB,
+ PK11_OriginGenerated, CKA_ENCRYPT, &masterKeyItem,
+ CKF_ENCRYPT, PR_FALSE, 0);
+ if (master == NULL)
+ {
+ goto done;
+ }
+
+ context = PK11_CreateContextBySymKey(CKM_DES3_ECB, CKA_ENCRYPT, master,
+ &noParams);
+ if (context == NULL)
+ {
+ goto done;
+ }
+
+ for(i = 0;i < (int)cc_len;i += 8)
+ {
+ s = PK11_CipherOp(context, result, &len, 8,
+ (unsigned char *)(input+i), 8);
+
+ if (s != SECSuccess)
+ {
+ goto done;
+ }
+ output.replace(i, result, 8);
+ }
+
+ rv = PR_SUCCESS;
+
+done:
+ /* memset(masterKeyData, 0, sizeof masterKeyData); */
+ if (context != NULL)
+ {
+ PK11_DestroyContext(context, PR_TRUE);
+ context = NULL;
+ }
+ if (slot != NULL)
+ {
+ PK11_FreeSlot(slot);
+ slot = NULL;
+ }
+ if (master != NULL)
+ {
+ PK11_FreeSymKey(master);
+ master = NULL;
+ }
+
+ return rv;
+}
+
+void GetKeyName(jbyte *keyVersion, char *keyname)
+{
+ int index=0;
+ if(strlen(masterKeyPrefix)!=0)
+ {
+ index= strlen(masterKeyPrefix);
+ strcpy(keyname,masterKeyPrefix);
+ }
+ keyname[index+0]='#';
+ sprintf(keyname+index+1,"%.2d", keyVersion[0]);
+ keyname[index+3]='#';
+ sprintf(keyname+index+4,"%.2d", keyVersion[1]);
+}
+
+
+extern "C" JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_EncryptData
+(JNIEnv *, jclass, jstring, jstring, jbyteArray, jbyteArray, jbyteArray, jbyteArray, jstring);
+
+extern "C" JNIEXPORT jbyteArray JNICALL
+Java_com_netscape_symkey_SessionKey_EncryptData(JNIEnv * env, jclass this2, jstring j_tokenName, jstring j_keyName, jbyteArray j_in, jbyteArray keyInfo, jbyteArray CUID, jbyteArray kekKeyArray, jstring useSoftToken_s)
+{
+ int status = PR_FAILURE;
+ jbyte * kek_key = (jbyte*)(env)->GetByteArrayElements(kekKeyArray, NULL);
+ jbyte * keyVersion = (jbyte*)(env)->GetByteArrayElements( keyInfo, NULL);
+ jbyte * cuidValue = (jbyte*)(env)->GetByteArrayElements( CUID, NULL);
+ jbyte *cc = (jbyte*)(env)->GetByteArrayElements( j_in, NULL);
+ int cc_len = (env)->GetArrayLength(j_in);
+
+ Buffer kek_buffer = Buffer((BYTE*)kek_key, 16);
+ Buffer out = Buffer(16, (BYTE)0);
+
+ /* generate kek key */
+ /* identify the masterKey by KeyInfo in TKS */
+ BYTE kekData[KEYLENGTH];
+ char keyname[KEYNAMELENGTH];
+ GetDiversificationData(cuidValue,kekData,kek);
+
+ PK11SlotInfo *slot = NULL;
+ if(j_tokenName != NULL)
+ {
+ char *tokenNameChars = (char *)(env)->GetStringUTFChars(j_tokenName, NULL);
+ slot = ReturnSlot(tokenNameChars);
+ (env)->ReleaseStringUTFChars(j_tokenName, (const char *)tokenNameChars);
+ tokenNameChars = NULL;
+ }
+
+ if(j_keyName != NULL)
+ {
+ char *keyNameChars= (char *)(env)->GetStringUTFChars(j_keyName, NULL);
+ strcpy(keyname,keyNameChars);
+ env->ReleaseStringUTFChars(j_keyName, (const char *)keyNameChars);
+ keyNameChars = NULL;
+ }
+ else
+ {
+ GetKeyName(keyVersion,keyname);
+ }
+
+ PK11SymKey *masterKey = NULL;
+ if (keyVersion[0] == 0x1 && keyVersion[1]== 0x1 &&strcmp( keyname, "#01#01") == 0)
+ {
+ /* default development keyset */
+ status = EncryptData(kek_buffer, cc, cc_len, out);
+ }
+ else
+ {
+ if (slot!=NULL)
+ {
+ masterKey = ReturnSymKey( slot,keyname);
+
+ /* We need to use internal so that the key
+ * can be exported by using PK11_GetKeyData()
+ */
+ if (masterKey != NULL)
+ {
+ PK11SymKey *kekKey = ComputeCardKeyOnToken(masterKey,kekData);
+ if (kekKey != NULL)
+ {
+ Buffer input = Buffer((BYTE*)cc, cc_len);
+ status = EncryptDataWithCardKey(kekKey, input, out);
+
+ if (kekKey != NULL)
+ {
+ PK11_FreeSymKey( kekKey);
+ kekKey = NULL;
+ }
+ }
+ }
+ }
+ }
+
+ if (masterKey != NULL)
+ {
+ PK11_FreeSymKey( masterKey);
+ masterKey = NULL;
+ }
+
+ if( slot!= NULL )
+ {
+ PK11_FreeSlot( slot );
+ slot = NULL;
+ }
+
+ jbyteArray handleBA=NULL;
+ if (status != PR_FAILURE && (out.size()>0) )
+ {
+ jbyte *handleBytes=NULL;
+ handleBA = (env)->NewByteArray( out.size());
+ handleBytes = (env)->GetByteArrayElements(handleBA, NULL);
+ BYTE* outp = (BYTE*)out;
+ memcpy(handleBytes, outp,out.size());
+ env->ReleaseByteArrayElements( handleBA, handleBytes, 0);
+ handleBytes=NULL;
+ }
+
+ env->ReleaseByteArrayElements(j_in, cc, JNI_ABORT);
+ env->ReleaseByteArrayElements(keyInfo, keyVersion, JNI_ABORT);
+ env->ReleaseByteArrayElements(CUID, cuidValue, JNI_ABORT);
+
+ return handleBA;
+}
diff --git a/pki/base/symkey/src/com/netscape/symkey/SessionKey.cpp b/pki/base/symkey/src/com/netscape/symkey/SessionKey.cpp
new file mode 100644
index 000000000..e4a02113d
--- /dev/null
+++ b/pki/base/symkey/src/com/netscape/symkey/SessionKey.cpp
@@ -0,0 +1,1728 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+#include "pk11func.h"
+#include "seccomon.h"
+#include "nspr.h"
+#ifdef __cplusplus
+#include <jni.h>
+#include <assert.h>
+#include <string.h>
+
+/*
+#include <jss_exceptions.h>
+#include <jssutil.h>
+*/
+
+}
+#endif
+#include <memory.h>
+#include <assert.h>
+#include <stdio.h>
+#include <cstdarg>
+#include <string>
+
+// DRM_PROTO begins
+#define PK11SYMKEY_CLASS_NAME "org/mozilla/jss/pkcs11/PK11SymKey"
+#define PK11SYMKEY_CONSTRUCTOR_SIG "([B)V"
+#define ALL_SYMKEY_OPS (CKF_ENCRYPT | CKF_DECRYPT | CKF_WRAP | CKF_UNWRAP)
+// DRM_PROTO ends
+
+#include "Buffer.h"
+#include "SymKey.h"
+
+#define STEAL_JSS
+#ifdef STEAL_JSS
+// stealing code from JSS to handle DRM support
+/*
+ * NativeProxy
+ */
+#define NATIVE_PROXY_CLASS_NAME "org/mozilla/jss/util/NativeProxy"
+#define NATIVE_PROXY_POINTER_FIELD "mPointer"
+#define NATIVE_PROXY_POINTER_SIG "[B"
+
+/*
+ * SymKeyProxy
+ */
+#define SYM_KEY_PROXY_FIELD "keyProxy"
+#define SYM_KEY_PROXY_SIG "Lorg/mozilla/jss/pkcs11/SymKeyProxy;"
+
+/***********************************************************************
+ **
+ ** J S S _ p t r T o B y t e A r r a y
+ **
+ ** Turn a C pointer into a Java byte array. The byte array can be passed
+ ** into a NativeProxy constructor.
+ **
+ ** Returns a byte array containing the pointer, or NULL if an exception
+ ** was thrown.
+ */
+jbyteArray
+JSS_ptrToByteArray(JNIEnv *env, void *ptr)
+{
+ jbyteArray byteArray;
+
+ /* Construct byte array from the pointer */
+ byteArray = (env)->NewByteArray(sizeof(ptr));
+ if(byteArray==NULL)
+ {
+ PR_ASSERT( (env)->ExceptionOccurred() != NULL);
+ return NULL;
+ }
+ (env)->SetByteArrayRegion(byteArray, 0, sizeof(ptr), (jbyte*)&ptr);
+ if((env)->ExceptionOccurred() != NULL)
+ {
+ PR_ASSERT(PR_FALSE);
+ return NULL;
+ }
+ return byteArray;
+}
+
+
+/***********************************************************************
+ *
+ * J S S _ P K 1 1 _ w r a p S y m K e y
+
+ * Puts a Symmetric Key into a Java object.
+ * (Does NOT perform a cryptographic "wrap" operation.)
+ * symKey: will be stored in a Java wrapper.
+ * Returns: a new PK11SymKey, or NULL if an exception occurred.
+ */
+jobject
+JSS_PK11_wrapSymKey(JNIEnv *env, PK11SymKey **symKey)
+{
+// return JSS_PK11_wrapSymKey(env, symKey, NULL);
+// hmmm, looks like I may not need to steal code after all
+ return JSS_PK11_wrapSymKey(env, symKey);
+}
+
+
+jobject
+JSS_PK11_wrapSymKey(JNIEnv *env, PK11SymKey **symKey, PRFileDesc *debug_fd)
+{
+ jclass keyClass;
+ jmethodID constructor;
+ jbyteArray ptrArray;
+ jobject Key=NULL;
+
+ if (debug_fd)
+ PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey\n");
+
+ PR_ASSERT(env!=NULL && symKey!=NULL && *symKey!=NULL);
+
+ /* find the class */
+ keyClass = (env)->FindClass(PK11SYMKEY_CLASS_NAME);
+ if (debug_fd)
+ PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey called FindClass\n");
+ if( keyClass == NULL )
+ {
+ if (debug_fd)
+ PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey FindClass NULL\n");
+// ASSERT_OUTOFMEM(env);
+ goto finish;
+ }
+
+ /* find the constructor */
+ constructor = (env)->GetMethodID(keyClass,
+ "<init>"/*PLAIN_CONSTRUCTOR*/,
+ PK11SYMKEY_CONSTRUCTOR_SIG);
+ if (debug_fd)
+ PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey called GetMethodID\n");
+ if(constructor == NULL)
+ {
+// ASSERT_OUTOFMEM(env);
+ if (debug_fd)
+ PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey GetMethodID returns NULL\n");
+ goto finish;
+ }
+
+ /* convert the pointer to a byte array */
+ ptrArray = JSS_ptrToByteArray(env, (void*)*symKey);
+ if (debug_fd)
+ PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey called JSS_ptrToByteArray\n");
+ if( ptrArray == NULL )
+ {
+ if (debug_fd)
+ PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey JSS_ptrToByteArray returns NULL\n");
+ goto finish;
+ }
+
+ /* call the constructor */
+ Key = (env)->NewObject( keyClass, constructor, ptrArray);
+ if (debug_fd)
+ PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey called NewObject\n");
+
+finish:
+ if(Key == NULL)
+ {
+ if (debug_fd)
+ PR_fprintf(debug_fd, "DRMproto in JSS_PK11_wrapSymKey NewObject returns NULL\n");
+ PK11_FreeSymKey(*symKey);
+ }
+ *symKey = NULL;
+ return Key;
+}
+
+
+/***********************************************************************
+ **
+ ** J S S _ g e t P t r F r o m P r o x y
+ **
+ ** Given a NativeProxy, extract the pointer and store it at the given
+ ** address.
+ **
+ ** nativeProxy: a JNI reference to a NativeProxy.
+ ** ptr: address of a void* that will receive the pointer extracted from
+ ** the NativeProxy.
+ ** Returns: PR_SUCCESS on success, PR_FAILURE if an exception was thrown.
+ **
+ ** Example:
+ ** DataStructure *recovered;
+ ** jobject proxy;
+ ** JNIEnv *env;
+ ** [...]
+ ** if(JSS_getPtrFromProxy(env, proxy, (void**)&recovered) != PR_SUCCESS) {
+ ** return; // exception was thrown!
+ ** }
+ */
+PRStatus
+JSS_getPtrFromProxy(JNIEnv *env, jobject nativeProxy, void **ptr)
+{
+#ifdef DEBUG
+ jclass nativeProxyClass;
+#endif
+ jclass proxyClass;
+ jfieldID byteArrayField;
+ jbyteArray byteArray;
+ int size;
+
+ PR_ASSERT(env!=NULL && nativeProxy != NULL && ptr != NULL);
+ if( nativeProxy == NULL )
+ {
+// JSS_throw(env, NULL_POINTER_EXCEPTION);
+ return PR_FAILURE;
+ }
+
+ proxyClass = (env)->GetObjectClass(nativeProxy);
+ PR_ASSERT(proxyClass != NULL);
+
+#ifdef DEBUG
+ nativeProxyClass = (env)->FindClass(
+ NATIVE_PROXY_CLASS_NAME);
+ if(nativeProxyClass == NULL)
+ {
+// ASSERT_OUTOFMEM(env);
+ return PR_FAILURE;
+ }
+
+ /* make sure what we got was really a NativeProxy object */
+ PR_ASSERT( (env)->IsInstanceOf(nativeProxy, nativeProxyClass) );
+#endif
+
+ byteArrayField = (env)->GetFieldID(
+ proxyClass,
+ NATIVE_PROXY_POINTER_FIELD,
+ NATIVE_PROXY_POINTER_SIG);
+ if(byteArrayField==NULL)
+ {
+// ASSERT_OUTOFMEM(env);
+ return PR_FAILURE;
+ }
+
+ byteArray = (jbyteArray) (env)->GetObjectField(nativeProxy,
+ byteArrayField);
+ PR_ASSERT(byteArray != NULL);
+
+ size = sizeof(*ptr);
+ PR_ASSERT((env)->GetArrayLength( byteArray) == size);
+ (env)->GetByteArrayRegion(byteArray, 0, size, (jbyte*)ptr);
+ if( (env)->ExceptionOccurred() )
+ {
+ PR_ASSERT(PR_FALSE);
+ return PR_FAILURE;
+ }
+ else
+ {
+ return PR_SUCCESS;
+ }
+}
+
+
+/***********************************************************************
+ **
+ ** J S S _ g e t P t r F r o m P r o x y O w n e r
+ **
+ ** Given an object which contains a NativeProxy, extract the pointer
+ ** from the NativeProxy and store it at the given address.
+ **
+ ** proxyOwner: an object which contains a NativeProxy member.
+ ** proxyFieldName: the name of the NativeProxy member.
+ ** proxyFieldSig: the signature of the NativeProxy member.
+ ** ptr: address of a void* that will receive the extract pointer.
+ ** Returns: PR_SUCCESS for success, PR_FAILURE if an exception was thrown.
+ **
+ ** Example:
+ ** <Java>
+ ** public class Owner {
+ ** protected MyProxy myProxy;
+ ** [...]
+ ** }
+ **
+ ** <C>
+ ** DataStructure *recovered;
+ ** jobject owner;
+ ** JNIEnv *env;
+ ** [...]
+ ** if(JSS_getPtrFromProxyOwner(env, owner, "myProxy", (void**)&recovered)
+ ** != PR_SUCCESS) {
+ ** return; // exception was thrown!
+ ** }
+ */
+PRStatus
+JSS_getPtrFromProxyOwner(JNIEnv *env, jobject proxyOwner, char* proxyFieldName,
+char *proxyFieldSig, void **ptr)
+{
+ jclass ownerClass;
+ jfieldID proxyField;
+ jobject proxyObject;
+
+ PR_ASSERT(env!=NULL && proxyOwner!=NULL && proxyFieldName!=NULL &&
+ ptr!=NULL);
+
+ /*
+ * Get proxy object
+ */
+ ownerClass = (env)->GetObjectClass(proxyOwner);
+ proxyField = (env)->GetFieldID(ownerClass, proxyFieldName,
+ proxyFieldSig);
+ if(proxyField == NULL)
+ {
+ return PR_FAILURE;
+ }
+ proxyObject = (env)->GetObjectField(proxyOwner, proxyField);
+ PR_ASSERT(proxyObject != NULL);
+
+ /*
+ * Get the pointer from the Native Reference object
+ */
+ return JSS_getPtrFromProxy(env, proxyObject, ptr);
+}
+
+
+/***********************************************************************
+ *
+ * J S S _ P K 1 1 _ g e t S y m K e y P t r
+ *
+ */
+PRStatus
+JSS_PK11_getSymKeyPtr(JNIEnv *env, jobject symKeyObject, PK11SymKey **ptr)
+{
+ PR_ASSERT(env!=NULL && symKeyObject!=NULL);
+
+ /* Get the pointer from the key proxy */
+ return JSS_getPtrFromProxyOwner(env, symKeyObject, SYM_KEY_PROXY_FIELD,
+ SYM_KEY_PROXY_SIG, (void**)ptr);
+}
+#endif //STEAL_JSS
+
+PK11SymKey *DeriveKeyWithCardKey(PK11SymKey *cardkey, const Buffer& hostChallenge, const Buffer& cardChallenge)
+{
+ PK11SymKey *key = NULL, *master = NULL;
+ PK11SlotInfo *slot = PK11_GetInternalKeySlot();
+ PK11Context *context = NULL;
+ unsigned char derivationData[16];
+#ifdef DES2_WORKAROUND
+ unsigned char keyData[24];
+#else
+ unsigned char keyData[16];
+#endif
+ int i;
+ SECStatus s;
+ int len;
+ SECItem keyItem = { siBuffer, keyData, sizeof keyData };
+ static SECItem noParams = { siBuffer, 0, 0 };
+
+ for(i = 0;i < 4;i++)
+ {
+ derivationData[i] = cardChallenge[i+4];
+ derivationData[i+4] = hostChallenge[i];
+ derivationData[i+8] = cardChallenge[i];
+ derivationData[i+12] = hostChallenge[i+4];
+ }
+ context = PK11_CreateContextBySymKey(CKM_DES3_ECB, CKA_ENCRYPT, cardkey,
+ &noParams);
+ if (!context) goto done;
+
+ /* Part 1 */
+ s = PK11_CipherOp(context, &keyData[0], &len, 8, &derivationData[0], 8);
+ if (s != SECSuccess) goto done;
+
+ /* Part 2 */
+ s = PK11_CipherOp(context, &keyData[8], &len, 8, &derivationData[8], 8);
+ if (s != SECSuccess) goto done;
+
+#ifdef DES2_WORKAROUND
+ /* Part 3 */
+ for(i = 0;i < 8;i++)
+ {
+ keyData[i+16] = keyData[i];
+ }
+#endif
+
+ key = PK11_ImportSymKeyWithFlags(slot, CKM_DES3_ECB, PK11_OriginGenerated,
+ CKA_ENCRYPT, &keyItem, CKF_SIGN | CKF_ENCRYPT, PR_FALSE, 0);
+
+ done:
+ memset(keyData, 0, sizeof keyData);
+ if (context) PK11_DestroyContext(context, PR_TRUE);
+ if (slot) PK11_FreeSlot(slot);
+ if (master) PK11_FreeSymKey(master);
+
+ return key;
+}
+
+
+PK11SymKey *DeriveKey(const Buffer& permKey, const Buffer& hostChallenge, const Buffer& cardChallenge)
+{
+ PK11SymKey *key = NULL, *master = NULL;
+ PK11SlotInfo *slot = PK11_GetInternalKeySlot();
+ PK11Context *context = NULL;
+ unsigned char derivationData[16];
+#ifdef DES2_WORKAROUND
+ unsigned char keyData[24];
+#else
+ unsigned char keyData[16];
+#endif
+ int i;
+ SECStatus s;
+ int len;
+ SECItem keyItem = { siBuffer, keyData, sizeof keyData };
+ static SECItem noParams = { siBuffer, 0, 0 };
+ BYTE masterKeyData[24];
+ SECItem masterKeyItem = {siBuffer, masterKeyData, sizeof(masterKeyData) };
+
+ /* convert 16-byte to 24-byte triple-DES key */
+ memcpy(masterKeyData, permKey, 16);
+ memcpy(masterKeyData+16, permKey, 8);
+
+ master = PK11_ImportSymKeyWithFlags(slot, CKM_DES3_ECB,
+ PK11_OriginGenerated, CKA_ENCRYPT, &masterKeyItem,
+ CKF_ENCRYPT, PR_FALSE, 0);
+ if( ! master ) goto done;
+
+ for(i = 0;i < 4;i++)
+ {
+ derivationData[i] = cardChallenge[i+4];
+ derivationData[i+4] = hostChallenge[i];
+ derivationData[i+8] = cardChallenge[i];
+ derivationData[i+12] = hostChallenge[i+4];
+ }
+ context = PK11_CreateContextBySymKey(CKM_DES3_ECB, CKA_ENCRYPT, master,
+ &noParams);
+ if (!context) goto done;
+
+ /* Part 1 */
+ s = PK11_CipherOp(context, &keyData[0], &len, 8, &derivationData[0], 8);
+ if (s != SECSuccess) goto done;
+
+ /* Part 2 */
+ s = PK11_CipherOp(context, &keyData[8], &len, 8, &derivationData[8], 8);
+ if (s != SECSuccess) goto done;
+
+#ifdef DES2_WORKAROUND
+ /* Part 3 */
+ for(i = 0;i < 8;i++)
+ {
+ keyData[i+16] = keyData[i];
+ }
+#endif
+
+ key = PK11_ImportSymKeyWithFlags(slot, CKM_DES3_ECB, PK11_OriginGenerated,
+ CKA_ENCRYPT, &keyItem, CKF_SIGN | CKF_ENCRYPT, PR_FALSE, 0);
+
+ done:
+ memset(keyData, 0, sizeof keyData);
+ if (context) PK11_DestroyContext(context, PR_TRUE);
+ if (slot) PK11_FreeSlot(slot);
+ if (master) PK11_FreeSymKey(master);
+
+ return key;
+}
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+ JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeKeyCheck
+ (JNIEnv *, jclass, jbyteArray);
+#ifdef __cplusplus
+}
+#endif
+extern "C" JNIEXPORT jbyteArray JNICALL
+Java_com_netscape_symkey_SessionKey_ComputeKeyCheck
+(JNIEnv* env, jclass this2, jbyteArray data)
+{
+ jbyteArray handleBA=NULL;
+ jint len;
+ jbyte *bytes=NULL;
+ jbyte *handleBytes=NULL;
+
+ PK11SymKey *key = NULL;
+ PK11SlotInfo *slot = PK11_GetInternalKeySlot();
+ PK11Context *context = NULL;
+ SECStatus s = SECFailure;
+ int lenx;
+ static SECItem noParams = { siBuffer, 0, 0 };
+#ifdef DES2_WORKAROUND
+ unsigned char keyData[24];
+#else
+ unsigned char keyData[16];
+#endif
+ SECItem keyItem = {siBuffer, keyData, sizeof(keyData) };
+ unsigned char value[8];
+
+ len = (env)->GetArrayLength(data);
+ bytes = (env)->GetByteArrayElements(data, NULL);
+ if( bytes == NULL )
+ {
+ goto finish;
+ }
+
+/* convert 16-byte to 24-byte triple-DES key */
+ memcpy(keyData, bytes, 16);
+#ifdef DES2_WORKAROUND
+ memcpy(keyData+16, bytes, 8);
+#endif
+ memset(value, 0, sizeof value);
+
+ key = PK11_ImportSymKeyWithFlags(slot, CKM_DES3_ECB,
+ PK11_OriginGenerated, CKA_ENCRYPT, &keyItem,
+ CKF_ENCRYPT, PR_FALSE, 0);
+ if( ! key )
+ {
+ goto finish;
+ }
+
+ context = PK11_CreateContextBySymKey(CKM_DES3_ECB, CKA_ENCRYPT, key,
+ &noParams);
+ if (!context)
+ {
+ goto finish;
+ }
+ s = PK11_CipherOp(context, &value[0], &lenx, 8, &value[0], 8);
+ if (s != SECSuccess)
+ {
+ goto finish;
+ }
+ handleBA = (env)->NewByteArray(3);
+ if(handleBA == NULL )
+ {
+ goto finish;
+ }
+ handleBytes = (env)->GetByteArrayElements(handleBA, NULL);
+ if(handleBytes==NULL)
+ {
+ goto finish;
+ }
+ memcpy(handleBytes, value, 3);
+
+ (env)->ReleaseByteArrayElements(handleBA, handleBytes, 0);
+
+ finish:
+ if (context) PK11_DestroyContext(context, PR_TRUE);
+ if (slot) PK11_FreeSlot(slot);
+ if (key) PK11_FreeSymKey(key);
+
+ return handleBA;
+}
+
+
+//=================================================================================
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/*
+ * Class: com_netscape_cms_servlet_tks_RASessionKey
+ * Method: ComputeSessionKey
+ * Signature: ([B[B[B[B)[B
+ */
+ JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeSessionKey
+ (JNIEnv *, jclass, jstring, jstring, jbyteArray, jbyteArray, jbyteArray, jbyteArray, jbyteArray, jstring);
+#ifdef __cplusplus
+}
+#endif
+#define KEYLENGTH 16
+extern "C" JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeSessionKey(JNIEnv * env, jclass this2, jstring tokenName, jstring keyName, jbyteArray card_challenge, jbyteArray host_challenge, jbyteArray keyInfo, jbyteArray CUID, jbyteArray macKeyArray, jstring useSoftToken_s)
+{
+/* hardcore permanent mac key */
+ jbyte *mac_key = (jbyte*)(env)->GetByteArrayElements(macKeyArray, NULL);
+ char input[16];
+ int i;
+
+//char icv[8];
+ jbyte *cc = (jbyte*)(env)->GetByteArrayElements( card_challenge, NULL);
+ int cc_len = (env)->GetArrayLength(card_challenge);
+
+ jbyte *hc = (jbyte*)(env)->GetByteArrayElements( host_challenge, NULL);
+ // .size();
+ int hc_len = (env)->GetArrayLength( host_challenge);
+
+ jbyte * keyVersion = (jbyte*)(env)->GetByteArrayElements( keyInfo, NULL);
+ jbyte * cuidValue = (jbyte*)(env)->GetByteArrayElements( CUID, NULL);
+
+ /* copy card and host challenge into input buffer */
+ for (i = 0; i < 8; i++)
+ {
+ input[i] = cc[i];
+ }
+ for (i = 0; i < 8; i++)
+ {
+ input[8+i] = hc[i];
+ }
+ PK11SymKey *symkey = NULL;
+
+ BYTE macData[KEYLENGTH];
+ char keyname[KEYNAMELENGTH];
+
+ GetDiversificationData(cuidValue,macData,mac);//keytype is mac
+
+ char *tokenNameChars;
+ PK11SlotInfo *slot = NULL;
+ if(tokenName)
+ {
+ tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
+ slot = ReturnSlot(tokenNameChars);
+ (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
+ }
+
+ char *keyNameChars=NULL;
+
+ if(keyName)
+ {
+ keyNameChars = (char *)(env)->GetStringUTFChars(keyName, NULL);
+ strcpy(keyname,keyNameChars);
+ (env)->ReleaseStringUTFChars(keyName, (const char *)keyNameChars);
+ }else
+ GetKeyName(keyVersion,keyname);
+
+ if (keyVersion[0] == 0x1 && keyVersion[1]== 0x1 &&strcmp( keyname, "#01#01") == 0)
+ {
+
+ /* default manufacturers key */
+ symkey = DeriveKey( //Util::DeriveKey(
+ Buffer((BYTE*)mac_key, KEYLENGTH), Buffer((BYTE*)hc, hc_len), Buffer((BYTE*)cc, cc_len));
+
+ if( slot )
+ PK11_FreeSlot( slot );
+
+ }else
+ {
+ PK11SymKey * masterKey = ReturnSymKey( slot,keyname);
+
+ /* We need to use internal so that the key
+ * can be exported by using PK11_GetKeyData()
+ */
+ if(masterKey == NULL)
+ {
+
+ if(slot)
+ PK11_FreeSlot(slot);
+ return NULL;
+ }
+
+ PK11SymKey *macKey =ComputeCardKeyOnToken(masterKey,macData);
+
+ if(macKey == NULL)
+ {
+
+ if(slot)
+ PK11_FreeSlot(slot);
+
+ PK11_FreeSymKey(masterKey);
+ return NULL;
+ }
+
+ symkey = DeriveKeyWithCardKey(macKey, Buffer((BYTE*)hc, hc_len), Buffer((BYTE*)cc, cc_len));
+
+ if(symkey == NULL)
+ {
+
+ if(slot)
+ PK11_FreeSlot(slot);
+
+ PK11_FreeSymKey( masterKey);
+ PK11_FreeSymKey( macKey);
+
+ return NULL;
+ }
+
+ if( slot )
+ PK11_FreeSlot( slot );
+
+ PK11_FreeSymKey( masterKey);
+ PK11_FreeSymKey( macKey);
+
+ }
+
+ /* status = EncryptData(kek_key, Buffer(cc,cc_len),out); */
+ jbyte * session_key = (jbyte *) (PK11_GetKeyData(symkey)->data);
+
+ if(session_key == NULL)
+ {
+ PK11_FreeSymKey(symkey);
+ return NULL;
+ }
+
+ jbyteArray handleBA=NULL;
+ jbyte *handleBytes=NULL;
+ handleBA = (env)->NewByteArray( KEYLENGTH);
+ handleBytes = (env)->GetByteArrayElements(handleBA, NULL);
+ memcpy(handleBytes, session_key,KEYLENGTH);
+ PK11_FreeSymKey( symkey);
+
+ (env)->ReleaseByteArrayElements( handleBA, handleBytes, 0);
+
+ (env)->ReleaseByteArrayElements(card_challenge, cc, JNI_ABORT);
+ (env)->ReleaseByteArrayElements(host_challenge, hc, JNI_ABORT);
+
+ (env)->ReleaseByteArrayElements(keyInfo, keyVersion, JNI_ABORT);
+ (env)->ReleaseByteArrayElements(CUID, cuidValue, JNI_ABORT);
+
+ return handleBA;
+}
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/*
+ * Class: com_netscape_cms_servlet_tks_RASessionKey
+ * Method: ComputeEncSessionKey
+ * Signature: ([B[B[B[B)[B
+ */
+ JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeEncSessionKey
+ (JNIEnv *, jclass, jstring, jstring, jbyteArray, jbyteArray, jbyteArray, jbyteArray, jbyteArray, jstring);
+#ifdef __cplusplus
+}
+#endif
+#define KEYLENGTH 16
+extern "C" JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeEncSessionKey(JNIEnv * env, jclass this2, jstring tokenName, jstring keyName, jbyteArray card_challenge, jbyteArray host_challenge, jbyteArray keyInfo, jbyteArray CUID, jbyteArray encKeyArray, jstring useSoftToken_s)
+{
+ /* hardcoded permanent enc key */
+ jbyte *enc_key = (jbyte*)(env)->GetByteArrayElements(encKeyArray, NULL);
+ char input[16];
+ int i;
+//char icv[8];
+
+ jbyte *cc = (jbyte*)(env)->GetByteArrayElements( card_challenge, NULL);
+ int cc_len = (env)->GetArrayLength(card_challenge);
+
+ jbyte *hc = (jbyte*)(env)->GetByteArrayElements( host_challenge, NULL);
+ // .size();
+ int hc_len = (env)->GetArrayLength( host_challenge);
+
+ jbyte * keyVersion = (jbyte*)(env)->GetByteArrayElements( keyInfo, NULL);
+ jbyte * cuidValue = (jbyte*)(env)->GetByteArrayElements( CUID, NULL);
+
+ /* copy card and host challenge into input buffer */
+ for (i = 0; i < 8; i++)
+ {
+ input[i] = cc[i];
+ }
+ for (i = 0; i < 8; i++)
+ {
+ input[8+i] = hc[i];
+ }
+ PK11SymKey *symkey = NULL;
+
+ BYTE encData[KEYLENGTH];
+ char keyname[KEYNAMELENGTH];
+ GetDiversificationData(cuidValue,encData,enc);
+ char *tokenNameChars;
+ PK11SlotInfo *slot = NULL;
+ if(tokenName)
+ {
+ tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
+ slot = ReturnSlot(tokenNameChars);
+ (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
+ }
+ char *keyNameChars=NULL;
+
+ if(keyName)
+ {
+ keyNameChars = (char *)(env)->GetStringUTFChars(keyName, NULL);
+ strcpy(keyname,keyNameChars);
+ (env)->ReleaseStringUTFChars(keyName, (const char *)keyNameChars);
+ }
+ else
+ {
+ GetKeyName(keyVersion,keyname);
+ }
+
+ if (keyVersion[0] == 0x1 && keyVersion[1]== 0x1 &&
+ strcmp( keyname, "#01#01") == 0)
+ {
+ /* default manufacturers key */
+ symkey = DeriveKey( //Util::DeriveKey(
+ Buffer((BYTE*)enc_key, KEYLENGTH), Buffer((BYTE*)hc, hc_len), Buffer((BYTE*)cc, cc_len));
+
+ if( slot )
+ PK11_FreeSlot( slot );
+ }else
+ {
+ PK11SymKey * masterKey = ReturnSymKey( slot,keyname);
+
+ /* We need to use internal so that the key
+ * can be exported by using PK11_GetKeyData()
+ */
+ if(masterKey == NULL)
+ {
+ if(slot)
+ PK11_FreeSlot(slot);
+ return NULL;
+
+ }
+
+ PK11SymKey *encKey =ComputeCardKeyOnToken(masterKey,encData);
+ if(encKey == NULL)
+ {
+ if(slot)
+ PK11_FreeSlot(slot);
+
+ PK11_FreeSymKey(masterKey);
+
+ return NULL;
+ }
+
+ symkey = DeriveKeyWithCardKey(encKey, Buffer((BYTE*)hc, hc_len), Buffer((BYTE*)cc, cc_len));
+
+ PK11_FreeSymKey( masterKey);
+ PK11_FreeSymKey( encKey);
+
+ if(slot)
+ PK11_FreeSlot(slot);
+
+ }
+ /* status = EncryptData(kek_key, Buffer(cc,cc_len),out); */
+
+ if(symkey == NULL)
+ {
+ return NULL;
+ }
+
+ jbyte * session_key = (jbyte *) (PK11_GetKeyData(symkey)->data);
+
+ jbyteArray handleBA=NULL;
+ jbyte *handleBytes=NULL;
+ handleBA = (env)->NewByteArray( KEYLENGTH);
+ handleBytes = (env)->GetByteArrayElements(handleBA, NULL);
+ memcpy(handleBytes, session_key,KEYLENGTH);
+ PK11_FreeSymKey( symkey);
+
+ (env)->ReleaseByteArrayElements( handleBA, handleBytes, 0);
+
+ (env)->ReleaseByteArrayElements(card_challenge, cc, JNI_ABORT);
+ (env)->ReleaseByteArrayElements(host_challenge, hc, JNI_ABORT);
+
+ (env)->ReleaseByteArrayElements(keyInfo, keyVersion, JNI_ABORT);
+ (env)->ReleaseByteArrayElements(CUID, cuidValue, JNI_ABORT);
+
+ return handleBA;
+}
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/*
+ * Class: com_netscape_cms_servlet_tks_RASessionKey
+ * Method: ComputeKekSessionKey
+ * Signature: ([B[B[B[B)[B
+ */
+ JNIEXPORT jobject JNICALL Java_com_netscape_symkey_SessionKey_ComputeKekSessionKey
+ (JNIEnv *, jclass, jstring, jstring, jbyteArray, jbyteArray, jbyteArray, jbyteArray, jbyteArray, jstring);
+#ifdef __cplusplus
+}
+#endif
+#define KEYLENGTH 16
+extern "C" JNIEXPORT jobject JNICALL Java_com_netscape_symkey_SessionKey_ComputeKekSessionKey(JNIEnv * env, jclass this2, jstring tokenName, jstring keyName, jbyteArray card_challenge, jbyteArray host_challenge, jbyteArray keyInfo, jbyteArray CUID, jbyteArray kekKeyArray, jstring useSoftToken_s)
+{
+ /* hardcoded permanent kek key */
+ jbyte *kek_key = (jbyte*)(env)->GetByteArrayElements(kekKeyArray, NULL);
+ char input[16];
+ int i;
+//char icv[8];
+
+ PRFileDesc *debug_fd = NULL;
+
+#ifdef DRM_SUPPORT_DEBUG
+ debug_fd = PR_Open("/tmp/debug1.cfu",
+ PR_RDWR | PR_CREATE_FILE | PR_APPEND,
+ 400 | 200);
+ PR_fprintf(debug_fd,"ComputeKekSessionKey\n");
+#endif // DRM_SUPPORT_DEBUG
+
+ jbyte *cc = (jbyte*)(env)->GetByteArrayElements( card_challenge, NULL);
+ int cc_len = (env)->GetArrayLength(card_challenge);
+
+ jbyte *hc = (jbyte*)(env)->GetByteArrayElements( host_challenge, NULL);
+ // .size();
+ int hc_len = (env)->GetArrayLength( host_challenge);
+
+ jbyte * keyVersion = (jbyte*)(env)->GetByteArrayElements( keyInfo, NULL);
+ jbyte * cuidValue = (jbyte*)(env)->GetByteArrayElements( CUID, NULL);
+
+ /* copy card and host challenge into input buffer */
+ for (i = 0; i < 8; i++)
+ {
+ input[i] = cc[i];
+ }
+ for (i = 0; i < 8; i++)
+ {
+ input[8+i] = hc[i];
+ }
+ PK11SymKey *symkey = NULL;
+
+ BYTE kekData[KEYLENGTH];
+ char keyname[KEYNAMELENGTH];
+ GetDiversificationData(cuidValue,kekData,kek);//keytype is kek
+ char *tokenNameChars;
+ PK11SlotInfo *slot = NULL;
+ if (tokenName)
+ {
+ tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
+ slot = ReturnSlot(tokenNameChars);
+ (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
+ }
+ char *keyNameChars=NULL;
+ if (keyName)
+ {
+ keyNameChars = (char *)(env)->GetStringUTFChars(keyName, NULL);
+ strcpy(keyname,keyNameChars);
+ (env)->ReleaseStringUTFChars(keyName, (const char *)keyNameChars);
+ } else {
+ GetKeyName(keyVersion,keyname);
+ }
+
+ if (keyVersion[0] == 0x1 && keyVersion[1]== 0x1 &&strcmp( keyname, "#01#01") == 0)
+ {
+ /* default manufacturers key */
+ symkey = DeriveKey( //Util::DeriveKey(
+ Buffer((BYTE*)kek_key, KEYLENGTH), Buffer((BYTE*)hc, hc_len), Buffer((BYTE*)cc, cc_len));
+ } else {
+ PK11SymKey * masterKey = ReturnSymKey( slot,keyname);
+
+ /* We need to use internal so that the key
+ * can be exported by using PK11_GetKeyData()
+ */
+ if(masterKey == NULL)
+ {
+ if(slot)
+ PK11_FreeSlot(slot);
+ return NULL;
+ }
+
+ PK11SymKey *kekKey =ComputeCardKeyOnToken(masterKey,kekData);
+ if (kekKey == NULL)
+ {
+ if(slot)
+ PK11_FreeSlot(slot);
+
+ PK11_FreeSymKey(masterKey);
+ return NULL;
+ }
+
+ symkey = DeriveKeyWithCardKey(kekKey, Buffer((BYTE*)hc, hc_len), Buffer((BYTE*)cc, cc_len));
+
+ PK11_FreeSymKey( masterKey);
+ PK11_FreeSymKey( kekKey);
+
+ if(slot)
+ PK11_FreeSlot(slot);
+
+ }
+ /* status = EncryptData(kek_key, Buffer(cc,cc_len),out); */
+
+ if(symkey == NULL)
+ {
+ return NULL;
+ }
+
+ if (debug_fd)
+ PR_fprintf(debug_fd,"ComputeKekSessionKey: got kek session key\n");
+
+ jobject keyObj = JSS_PK11_wrapSymKey(env, &symkey, debug_fd);
+ if (keyObj == NULL)
+ {
+ if (debug_fd)
+ PR_fprintf(debug_fd,"ComputeKekSessionKey called wrapSymKey, key NULL\n");
+ }
+ else
+ {
+ if (debug_fd)
+ PR_fprintf(debug_fd,"ComputeKekSessionKey called wrapSymKey, key not NULL\n");
+ }
+ return keyObj;
+}
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/*
+ * Class: com_netscape_cms_servlet_tks_RASessionKey
+ * Method: ComputeKekKey
+ * Signature: ([B[B[B[B)[B
+ */
+ JNIEXPORT jobject JNICALL Java_com_netscape_symkey_SessionKey_ComputeKekKey
+ (JNIEnv *, jclass, jstring, jstring, jbyteArray, jbyteArray, jbyteArray, jbyteArray, jbyteArray, jstring);
+#ifdef __cplusplus
+}
+#endif
+#define KEYLENGTH 16
+extern "C" JNIEXPORT jobject JNICALL Java_com_netscape_symkey_SessionKey_ComputeKekKey(JNIEnv * env, jclass this2, jstring tokenName, jstring keyName, jbyteArray card_challenge, jbyteArray host_challenge, jbyteArray keyInfo, jbyteArray CUID, jbyteArray kekKeyArray, jstring useSoftToken_s)
+{
+ /* hardcoded permanent kek key */
+ jbyte *kek_key = (jbyte*)(env)->GetByteArrayElements(kekKeyArray, NULL);
+ char input[16];
+ int i;
+//char icv[8];
+ jobject keyObj = NULL;
+
+ PRFileDesc *debug_fd = NULL;
+
+#ifdef DRM_SUPPORT_DEBUG
+ debug_fd = PR_Open("/tmp/debug1.cfu",
+ PR_RDWR | PR_CREATE_FILE | PR_APPEND,
+ 400 | 200);
+ PR_fprintf(debug_fd,"ComputeKekKey\n");
+#endif // DRM_SUPPORT_DEBUG
+
+ jbyte *cc = (jbyte*)(env)->GetByteArrayElements( card_challenge, NULL);
+ jbyte *hc = (jbyte*)(env)->GetByteArrayElements( host_challenge, NULL);
+ jbyte * keyVersion = (jbyte*)(env)->GetByteArrayElements( keyInfo, NULL);
+ jbyte * cuidValue = (jbyte*)(env)->GetByteArrayElements( CUID, NULL);
+
+ /* copy card and host challenge into input buffer */
+ for (i = 0; i < 8; i++)
+ {
+ input[i] = cc[i];
+ }
+ for (i = 0; i < 8; i++)
+ {
+ input[8+i] = hc[i];
+ }
+
+ PK11SlotInfo *internalSlot = NULL;
+ PK11SymKey *masterKey = NULL;
+ PK11SymKey *kekKey = NULL;
+ BYTE kekData[KEYLENGTH];
+ char keyname[KEYNAMELENGTH];
+ GetDiversificationData(cuidValue,kekData,kek);//keytype is kek
+ char *tokenNameChars;
+ PK11SlotInfo *slot = NULL;
+ if (tokenName)
+ {
+ tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
+ slot = ReturnSlot(tokenNameChars);
+ (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
+ }
+ char *keyNameChars=NULL;
+ if (keyName)
+ {
+ keyNameChars = (char *)(env)->GetStringUTFChars(keyName, NULL);
+ strcpy(keyname,keyNameChars);
+ (env)->ReleaseStringUTFChars(keyName, (const char *)keyNameChars);
+ }else
+ GetKeyName(keyVersion,keyname);
+
+ if (keyVersion[0] == 0x1 && keyVersion[1]== 0x1 &&
+ strcmp( keyname, "#01#01") == 0)
+ {
+ /* default manufacturers key */
+ if (debug_fd)
+ PR_fprintf(debug_fd,"ComputeKekKey shouldn't get here\n");
+
+ BYTE masterKeyData[24];
+ SECItem masterKeyItem = {siBuffer, masterKeyData, sizeof(masterKeyData)};
+
+ memcpy(masterKeyData, (char*)kek_key, 16);
+ memcpy(masterKeyData+16, (char*)kek_key, 8);
+ if (debug_fd)
+ PR_fprintf(debug_fd, "ComputeKekKey DRMproto before import\n");
+ kekKey = PK11_ImportSymKeyWithFlags(slot, CKM_DES3_ECB,
+ PK11_OriginUnwrap, CKA_ENCRYPT, &masterKeyItem,
+ ALL_SYMKEY_OPS /*CKF_ENCRYPT*/, PR_FALSE, 0);
+
+ if( slot )
+ PK11_FreeSlot( slot );
+
+ } else {
+ masterKey = ReturnSymKey( slot,keyname);
+ /* We need to use internal so that the key
+ * can be exported by using PK11_GetKeyData()
+ */
+ if(masterKey == NULL)
+ {
+ if(slot)
+ PK11_FreeSlot(slot);
+ return NULL;
+ }
+
+ kekKey =ComputeCardKeyOnToken(masterKey,kekData);
+
+ }
+
+ if(kekKey == NULL)
+ {
+ if(slot)
+ PK11_FreeSlot(slot);
+
+ if(masterKey)
+ PK11_FreeSymKey(masterKey);
+
+ return NULL;
+ }
+ if (debug_fd)
+ PR_fprintf(debug_fd,"ComputeKekKey: got kek key\n");
+
+ keyObj = JSS_PK11_wrapSymKey(env, &kekKey, debug_fd);
+ if (keyObj == NULL)
+ {
+ if (debug_fd)
+ PR_fprintf(debug_fd,"ComputeKekKey: keyObj is NULL\n");
+ }
+ else
+ {
+ if (debug_fd)
+ PR_fprintf(debug_fd,"ComputeKekKey: keyObj is not NULL\n");
+ }
+
+ if(masterKey)
+ PK11_FreeSymKey( masterKey);
+
+ if(kekKey)
+ PK11_FreeSymKey( kekKey);
+
+ if(slot)
+ PK11_FreeSlot(slot);
+
+ if(internalSlot)
+ PK11_FreeSlot(internalSlot);
+
+ return keyObj;
+}
+
+
+PRStatus ComputeMAC(PK11SymKey *key, Buffer &x_input,
+const Buffer &icv, Buffer &output)
+{
+ PRStatus rv = PR_SUCCESS;
+ PK11Context *context = NULL;
+// NetkeyICV temp;
+ unsigned char result[8];
+ int i;
+ SECStatus s;
+ int len;
+#ifdef USE_DESMAC
+ CK_ULONG macLen = sizeof result;
+ SECItem params = { siBuffer, (unsigned char *)&macLen, sizeof macLen };
+#endif
+ static SECItem noParams = { siBuffer, 0, 0 };
+ static unsigned char macPad[] =
+ {
+ 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+ };
+ BYTE *input = (BYTE *) x_input;
+ int inputLen = x_input.size();
+
+ if(key == NULL)
+ {
+ rv = PR_FAILURE; goto done;
+ }
+
+#ifdef USE_DESMAC
+ context = PK11_CreateContextBySymKey(CKM_DES3_MAC_GENERAL, CKA_SIGN,
+ key, &params);
+ if (!context) { rv = PR_FAILURE; goto done; }
+
+ s = PK11_DigestBegin(context);
+ if (s != SECSuccess) { rv = PR_FAILURE; goto done; }
+
+ s = PK11_DigestOp(context, icv, 8);
+ if (s != SECSuccess) { rv = PR_FAILURE; goto done; }
+
+ while(inputLen >= 8)
+ {
+ s = PK11_DigestOp(context, input, 8);
+ if (s != SECSuccess) { rv = PR_FAILURE; goto done; }
+
+ input += 8;
+ inputLen -= 8;
+ }
+
+ for (i = 0;i < inputLen;i++)
+ {
+ result[i] = input[i];
+ }
+
+ input = macPad;
+ for(;i < 8;i++)
+ {
+ result[i] = *input++;
+ }
+
+ s = PK11_DigestOp(context, result, sizeof result);
+ if (s != SECSuccess) { rv = PR_FAILURE; goto done; }
+
+ s = PK11_DigestFinal(context, output, (unsigned int *)&len, sizeof output);
+ if (1 != SECSuccess) { rv = PR_FAILURE; goto done; }
+
+#else
+
+ context = PK11_CreateContextBySymKey(CKM_DES3_ECB, CKA_ENCRYPT, key, &noParams);
+ if (!context) { rv = PR_FAILURE; goto done; }
+
+ memcpy(result, icv, sizeof result);
+
+ /* Process whole blocks */
+ while (inputLen >= 8)
+ {
+ for(i = 0;i < 8;i++)
+ {
+ result[i] ^= input[i];
+ }
+
+ s = PK11_CipherOp(context, result, &len, sizeof result, result, sizeof result);
+ if (s != SECSuccess) { rv = PR_FAILURE; goto done; }
+ if (len != sizeof result) /* assert? */
+ {
+//PR_SetError(PR_UNKNOWN_ERROR, 0);
+ rv = PR_FAILURE;
+ goto done;
+ }
+
+ input += 8;
+ inputLen -= 8;
+ }
+
+/*
+ * Fold in remaining data (if any)
+ * Set i to number of bytes processed
+ */
+ for(i = 0;i < inputLen;i++)
+ {
+ result[i] ^= input[i];
+ }
+
+ /*
+ * Fill remainder of last block. There
+ * will be at least one byte handled here.
+ */
+ input = macPad;
+ while(i < 8)
+ {
+ result[i] ^= *input++;
+ i++;
+ }
+
+ s = PK11_CipherOp(context, result, &len, sizeof result, result, sizeof result);
+ if (s != SECSuccess) { rv = PR_FAILURE; goto done; }
+ if (len != sizeof result)
+ {
+//PR_SetError(PR_UNKNOWN_ERROR, 0);
+ rv = PR_FAILURE;
+ goto done;
+ }
+
+ output.replace(0, result, sizeof result);
+#endif
+
+ done:
+ if (context)
+ {
+ PK11_Finalize(context);
+ PK11_DestroyContext(context, PR_TRUE);
+ }
+ memset(result, 0, sizeof result);
+
+ return rv;
+} /* ComputeMAC */
+
+
+//=================================================================================
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/*
+ * Class: com_netscape_cms_servlet_tks_RASessionKey
+ * Method: ComputeCryptogram
+ * Signature: ([B[B[B[B)[B
+ */
+ JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeCryptogram
+ (JNIEnv *, jclass, jstring, jstring, jbyteArray, jbyteArray, jbyteArray, jbyteArray, int, jbyteArray, jstring);
+#ifdef __cplusplus
+}
+#endif
+#define KEYLENGTH 16
+extern "C" JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeCryptogram(JNIEnv * env, jclass this2, jstring tokenName, jstring keyName, jbyteArray card_challenge, jbyteArray host_challenge, jbyteArray keyInfo, jbyteArray CUID, int type, jbyteArray authKeyArray, jstring useSoftToken_s)
+{
+/* hardcore permanent mac key */
+ jbyte *auth_key = (jbyte*)(env)->GetByteArrayElements(authKeyArray, NULL);
+ char input[16];
+ int i;
+//char icv[8];
+ jbyte *cc = (jbyte*)(env)->GetByteArrayElements( card_challenge, NULL);
+ int cc_len = (env)->GetArrayLength(card_challenge);
+
+ jbyte *hc = (jbyte*)(env)->GetByteArrayElements( host_challenge, NULL);
+ // .size();
+ int hc_len = (env)->GetArrayLength( host_challenge);
+
+ jbyte * keyVersion = (jbyte*)(env)->GetByteArrayElements( keyInfo, NULL);
+ jbyte * cuidValue = (jbyte*)(env)->GetByteArrayElements( CUID, NULL);
+
+ if (type == 0) // compute host cryptogram
+ {
+ /* copy card and host challenge into input buffer */
+ for (i = 0; i < 8; i++)
+ {
+ input[i] = cc[i];
+ }
+ for (i = 0; i < 8; i++)
+ {
+ input[8+i] = hc[i];
+ }
+ } // compute card cryptogram
+ else if (type == 1)
+ {
+ for (i = 0; i < 8; i++)
+ {
+ input[i] = hc[i];
+ }
+ for (i = 0; i < 8; i++)
+ {
+ input[8+i] = cc[i];
+ }
+ }
+
+ PK11SymKey *symkey = NULL;
+
+ BYTE authData[KEYLENGTH];
+ char keyname[KEYNAMELENGTH];
+ GetDiversificationData(cuidValue,authData,enc);
+ char *tokenNameChars;
+ PK11SlotInfo *slot = NULL;
+ if (tokenName)
+ {
+ tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
+ slot = ReturnSlot(tokenNameChars);
+ (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
+ }
+ char *keyNameChars=NULL;
+
+ if (keyName)
+ {
+ keyNameChars = (char *)(env)->GetStringUTFChars(keyName, NULL);
+ strcpy(keyname,keyNameChars);
+ (env)->ReleaseStringUTFChars(keyName, (const char *)keyNameChars);
+ }else
+ GetKeyName(keyVersion,keyname);
+
+ if (keyVersion[0] == 0x1 && keyVersion[1]== 0x1 &&
+ strcmp( keyname, "#01#01") == 0)
+ {
+ /* default manufacturers key */
+ symkey = DeriveKey( //Util::DeriveKey(
+ Buffer((BYTE*)auth_key, KEYLENGTH), Buffer((BYTE*)hc, hc_len), Buffer((BYTE*)cc, cc_len));
+
+ if( slot )
+ PK11_FreeSlot( slot );
+ }
+ else
+ {
+ PK11SymKey * masterKey = ReturnSymKey( slot,keyname);
+ if (masterKey == NULL)
+ {
+ if(slot)
+ PK11_FreeSlot(slot);
+
+ return NULL;
+ }
+
+ PK11SymKey *authKey = ComputeCardKeyOnToken(masterKey,authData);
+ if (authKey == NULL)
+ {
+ if(slot)
+ PK11_FreeSlot(slot);
+
+ PK11_FreeSymKey( masterKey);
+ return NULL;
+ }
+
+ if(slot)
+ PK11_FreeSlot(slot);
+
+ symkey = DeriveKeyWithCardKey(authKey,
+ Buffer((BYTE*)hc, hc_len), Buffer((BYTE*)cc, cc_len));
+
+ PK11_FreeSymKey( masterKey);
+ PK11_FreeSymKey( authKey);
+ }
+
+ if(symkey == NULL)
+ {
+ return NULL;
+ }
+
+ Buffer icv = Buffer(8, (BYTE)0);
+ Buffer output = Buffer(8, (BYTE)0);
+ Buffer input_x = Buffer((BYTE*)input, 16);
+ ComputeMAC(symkey, input_x, icv, output);
+ jbyte * session_key = (jbyte *) (BYTE*)output;
+
+ jbyteArray handleBA=NULL;
+ jbyte *handleBytes=NULL;
+ handleBA = (env)->NewByteArray( 8);
+ handleBytes = (env)->GetByteArrayElements(handleBA, NULL);
+ memcpy(handleBytes, session_key,8);
+ PK11_FreeSymKey( symkey);
+ (env)->ReleaseByteArrayElements( handleBA, handleBytes, 0);
+ (env)->ReleaseByteArrayElements(card_challenge, cc, JNI_ABORT);
+ (env)->ReleaseByteArrayElements(host_challenge, hc, JNI_ABORT);
+ (env)->ReleaseByteArrayElements(keyInfo, keyVersion, JNI_ABORT);
+ (env)->ReleaseByteArrayElements(CUID, cuidValue, JNI_ABORT);
+
+ return handleBA;
+}
+
+
+//=================================================================================
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/*
+ * Class: com_netscape_cms_servlet_tks_RASessionKey
+ * Method: ComputeCardCryptogram
+ * Signature: ([B[B[B[B)[B
+ */
+ JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeCardCryptogram
+ (JNIEnv *, jclass, jbyteArray, jbyteArray, jbyteArray);
+#ifdef __cplusplus
+}
+#endif
+#define KEYLENGTH 16
+extern "C" JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_ComputeCardCryptogram(JNIEnv * env, jclass this2, jbyteArray auth_key, jbyteArray card_challenge, jbyteArray host_challenge)
+{
+ char input[16];
+ int i;
+
+ jbyte *ak = (jbyte*)(env)->GetByteArrayElements( auth_key, NULL);
+ int ak_len = (env)->GetArrayLength(auth_key);
+
+ jbyte *cc = (jbyte*)(env)->GetByteArrayElements( card_challenge, NULL);
+ int cc_len = (env)->GetArrayLength(card_challenge);
+
+ jbyte *hc = (jbyte*)(env)->GetByteArrayElements( host_challenge, NULL);
+ // .size();
+ int hc_len = (env)->GetArrayLength( host_challenge);
+
+ for (i = 0; i < 8; i++)
+ {
+ input[i] = hc[i];
+ }
+ for (i = 0; i < 8; i++)
+ {
+ input[8+i] = cc[i];
+ }
+
+ PK11SymKey *symkey = NULL;
+
+ /* default manufacturers key */
+ symkey = DeriveKey( //Util::DeriveKey(
+ Buffer((BYTE*)ak, ak_len), Buffer((BYTE*)hc, hc_len), Buffer((BYTE*)cc, cc_len));
+
+ Buffer icv = Buffer(8, (BYTE)0);
+ Buffer output = Buffer(8, (BYTE)0);
+ Buffer input_x = Buffer((BYTE*)input, 16);
+ ComputeMAC(symkey, input_x, icv, output);
+ jbyte * session_key = (jbyte *) (BYTE*)output;
+
+ jbyteArray handleBA=NULL;
+ jbyte *handleBytes=NULL;
+ handleBA = (env)->NewByteArray( 8);
+ handleBytes = (env)->GetByteArrayElements(handleBA, NULL);
+ memcpy(handleBytes, session_key,8);
+ PK11_FreeSymKey( symkey);
+ (env)->ReleaseByteArrayElements( handleBA, handleBytes, 0);
+ (env)->ReleaseByteArrayElements(auth_key, ak, JNI_ABORT);
+ (env)->ReleaseByteArrayElements(card_challenge, cc, JNI_ABORT);
+ (env)->ReleaseByteArrayElements(host_challenge, hc, JNI_ABORT);
+
+ return handleBA;
+}
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/*
+ * Class: com_netscape_cms_servlet_tks_ECBencrypt
+ * Method: ECBencrypt
+ * Signature: ([B[B[B[B)[B
+ */
+ JNIEXPORT jbyteArray JNICALL
+ Java_com_netscape_symkey_SessionKey_ECBencrypt
+ (JNIEnv*, jclass, jobject, jbyteArray);
+#ifdef __cplusplus
+}
+#endif
+extern "C" JNIEXPORT jbyteArray JNICALL
+Java_com_netscape_symkey_SessionKey_ECBencrypt
+(JNIEnv* env, jclass this2, jobject symkeyObj, jbyteArray data)
+{
+ jbyteArray handleBA=NULL;
+ jint datalen, i;
+ jint dlen=16; // applet only supports 16 bytes
+ jbyte *databytes=NULL;
+ jbyte *handleBytes=NULL;
+
+ PK11SymKey *symkey = NULL;
+ PK11Context *context = NULL;
+ PRStatus r = PR_FAILURE;
+ SECStatus s = SECFailure;
+ int lenx;
+ static SECItem noParams = { siBuffer, 0, 0 };
+
+ unsigned char result[8];
+/*
+ PRFileDesc *debug_fd = PR_Open("/tmp/debug.cfu",
+ PR_RDWR | PR_CREATE_FILE | PR_APPEND,
+ 400 | 200);
+
+ PR_fprintf(debug_fd,"ECBencrypt\n");
+*/
+ r = JSS_PK11_getSymKeyPtr(env, symkeyObj, &symkey);
+ if (r != PR_SUCCESS)
+ {
+ goto finish;
+ }
+
+ datalen = (jint)(env)->GetArrayLength(data);
+ databytes = (jbyte*)(env)->GetByteArrayElements(data, NULL);
+ if( databytes == NULL )
+ {
+ goto finish;
+ }
+
+ if( ! symkey )
+ {
+ goto finish;
+ }
+
+ context = PK11_CreateContextBySymKey(CKM_DES3_ECB, CKA_ENCRYPT, symkey,
+ &noParams);
+ if (!context)
+ {
+ goto finish;
+ }
+
+ if (datalen > 16)
+ dlen = 16; // applet suports only 16 bytes
+
+ handleBA = (env)->NewByteArray(dlen);
+ if(handleBA == NULL )
+ {
+ goto finish;
+ }
+ handleBytes = (jbyte *)(env)->GetByteArrayElements(handleBA, NULL);
+
+ if(handleBytes==NULL)
+ {
+ goto finish;
+ }
+
+ for (i=0; i< dlen; i+=8)
+ {
+ s = PK11_CipherOp(context, result, &lenx, 8, (unsigned char *)&databytes[i], 8);
+ if (s != SECSuccess)
+ {
+ goto finish;
+ }
+ memcpy(handleBytes+i, result, 8);
+ }
+
+ (env)->ReleaseByteArrayElements( handleBA, handleBytes, 0);
+
+ finish:
+ if (context) PK11_DestroyContext(context, PR_TRUE);
+
+ return handleBA;
+}
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/*
+ * Class: com_netscape_cms_servlet_tks_GenerateSymkey
+ * Method: GenerateSymkey
+ * Signature: ([B[B[B[B)[B
+ */
+ JNIEXPORT jobject JNICALL
+ Java_com_netscape_symkey_SessionKey_GenerateSymkey
+ (JNIEnv*, jclass, jstring);
+#ifdef __cplusplus
+}
+#endif
+extern "C" JNIEXPORT jobject JNICALL
+Java_com_netscape_symkey_SessionKey_GenerateSymkey
+(JNIEnv* env, jclass this2, jstring tokenName)
+{
+ jint keylen=24;
+ jobject keyObj = NULL;
+
+ PK11SymKey *okey = NULL;
+ PK11SymKey *key = NULL;
+ char *tokenNameChars;
+
+ PK11SlotInfo *slot = NULL;
+ SECStatus s = SECFailure;
+
+ SECItem* okeyItem = NULL;
+ unsigned char keyData[24];
+ SECItem keyItem = {siBuffer, keyData, sizeof(keyData) };
+/*
+PRFileDesc *debug_fd = PR_Open("/tmp/debug.cfu",
+ PR_RDWR | PR_CREATE_FILE | PR_APPEND,
+ 400 | 200);
+
+PR_fprintf(debug_fd,"GenerateSymkey\n");
+*/
+ if (tokenName)
+ {
+ tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
+ slot = ReturnSlot(tokenNameChars);
+ (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
+ }
+
+ okey = PK11_TokenKeyGen(slot, CKM_DES2_KEY_GEN,0, 0, 0, PR_FALSE, NULL);
+ if (okey == NULL)
+ goto finish;
+
+ s= PK11_ExtractKeyValue(okey);
+
+ if (s != SECSuccess)
+ goto finish;
+
+ okeyItem = PK11_GetKeyData( okey);
+
+ if (okeyItem == NULL)
+ goto finish;
+
+ memcpy(keyData, okeyItem->data, 16);
+
+// make the 3rd 8 bytes the same as the 1st
+ if (keylen == 24)
+ {
+ memcpy(keyData+16, okeyItem->data, 8);
+
+ keyItem.len = keylen;
+ }
+
+ key = PK11_ImportSymKeyWithFlags(slot, CKM_DES3_ECB,
+ PK11_OriginGenerated, CKA_ENCRYPT, &keyItem,
+ CKF_ENCRYPT, PR_FALSE, 0);
+ if( ! key )
+ {
+ goto finish;
+ }
+
+ /* wrap the symkey in java object. This sets symkey to NULL. */
+ keyObj = JSS_PK11_wrapSymKey(env, &key, NULL);
+
+finish:
+ if (slot) PK11_FreeSlot(slot);
+ if (okey) PK11_FreeSymKey(okey);
+ if (key) PK11_FreeSymKey(key);
+
+ return keyObj;
+}
+
+
+// begin DRM proto
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/*
+ * Class: com_netscape_cms_servlet_tks_RASessionKey
+ * Method: bytes2PK11SymKey
+ * Signature:
+ */
+ JNIEXPORT jobject JNICALL Java_com_netscape_symkey_SessionKey_bytes2PK11SymKey
+ (JNIEnv *, jclass, jbyteArray);
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef DRM_SUPPORT_DEBUG
+extern "C" JNIEXPORT jobject JNICALL Java_com_netscape_symkey_SessionKey_bytes2PK11SymKey(JNIEnv * env, jclass this2, jbyteArray symKeyBytes)
+{
+ PK11SlotInfo *slot=NULL;
+ jobject keyObj = NULL;
+ PK11SymKey *symKey=NULL;
+
+// how about do unwrap (decrypt of the symkey in here??
+
+// DRM proto just use internal slot
+ slot = PK11_GetInternalKeySlot();
+
+ BYTE masterKeyData[24];
+ SECItem masterKeyItem = {siBuffer, masterKeyData, sizeof(masterKeyData)};
+
+ memcpy(masterKeyData, (char*)symKeyBytes, 16);
+ memcpy(masterKeyData+16, (char*)symKeyBytes, 8);
+ PR_fprintf(debug_fd, "DRMproto before import\n");
+ symKey = PK11_ImportSymKeyWithFlags(slot, CKM_DES3_ECB,
+ PK11_OriginUnwrap, CKA_ENCRYPT, &masterKeyItem,
+ ALL_SYMKEY_OPS /*CKF_ENCRYPT*/, PR_FALSE, 0);
+
+ /* wrap the symkey in java object. This sets symkey to NULL. */
+ keyObj = JSS_PK11_wrapSymKey(env, &symKey, debug_fd);
+
+finish:
+ return keyObj;
+}
+
+
+// end DRM proto
+#endif // DRM_SUPPORT_DEBUG
diff --git a/pki/base/symkey/src/com/netscape/symkey/SessionKey.java b/pki/base/symkey/src/com/netscape/symkey/SessionKey.java
new file mode 100644
index 000000000..c93e8491e
--- /dev/null
+++ b/pki/base/symkey/src/com/netscape/symkey/SessionKey.java
@@ -0,0 +1,136 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+package com.netscape.symkey;
+
+
+import java.io.*;
+import java.util.*;
+import org.mozilla.jss.pkcs11.*;
+
+
+/**
+ * This object contains the OS independent interfaces.
+ */
+public class SessionKey
+{
+ static
+ {
+ try {
+ System.loadLibrary( "symkey" );
+ } catch( Throwable t ) {
+ // This is bad news, the program is doomed at this point
+ t.printStackTrace();
+ }
+ }
+
+ // external calls from RA
+ public static native byte[] ComputeKeyCheck( byte data[] );
+
+ public static native byte[] ComputeCardCryptogram( byte[] raw_auth_key,
+ byte[] card_challenge,
+ byte[] host_challenge );
+
+ public static native byte[] ComputeSessionKey( String tokenName,
+ String keyName,
+ byte[] card_challenge,
+ byte[] host_challenge,
+ byte[] keyInfo,
+ byte[] CUID,
+ byte[] macKeyArray,
+ String useSoftToken );
+
+ public static native byte[] ComputeEncSessionKey( String tokenName,
+ String keyName,
+ byte[] card_challenge,
+ byte[] host_challenge,
+ byte[] keyInfo,
+ byte[] CUID,
+ byte[] encKeyArray,
+ String useSoftToken );
+
+ public static native PK11SymKey ComputeKekSessionKey( String tokenName,
+ String keyName,
+ byte[] card_challenge,
+ byte[] host_challenge,
+ byte[] keyInfo,
+ byte[] CUID,
+ byte[] kekKeyArray,
+ String useSoftToken );
+
+ public static native PK11SymKey ComputeKekKey( String tokenName,
+ String keyName,
+ byte[] card_challenge,
+ byte[] host_challenge,
+ byte[] keyInfo,
+ byte[] CUID,
+ byte[] kekKeyArray,
+ String useSoftToken );
+
+ public static native byte[] ECBencrypt( PK11SymKey key,
+ byte[] data );
+
+ public static native PK11SymKey GenerateSymkey( String tokenName );
+
+ /*
+ * DRM_SUPPORT_DEBUG
+ */
+
+ // public static native PK11SymKey bytes2PK11SymKey( byte[] symKeyBytes );
+
+ public static native byte[] ComputeCryptogram( String tokenName,
+ String keyName,
+ byte[] card_challenge,
+ byte[] host_challenge,
+ byte[] keyInfo,
+ byte[] CUID,
+ int type,
+ byte[] authKeyArray,
+ String useSoftToken );
+
+ public static native byte[] EncryptData( String tokenName,
+ String keyName,
+ byte[] in,
+ byte[] keyInfo,
+ byte[] CUID,
+ byte[] kekKeyArray,
+ String useSoftToken );
+
+ public static native byte[] DiversifyKey( String tokenName,
+ String newTokenName,
+ String oldMasterKeyName,
+ String newMasterKeyName,
+ String keyInfo,
+ byte[] CUIDValue,
+ byte[] kekKeyArray,
+ String useSoftToken );
+
+ // internal calls from config TKS keys tab
+ public static native String GenMasterKey( String token,
+ String keyName );
+
+ public static native String DeleteSymmetricKey( String token,
+ String keyName );
+
+ public static native String ListSymmetricKeys( String token );
+
+ // set when called from the config TKS tab to create master key
+ // get when called from the RA to create session key
+ public static native void SetDefaultPrefix( String masterPrefix );
+}
+
diff --git a/pki/base/symkey/src/com/netscape/symkey/SymKey.cpp b/pki/base/symkey/src/com/netscape/symkey/SymKey.cpp
new file mode 100644
index 000000000..d5b5ee917
--- /dev/null
+++ b/pki/base/symkey/src/com/netscape/symkey/SymKey.cpp
@@ -0,0 +1,1132 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#include <stdio.h>
+#include <string.h>
+
+#if defined(WIN32)
+#include "fcntl.h"
+#include "io.h"
+#endif
+
+#if defined(XP_UNIX)
+#include <unistd.h>
+#include <sys/time.h>
+#include <termios.h>
+#endif
+
+#if defined(XP_WIN) || defined (XP_PC)
+#include <time.h>
+#include <conio.h>
+#endif
+
+#include "nspr.h"
+#include "prtypes.h"
+#include "prtime.h"
+#include "prlong.h"
+#include "pk11func.h"
+#include "secasn1.h"
+#include "cert.h"
+#include "cryptohi.h"
+#include "secoid.h"
+#include "certdb.h"
+#include "nss.h"
+
+#include "seccomon.h"
+#include "nspr.h"
+#ifdef __cplusplus
+#include <jni.h>
+#include <assert.h>
+#include <string.h>
+
+}
+#endif
+#include <memory.h>
+#include <assert.h>
+#include <stdio.h>
+#include <cstdarg>
+#include <string>
+
+#include "Buffer.h"
+#include "SymKey.h"
+
+typedef unsigned char BYTE;
+
+typedef struct
+{
+ enum
+ {
+ PW_NONE = 0,
+ PW_FROMFILE = 1,
+ PW_PLAINTEXT = 2,
+ PW_EXTERNAL = 3
+ } source;
+ char *data;
+} secuPWData;
+
+char masterKeyPrefix[PREFIXLENGHT];
+char masterKeyNickName[KEYNAMELENGTH];
+char masterNewKeyNickName[KEYNAMELENGTH];
+
+//=================================================================================
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+/*
+ * Class: com_netscape_cms_servlet_tks_RASessionKey
+ * Method: ListSymmetricKeys
+ * Signature: (Ljava/lang/String;)Ljava/lang/String;
+ */
+ JNIEXPORT jstring JNICALL Java_com_netscape_symkey_SessionKey_ListSymmetricKeys
+ (JNIEnv *, jclass, jstring);
+
+#ifdef __cplusplus
+}
+#endif
+
+PK11SlotInfo *ReturnSlot(char *tokenNameChars)
+{
+ if( tokenNameChars == NULL)
+ {
+ return NULL;
+ }
+ PK11SlotInfo *slot=NULL;
+
+ if(!strcmp( tokenNameChars, "internal" ) )
+ {
+ slot = PK11_GetInternalKeySlot();
+ }
+ else
+ {
+ slot = PK11_FindSlotByName( tokenNameChars );
+ }
+ return slot;
+}
+
+
+/* Find the Symmetric key with the given nickname
+ Returns null if the key could not be found
+ Steve wrote this code to replace the old impl */
+
+PK11SymKey * ReturnSymKey( PK11SlotInfo *slot, char *keyname)
+{
+ char *name = NULL;
+ PK11SymKey *foundSymKey= NULL;
+ PK11SymKey *firstSymKey= NULL;
+ PK11SymKey *sk = NULL;
+ PK11SymKey *nextSymKey = NULL;
+ secuPWData pwdata;
+
+ pwdata.source = secuPWData::PW_NONE;
+ pwdata.data = (char *) NULL;
+
+ if (keyname == NULL)
+ {
+ goto cleanup;
+ }
+ if (slot== NULL)
+ {
+ goto cleanup;
+ }
+ /* Initialize the symmetric key list. */
+ firstSymKey = PK11_ListFixedKeysInSlot( slot , NULL, ( void *) &pwdata );
+
+ /* scan through the symmetric key list for a key matching our nickname */
+ sk = firstSymKey;
+ while( sk != NULL )
+ {
+ /* get the nickname of this symkey */
+ name = PK11_GetSymKeyNickname( sk );
+
+ /* if the name matches, make a 'copy' of it */
+ if ( name != NULL && !strcmp( keyname, name ))
+ {
+ if (foundSymKey == NULL)
+ {
+ foundSymKey = PK11_ReferenceSymKey(sk);
+ }
+ PORT_Free(name);
+ }
+
+ sk = PK11_GetNextSymKey( sk );
+ }
+
+ /* We're done with the list now, let's free all the keys in it
+ It's okay to free our key, because we made a copy of it */
+
+ sk = firstSymKey;
+ while( sk != NULL )
+ {
+ nextSymKey = PK11_GetNextSymKey(sk);
+ PK11_FreeSymKey(sk);
+ sk = nextSymKey;
+ }
+
+ cleanup:
+ return foundSymKey;
+}
+
+
+extern "C" JNIEXPORT jstring
+JNICALL Java_com_netscape_symkey_SessionKey_DeleteKey(JNIEnv * env, jclass this2, jstring tokenName, jstring keyName)
+
+{
+ char *tokenNameChars;
+ char *keyNameChars;
+ int count = 0;
+ int keys_deleted = 0;
+ PK11SymKey *symKey = NULL;
+ PK11SymKey *nextSymKey = NULL;
+ PK11SlotInfo *slot = NULL;
+ SECStatus rv;
+ secuPWData pwdata;
+ pwdata.source = secuPWData::PW_NONE;
+ pwdata.data = (char *) NULL;
+ jstring retval = NULL;
+
+ tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
+ keyNameChars = (char *)(env)->GetStringUTFChars(keyName, NULL);
+ char *result= (char *)malloc(1);
+
+ result[0] = '\0';
+ if( tokenNameChars == NULL || keyNameChars==NULL)
+ {
+ goto finish;
+ }
+ if(strcmp( tokenNameChars, "internal" ) == 0 )
+ {
+ slot = PK11_GetInternalKeySlot();
+ }
+ else if( tokenNameChars != NULL )
+ {
+ slot = PK11_FindSlotByName( tokenNameChars );
+ }
+ /* Initialize the symmetric key list. */
+ symKey = PK11_ListFixedKeysInSlot( slot , NULL, ( void *) &pwdata );
+
+ /* Iterate through the symmetric key list. */
+ while( symKey != NULL )
+ {
+ char *name = NULL;
+ rv = SECFailure;
+ name = PK11_GetSymKeyNickname( symKey );
+
+ if( strcmp( keyNameChars, name ) == 0 )
+ {
+ rv = PK11_DeleteTokenSymKey( symKey );
+ }
+ PORT_Free(name);
+
+ if( rv != SECFailure )
+ {
+ keys_deleted++;
+ }
+
+ nextSymKey = PK11_GetNextSymKey( symKey );
+ PK11_FreeSymKey( symKey );
+ symKey = nextSymKey;
+
+ count++;
+ }
+
+ if( keys_deleted == 0 )
+ {
+
+ rv = SECFailure;
+ }
+ else
+ {
+
+ rv = SECSuccess;
+ }
+
+ finish:
+ if (slot)
+ {
+ PK11_FreeSlot(slot);
+ }
+ if(tokenNameChars)
+ {
+ (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
+ }
+ if(keyNameChars)
+ {
+ (env)->ReleaseStringUTFChars(keyName, (const char *)keyNameChars);
+ }
+ retval = (env)->NewStringUTF( result);
+ free(result);
+ return retval;
+}
+
+
+#define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
+(x)->pValue=(v); (x)->ulValueLen = (l);
+
+extern "C" JNIEXPORT jstring
+JNICALL Java_com_netscape_symkey_SessionKey_ListSymmetricKeys(JNIEnv * env, jclass this2, jstring tokenName)
+{
+ char *tokenNameChars;
+ jstring retval = NULL;
+ PK11SymKey *symKey = NULL;
+ PK11SymKey *nextSymKey = NULL;
+ secuPWData pwdata;
+ pwdata.source = secuPWData::PW_NONE;
+ pwdata.data = (char *) NULL;
+ PK11SlotInfo *slot = NULL;
+
+ tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
+ char *result= (char *)malloc(1);
+ result[0] = '\0';
+ if( tokenNameChars == NULL )
+ {
+ goto finish;
+ }
+ if(strcmp( tokenNameChars, "internal" ) == 0 )
+ {
+ slot = PK11_GetInternalKeySlot();
+ }
+ else if( tokenNameChars != NULL )
+ {
+ slot = PK11_FindSlotByName( tokenNameChars );
+ }
+
+ /* Initialize the symmetric key list. */
+ symKey = PK11_ListFixedKeysInSlot( slot , NULL, (void *)&pwdata );
+
+ /* Iterate through the symmetric key list. */
+ while (symKey != NULL)
+ {
+ int count = 0;
+ char *name = NULL;
+ char *temp = NULL;
+ name = PK11_GetSymKeyNickname( symKey );
+ temp = result;
+ result = (char*)malloc( strlen(name) + strlen(temp) + 2 );
+ result[0]='\0';
+ strcat(result, temp);
+ strcat(result, ",");
+ strcat(result, name);
+ free(temp);
+
+ PORT_Free(name);
+
+ nextSymKey = PK11_GetNextSymKey( symKey );
+ PK11_FreeSymKey( symKey );
+ symKey = nextSymKey;
+
+ count++;
+ }
+
+ finish:
+ if (slot)
+ {
+ PK11_FreeSlot(slot);
+ }
+ if(tokenNameChars)
+ {
+ (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
+ }
+ retval = (env)->NewStringUTF(result);
+ free(result);
+ return retval;
+}
+
+
+/* DES KEY Parity conversion table. Takes each byte/2 as an index, returns
+ * that byte with the proper parity bit set */
+static const unsigned char parityTable[256] =
+{
+/* Even...0x00,0x02,0x04,0x06,0x08,0x0a,0x0c,0x0e */
+ /* E */ 0x01,0x02,0x04,0x07,0x08,0x0b,0x0d,0x0e,
+/* Odd....0x10,0x12,0x14,0x16,0x18,0x1a,0x1c,0x1e */
+ /* O */ 0x10,0x13,0x15,0x16,0x19,0x1a,0x1c,0x1f,
+/* Odd....0x20,0x22,0x24,0x26,0x28,0x2a,0x2c,0x2e */
+ /* O */ 0x20,0x23,0x25,0x26,0x29,0x2a,0x2c,0x2f,
+/* Even...0x30,0x32,0x34,0x36,0x38,0x3a,0x3c,0x3e */
+ /* E */ 0x31,0x32,0x34,0x37,0x38,0x3b,0x3d,0x3e,
+/* Odd....0x40,0x42,0x44,0x46,0x48,0x4a,0x4c,0x4e */
+ /* O */ 0x40,0x43,0x45,0x46,0x49,0x4a,0x4c,0x4f,
+/* Even...0x50,0x52,0x54,0x56,0x58,0x5a,0x5c,0x5e */
+ /* E */ 0x51,0x52,0x54,0x57,0x58,0x5b,0x5d,0x5e,
+/* Even...0x60,0x62,0x64,0x66,0x68,0x6a,0x6c,0x6e */
+ /* E */ 0x61,0x62,0x64,0x67,0x68,0x6b,0x6d,0x6e,
+/* Odd....0x70,0x72,0x74,0x76,0x78,0x7a,0x7c,0x7e */
+ /* O */ 0x70,0x73,0x75,0x76,0x79,0x7a,0x7c,0x7f,
+/* Odd....0x80,0x82,0x84,0x86,0x88,0x8a,0x8c,0x8e */
+ /* O */ 0x80,0x83,0x85,0x86,0x89,0x8a,0x8c,0x8f,
+/* Even...0x90,0x92,0x94,0x96,0x98,0x9a,0x9c,0x9e */
+ /* E */ 0x91,0x92,0x94,0x97,0x98,0x9b,0x9d,0x9e,
+/* Even...0xa0,0xa2,0xa4,0xa6,0xa8,0xaa,0xac,0xae */
+ /* E */ 0xa1,0xa2,0xa4,0xa7,0xa8,0xab,0xad,0xae,
+/* Odd....0xb0,0xb2,0xb4,0xb6,0xb8,0xba,0xbc,0xbe */
+ /* O */ 0xb0,0xb3,0xb5,0xb6,0xb9,0xba,0xbc,0xbf,
+/* Even...0xc0,0xc2,0xc4,0xc6,0xc8,0xca,0xcc,0xce */
+ /* E */ 0xc1,0xc2,0xc4,0xc7,0xc8,0xcb,0xcd,0xce,
+/* Odd....0xd0,0xd2,0xd4,0xd6,0xd8,0xda,0xdc,0xde */
+ /* O */ 0xd0,0xd3,0xd5,0xd6,0xd9,0xda,0xdc,0xdf,
+/* Odd....0xe0,0xe2,0xe4,0xe6,0xe8,0xea,0xec,0xee */
+ /* O */ 0xe0,0xe3,0xe5,0xe6,0xe9,0xea,0xec,0xef,
+/* Even...0xf0,0xf2,0xf4,0xf6,0xf8,0xfa,0xfc,0xfe */
+ /* E */ 0xf1,0xf2,0xf4,0xf7,0xf8,0xfb,0xfd,0xfe,
+};
+
+void
+pk11_FormatDESKey(unsigned char *key, int length)
+{
+ int i;
+
+ /* format the des key */
+ for (i=0; i < length; i++)
+ {
+ key[i] = parityTable[key[i]>>1];
+ }
+}
+
+
+static secuPWData pwdata = { secuPWData::PW_NONE, 0 };
+
+/**
+ * Internal token is required when we are doing key diversification
+ * where raw key material needs to be accessed
+ */
+PK11SymKey *ComputeCardKeyOnSoftToken(PK11SymKey *masterKey, unsigned char *data)
+{
+ PK11SlotInfo *slot = PK11_GetInternalKeySlot();
+ PK11SymKey *key = ComputeCardKey(masterKey, data, slot);
+ PK11_FreeSlot(slot);
+ return key;
+}
+
+PK11SymKey *ComputeCardKey(PK11SymKey *masterKey, unsigned char *data, PK11SlotInfo *slot)
+{
+ PK11SymKey *key = NULL;
+ PK11Context *context = NULL;
+ int keysize;
+ keysize = 24;
+ unsigned char *keyData = NULL;
+ SECStatus s;
+ int i = 0;
+ int len=0;
+ static SECItem noParams = { siBuffer, 0, 0 };
+ unsigned char *in = data;
+ PK11SymKey *tmpkey = NULL;
+ unsigned char wrappedkey[24];
+
+ keyData = (unsigned char*)malloc(keysize);
+
+ for (i = 0;i < keysize; i++)
+ {
+ keyData[i] = 0x0;
+ }
+
+ context = PK11_CreateContextBySymKey(CKM_DES3_ECB, CKA_ENCRYPT,
+ masterKey,
+ &noParams);
+
+ if (context == NULL)
+ {
+ printf("failed to create context\n");
+ goto done;
+ }
+
+ /* Part 1 */
+ s = PK11_CipherOp(context, &keyData[0], &len, 8, in, 8);
+ if (s != SECSuccess)
+ {
+ printf("failed to encryp #1\n");
+ goto done;
+ }
+ pk11_FormatDESKey(&keyData[0], 8); /* set parity */
+
+ /* Part 2 */
+ s = PK11_CipherOp(context, &keyData[8], &len, 8, in+8, 8);
+ if (s != SECSuccess)
+ {
+ printf("failed to encryp #2\n");
+ goto done;
+ }
+ pk11_FormatDESKey(&keyData[8], 8);
+
+ /* Part 3 */
+ for(i = 0;i < 8;i++)
+ {
+ keyData[i+16] = keyData[i];
+ }
+
+#define CKF_KEY_OPERATION_FLAGS 0x000e7b00UL
+
+ /* generate a tmp key to import the sym key */
+ tmpkey = PK11_TokenKeyGenWithFlags(slot,
+ CKM_DES3_KEY_GEN, 0, 0, 0,
+ (CKF_WRAP | CKF_UNWRAP | CKF_ENCRYPT | CKF_DECRYPT) & CKF_KEY_OPERATION_FLAGS,
+ PR_FALSE, &pwdata);
+
+ context = PK11_CreateContextBySymKey(CKM_DES3_ECB, CKA_ENCRYPT,
+ tmpkey,
+ &noParams);
+
+ /* encrypt the key with the master key */
+ s = PK11_CipherOp(context, wrappedkey, &len, 24, keyData, 24);
+ if (s != SECSuccess)
+ {
+ printf("failed to encryp #3\n");
+ goto done;
+ }
+
+ SECItem wrappeditem;
+ wrappeditem.data = wrappedkey;
+ wrappeditem.len = len;
+
+ key = PK11_UnwrapSymKeyWithFlags(tmpkey, CKM_DES3_ECB, &noParams,
+ &wrappeditem, CKM_DES3_KEY_GEN, CKA_DECRYPT, 24,
+ (CKA_ENCRYPT | CKA_DECRYPT) & CKF_KEY_OPERATION_FLAGS );
+
+done:
+ if (keyData != NULL)
+ {
+ free(keyData);
+ }
+ if (context != NULL)
+ {
+ PK11_DestroyContext(context, PR_TRUE);
+ context = NULL;
+ }
+ return key;
+}
+
+
+PK11SymKey * ComputeCardKeyOnToken(PK11SymKey *masterKey, BYTE* data)
+{
+ PK11SlotInfo *slot = PK11_GetSlotFromKey(masterKey);
+ PK11SymKey *key = ComputeCardKey(masterKey, data, slot);
+ PK11_FreeSlot(slot);
+ return key;
+}
+
+
+PRStatus EncryptDataWithCardKey(PK11SymKey *card_key, Buffer &input, Buffer &output)
+{
+ PRStatus rv = PR_FAILURE;
+
+ PK11Context *context = NULL;
+ int i;
+ SECStatus s = SECFailure;
+ int len;
+ static SECItem noParams = { siBuffer, 0, 0 };
+ unsigned char result[8];
+
+ context = PK11_CreateContextBySymKey(CKM_DES3_ECB, CKA_ENCRYPT, card_key,
+ &noParams);
+ if (context == NULL)
+ {
+ goto done;
+ }
+
+ for(i = 0;i < (int)input.size();i += 8)
+ {
+ s = PK11_CipherOp(context, result, &len, 8,
+ (unsigned char *)(((BYTE*)input)+i), 8);
+
+ if (s != SECSuccess)
+ {
+ goto done;
+ }
+ output.replace(i, result, 8);
+ }
+
+ rv = PR_SUCCESS;
+
+done:
+ if (context)
+ {
+ PK11_DestroyContext(context, PR_TRUE);
+ context = NULL;
+ }
+ return rv;
+}
+
+
+PRStatus EncryptData(Buffer &kek_key, Buffer &input, Buffer &output)
+{
+ PRStatus rv = PR_FAILURE;
+
+ PK11SymKey *master = NULL;
+ PK11SlotInfo *slot = NULL;
+ PK11Context *context = NULL;
+ int i;
+ SECStatus s = SECFailure;
+ int len;
+ static SECItem noParams = { siBuffer, 0, 0 };
+#ifdef DES2_WORKAROUND
+ unsigned char masterKeyData[24];
+#else
+ unsigned char masterKeyData[16];
+#endif
+ SECItem masterKeyItem = {siBuffer, masterKeyData, sizeof(masterKeyData) };
+ unsigned char result[8];
+
+ /* convert 16-byte to 24-byte triple-DES key */
+ memcpy(masterKeyData, (BYTE*)kek_key, 16);
+#ifdef DES2_WORKAROUND
+ memcpy(masterKeyData+16, (BYTE*)kek_key, 8);
+#endif
+
+ slot = PK11_GetInternalKeySlot();
+ if (slot == NULL)
+ {
+ goto done;
+ }
+
+ master = PK11_ImportSymKeyWithFlags(slot, CKM_DES3_ECB,
+ PK11_OriginGenerated, CKA_ENCRYPT, &masterKeyItem,
+ CKF_ENCRYPT, PR_FALSE, 0);
+ if( master == NULL)
+ {
+ goto done;
+ }
+
+ context = PK11_CreateContextBySymKey(CKM_DES3_ECB, CKA_ENCRYPT, master,
+ &noParams);
+ if (context == NULL)
+ {
+ goto done;
+ }
+
+ for(i = 0;i < (int)input.size();i += 8)
+ {
+ s = PK11_CipherOp(context, result, &len, 8,
+ (unsigned char *)(((BYTE*)input)+i), 8);
+
+ if (s != SECSuccess)
+ {
+ goto done;
+ }
+ output.replace(i, result, 8);
+ }
+
+ rv = PR_SUCCESS;
+
+done:
+
+ memset(masterKeyData, 0, sizeof masterKeyData);
+ if (context)
+ {
+ PK11_DestroyContext(context, PR_TRUE);
+ context = NULL;
+ }
+ if (slot)
+ {
+ PK11_FreeSlot(slot);
+ slot = NULL;
+ }
+ if (master)
+ {
+ PK11_FreeSymKey(master);
+ master = NULL;
+ }
+
+ return rv;
+}
+
+
+PRStatus ComputeKeyCheck(const Buffer& newKey, Buffer& output)
+{
+ PK11SymKey *key = NULL;
+ PRStatus status = PR_FAILURE ;
+ PK11SlotInfo *slot = NULL;
+ PK11Context *context = NULL;
+ SECStatus s = SECFailure;
+ int len;
+ static SECItem noParams = { siBuffer, 0, 0 };
+#ifdef DES2_WORKAROUND
+ unsigned char keyData[24];
+#else
+ unsigned char keyData[16];
+#endif
+ SECItem keyItem = {siBuffer, keyData, sizeof(keyData) };
+ unsigned char value[8];
+ /* convert 16-byte to 24-byte triple-DES key */
+ memcpy(keyData, newKey, 16);
+#ifdef DES2_WORKAROUND
+ memcpy(keyData+16, newKey, 8);
+#endif
+
+ memset(value, 0, sizeof value);
+
+ slot = PK11_GetInternalKeySlot();
+ if (slot != NULL)
+ {
+ key = PK11_ImportSymKeyWithFlags(slot, CKM_DES3_ECB,
+ PK11_OriginGenerated, CKA_ENCRYPT, &keyItem,
+ CKF_ENCRYPT, PR_FALSE, 0);
+ if( key != NULL )
+ {
+ context = PK11_CreateContextBySymKey(CKM_DES3_ECB, CKA_ENCRYPT, key,
+ &noParams);
+ if (context != NULL)
+ {
+ s = PK11_CipherOp(context, &value[0], &len, 8, &value[0], 8);
+
+ if (s == SECSuccess)
+ {
+ output.resize(3);
+ output.replace(0, value, 3);
+ status = PR_SUCCESS;
+ }
+ PK11_DestroyContext(context, PR_TRUE);
+ context = NULL;
+ memset(keyData, 0, sizeof keyData);
+ }
+ PK11_FreeSymKey(key);
+ key = NULL;
+
+ }
+ PK11_FreeSlot(slot);
+ }
+
+ return status;
+}
+
+
+PRStatus CreateKeySetDataWithKey( Buffer &newMasterVer, PK11SymKey *old_kek_key, Buffer &new_auth_key, Buffer &new_mac_key, Buffer &new_kek_key, Buffer &output)
+{
+ PRStatus rv = PR_FAILURE;
+
+ Buffer result;
+ if (old_kek_key == NULL)
+ {
+ result = new_auth_key + new_mac_key + new_kek_key + output ;
+ }
+ else
+ {
+
+ Buffer encrypted_auth_key(16);
+ EncryptDataWithCardKey(old_kek_key, new_auth_key, encrypted_auth_key);
+ Buffer kc_auth_key(3);
+ ComputeKeyCheck(new_auth_key, kc_auth_key);
+
+ Buffer encrypted_mac_key(16);
+ EncryptDataWithCardKey(old_kek_key, new_mac_key, encrypted_mac_key);
+ Buffer kc_mac_key(3);
+ ComputeKeyCheck(new_mac_key, kc_mac_key);
+
+ Buffer encrypted_kek_key(16);
+ EncryptDataWithCardKey(old_kek_key, new_kek_key, encrypted_kek_key);
+ Buffer kc_kek_key(3);
+ ComputeKeyCheck(new_kek_key, kc_kek_key);
+
+ result = newMasterVer +
+ Buffer(1, (BYTE)0x81) +
+ Buffer(1, (BYTE)0x10) +
+ encrypted_auth_key +
+ Buffer(1, (BYTE)0x03) +
+ kc_auth_key +
+ Buffer(1, (BYTE)0x81) +
+ Buffer(1, (BYTE)0x10) +
+ encrypted_mac_key +
+ Buffer(1, (BYTE)0x03) +
+ kc_mac_key +
+ Buffer(1, (BYTE)0x81) +
+ Buffer(1, (BYTE)0x10) +
+ encrypted_kek_key +
+ Buffer(1, (BYTE)0x03) +
+ kc_kek_key;
+ }
+ output = result;
+
+ rv = PR_SUCCESS;
+ return rv;
+
+} /* CreateKeySetDataWithKey */
+
+
+PRStatus CreateKeySetData( Buffer &newMasterVer, Buffer &old_kek_key2, Buffer &new_auth_key, Buffer &new_mac_key, Buffer &new_kek_key, Buffer &output)
+{
+ PRStatus rv = PR_FAILURE;
+
+ Buffer result;
+ if(old_kek_key2 == Buffer((BYTE*)"#00#00", 6))
+ {
+ result = new_auth_key + new_mac_key + new_kek_key + output ;
+ } else {
+ Buffer encrypted_auth_key(16);
+ EncryptData(old_kek_key2, new_auth_key, encrypted_auth_key);
+ Buffer kc_auth_key(3);
+ ComputeKeyCheck(new_auth_key, kc_auth_key);
+
+ Buffer encrypted_mac_key(16);
+ EncryptData(old_kek_key2, new_mac_key, encrypted_mac_key);
+ Buffer kc_mac_key(3);
+ ComputeKeyCheck(new_mac_key, kc_mac_key);
+
+ Buffer encrypted_kek_key(16);
+ EncryptData(old_kek_key2, new_kek_key, encrypted_kek_key);
+ Buffer kc_kek_key(3);
+ ComputeKeyCheck(new_kek_key, kc_kek_key);
+
+ result = newMasterVer +
+ Buffer(1, (BYTE)0x81) +
+ Buffer(1, (BYTE)0x10) +
+ encrypted_auth_key +
+ Buffer(1, (BYTE)0x03) +
+ kc_auth_key +
+ Buffer(1, (BYTE)0x81) +
+ Buffer(1, (BYTE)0x10) +
+ encrypted_mac_key +
+ Buffer(1, (BYTE)0x03) +
+ kc_mac_key +
+ Buffer(1, (BYTE)0x81) +
+ Buffer(1, (BYTE)0x10) +
+ encrypted_kek_key +
+ Buffer(1, (BYTE)0x03) +
+ kc_kek_key;
+ }
+ output = result;
+
+ rv = PR_SUCCESS;
+ return rv;
+}
+
+
+void GetDiversificationData(jbyte *cuidValue,BYTE *KDC,keyType keytype)
+{
+ BYTE *lastTwoBytesOfAID = (BYTE *)cuidValue;
+// BYTE *ICFabricationDate = (BYTE *)cuidValue + 2;
+ BYTE *ICSerialNumber = (BYTE *)cuidValue + 4;
+// BYTE *ICBatchIdentifier = (BYTE *)cuidValue + 8;
+
+// Last 2 bytes of AID
+ KDC[0]= (BYTE)lastTwoBytesOfAID[0];
+ KDC[1]= (BYTE)lastTwoBytesOfAID[1];
+ KDC[2]= (BYTE)ICSerialNumber[0];
+ KDC[3]= (BYTE)ICSerialNumber[1];
+ KDC[4]= (BYTE)ICSerialNumber[2];
+ KDC[5]= (BYTE)ICSerialNumber[3];
+ KDC[6]= 0xF0;
+ KDC[7]= 0x01;
+ KDC[8]= (BYTE)lastTwoBytesOfAID[0];
+ KDC[9]= (BYTE)lastTwoBytesOfAID[1];
+ KDC[10]= (BYTE)ICSerialNumber[0];
+ KDC[11]= (BYTE)ICSerialNumber[1];
+ KDC[12]= (BYTE)ICSerialNumber[2];
+ KDC[13]= (BYTE)ICSerialNumber[3];
+ KDC[14]= 0x0F;
+ KDC[15]= 0x01;
+ if(keytype == enc)
+ return;
+
+ KDC[6]= 0xF0;
+ KDC[7]= 0x02;
+ KDC[14]= 0x0F;
+ KDC[15]= 0x02;
+ if(keytype == mac)
+ return;
+
+ KDC[6]= 0xF0;
+ KDC[7]= 0x03;
+ KDC[14]= 0x0F;
+ KDC[15]= 0x03;
+ if(keytype == kek)
+ return;
+
+}
+
+static int getMasterKeyVersion(char *newMasterKeyNameChars)
+{
+
+ char masterKeyVersionNumber[3];
+ masterKeyVersionNumber[0]=newMasterKeyNameChars[1];
+ masterKeyVersionNumber[1]=newMasterKeyNameChars[2];
+ masterKeyVersionNumber[2]=0;
+ int newMasterKeyVesion = atoi(masterKeyVersionNumber);
+ return newMasterKeyVesion;
+}
+
+
+void getFullName(char * fullMasterKeyName, char * masterKeyNameChars )
+{
+ fullMasterKeyName[0]='\0';
+ if(strlen(masterKeyPrefix)>0)
+ strcpy(fullMasterKeyName,masterKeyPrefix);
+ strcat(fullMasterKeyName,masterKeyNameChars);
+}
+
+
+/*
+ * Class: com_netscape_cms_servlet_tks_RASessionKey
+ * Method: DiversifyKey
+ * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[B)[B
+ */
+extern "C" JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_DiversifyKey
+(JNIEnv *, jclass, jstring, jstring, jstring, jstring, jstring, jbyteArray, jbyteArray, jstring);
+
+extern "C" JNIEXPORT jbyteArray JNICALL Java_com_netscape_symkey_SessionKey_DiversifyKey( JNIEnv * env, jclass this2, jstring tokenName,jstring newTokenName, jstring oldMasterKeyName, jstring newMasterKeyName, jstring keyInfo, jbyteArray CUIDValue, jbyteArray kekKeyArray, jstring useSoftToken_s)
+{
+ PK11SymKey *encKey = NULL;
+ PK11SymKey *macKey = NULL;
+ PK11SymKey *kekKey = NULL;
+ Buffer encKeyBuff;
+ Buffer macKeyBuff;
+ Buffer kekKeyBuff;
+ char * oldMasterKeyNameChars=NULL;
+ Buffer old_kek_key_buff;
+ Buffer newMasterKeyBuffer;
+ char fullMasterKeyName[KEYNAMELENGTH];
+ char fullNewMasterKeyName[KEYNAMELENGTH];
+ PRBool specified_key_is_present = PR_TRUE;
+ PK11SymKey *old_kek_sym_key = NULL;
+ SECStatus s;
+
+ jbyte * cuidValue = (jbyte*)(env)->GetByteArrayElements( CUIDValue, NULL);
+
+ BYTE *encKeyData = NULL;
+ BYTE *macKeyData = NULL;
+ BYTE *kekKeyData = NULL;
+
+ BYTE KDCenc[KEYLENGTH];
+ BYTE KDCmac[KEYLENGTH];
+ BYTE KDCkek[KEYLENGTH];
+ jbyte * old_kek_key = (jbyte*)(env)->GetByteArrayElements(kekKeyArray, NULL);
+
+ GetDiversificationData(cuidValue,KDCenc,enc);
+ GetDiversificationData(cuidValue,KDCmac,mac);
+ GetDiversificationData(cuidValue,KDCkek,kek);
+
+ jbyteArray handleBA=NULL;
+ jbyte *handleBytes=NULL;
+ int newMasterKeyVesion = 1;
+
+ /* find slot */
+ char *tokenNameChars = NULL;
+ PK11SlotInfo *slot = NULL;
+
+ if(tokenName)
+ {
+ tokenNameChars = (char *)(env)->GetStringUTFChars(tokenName, NULL);
+ slot = ReturnSlot(tokenNameChars);
+ (env)->ReleaseStringUTFChars(tokenName, (const char *)tokenNameChars);
+ }
+
+ /* find masterkey */
+ char * newMasterKeyNameChars = NULL;
+ if(newMasterKeyName)
+ {
+ /* newMasterKeyNameChars #02#01 */
+ newMasterKeyNameChars= (char *)(env)->GetStringUTFChars(newMasterKeyName, NULL);
+ }
+
+ /* fullNewMasterKeyName - no prefix #02#01 */
+ getFullName(fullNewMasterKeyName,newMasterKeyNameChars);
+ Buffer output;
+ PK11SlotInfo *newSlot =NULL;
+ char * newTokenNameChars = NULL;
+ if(newTokenName)
+ {
+ newTokenNameChars = (char *)(env)->GetStringUTFChars(newTokenName, NULL);
+ newSlot = ReturnSlot(newTokenNameChars);
+ (env)->ReleaseStringUTFChars(newTokenName, (const char *)newTokenNameChars);
+ }
+ PK11SymKey * masterKey = ReturnSymKey(newSlot,fullNewMasterKeyName);
+
+ if(newMasterKeyNameChars)
+ {
+ (env)->ReleaseStringUTFChars(newMasterKeyName, (const char *)newMasterKeyNameChars);
+ }
+
+ /* packing return */
+ char *keyInfoChars;
+ keyInfoChars = (char *)(env)->GetStringUTFChars(keyInfo, NULL);
+ newMasterKeyVesion = getMasterKeyVersion(keyInfoChars);
+
+ if(keyInfoChars)
+ {
+ (env)->ReleaseStringUTFChars(keyInfo, (const char *)keyInfoChars);
+ }
+
+ /* NEW MASTER KEY VERSION */
+ newMasterKeyBuffer = Buffer((unsigned int) 1, (BYTE)newMasterKeyVesion);
+ if(oldMasterKeyName)
+ {
+ oldMasterKeyNameChars = (char *)(env)->GetStringUTFChars(oldMasterKeyName, NULL);
+ }
+ getFullName(fullMasterKeyName,oldMasterKeyNameChars);
+
+ if(newSlot == NULL)
+ {
+ newSlot = slot;
+ }
+ if(strcmp( oldMasterKeyNameChars, "#01#01") == 0)
+ {
+ old_kek_key_buff = Buffer((BYTE*)old_kek_key, 16);
+ }else if(strcmp( oldMasterKeyNameChars, "#00#00") == 0)
+ {
+
+ /* print Debug message - do not create real keysetdata */
+ old_kek_key_buff = Buffer((BYTE*)"#00#00", 6);
+ output = Buffer((BYTE*)old_kek_key, 16);
+ }
+ else
+ {
+ PK11SymKey * oldMasterKey = ReturnSymKey(slot,fullMasterKeyName);
+ old_kek_sym_key = ComputeCardKeyOnToken(oldMasterKey,KDCkek);
+ if (oldMasterKey)
+ PK11_FreeSymKey( oldMasterKey );
+ }
+ if(oldMasterKeyNameChars)
+ (env)->ReleaseStringUTFChars(oldMasterKeyName, (const char *)oldMasterKeyNameChars);
+
+ /* special case #01#01 */
+ if (fullNewMasterKeyName != NULL && strcmp(fullNewMasterKeyName, "#01#01") == 0)
+ {
+ encKeyData = (BYTE*)old_kek_key;
+ macKeyData = (BYTE*)old_kek_key;
+ kekKeyData = (BYTE*)old_kek_key;
+ } else {
+ /* compute card key */
+ encKey = ComputeCardKeyOnSoftToken(masterKey, KDCenc);
+ macKey = ComputeCardKeyOnSoftToken(masterKey, KDCmac);
+ kekKey = ComputeCardKeyOnSoftToken(masterKey, KDCkek);
+
+ /* Fixes Bugscape Bug #55855: TKS crashes if specified key
+ * is not present -- for each portion of the key, check if
+ * the PK11SymKey is NULL before sending it to PK11_GetKeyData()!
+ */
+ if( encKey != NULL)
+ {
+ s = PK11_ExtractKeyValue(encKey);
+ encKeyData = (BYTE*)(PK11_GetKeyData(encKey)->data);
+ }
+ else
+ {
+ specified_key_is_present = PR_FALSE;
+ goto done;
+ }
+ if( macKey != NULL)
+ {
+ s = PK11_ExtractKeyValue(macKey);
+ macKeyData = (BYTE*)(PK11_GetKeyData(macKey)->data);
+ }
+ else
+ {
+ specified_key_is_present = PR_FALSE;
+ goto done;
+ }
+ if( kekKey != NULL)
+ {
+ s = PK11_ExtractKeyValue(kekKey);
+ kekKeyData = (BYTE*)(PK11_GetKeyData(kekKey)->data);
+ }
+ else
+ {
+ specified_key_is_present = PR_FALSE;
+ goto done;
+ }
+
+ }
+
+ encKeyBuff = Buffer(encKeyData, 16);
+ macKeyBuff = Buffer(macKeyData, 16);
+ kekKeyBuff = Buffer(kekKeyData, 16);
+
+ /* decide to whether to create the new key set by using a sym key or
+ a buffered key */
+ if (old_kek_sym_key != NULL)
+ {
+ CreateKeySetDataWithKey(newMasterKeyBuffer,
+ old_kek_sym_key,
+ encKeyBuff,
+ macKeyBuff,
+ kekKeyBuff,
+ output);
+ }
+ else
+ {
+ CreateKeySetData(newMasterKeyBuffer,
+ old_kek_key_buff,
+ encKeyBuff,
+ macKeyBuff,
+ kekKeyBuff,
+ output);
+ }
+
+done:
+ if (masterKey != NULL)
+ PK11_FreeSymKey( masterKey);
+ if (encKey != NULL)
+ PK11_FreeSymKey( encKey );
+ if (macKey != NULL)
+ PK11_FreeSymKey( macKey );
+ if (kekKey != NULL)
+ PK11_FreeSymKey( kekKey );
+
+ if( specified_key_is_present )
+ {
+ if(output.size()>0)
+ handleBA = (env)->NewByteArray( output.size());
+ else
+ handleBA = (env)->NewByteArray(1);
+ handleBytes = (env)->GetByteArrayElements(handleBA, NULL);
+ memcpy(handleBytes, (BYTE*)output,output.size());
+
+ (env)->ReleaseByteArrayElements( handleBA, handleBytes, 0);
+ }
+
+ (env)->ReleaseByteArrayElements(CUIDValue, cuidValue, JNI_ABORT);
+
+ if((newSlot != slot)&& newSlot)
+ PK11_FreeSlot( newSlot );
+ if( slot )
+ PK11_FreeSlot( slot );
+
+ return handleBA;
+
+}
+
+
+/*
+ * Class: com_netscape_cms_servlet_tks_RASessionKey
+ * Method: SetDefaultPrefix
+ * Signature: (Ljava/lang/String;)V
+ */
+extern "C" JNIEXPORT void JNICALL Java_com_netscape_symkey_SessionKey_SetDefaultPrefix
+(JNIEnv *, jclass, jstring);
+extern "C" JNIEXPORT void
+JNICALL Java_com_netscape_symkey_SessionKey_SetDefaultPrefix(JNIEnv * env, jclass this2, jstring masterPrefix)
+{
+ char *masterPrefixChars;
+
+ masterPrefixChars = (char *)(env)->GetStringUTFChars(masterPrefix, NULL);
+
+ if(masterPrefixChars)
+ strcpy(masterKeyPrefix,masterPrefixChars);
+ else
+ masterKeyPrefix[0] = '\0';
+
+ if(masterPrefixChars)
+ {
+ (env)->ReleaseStringUTFChars(masterPrefix, (const char *)masterPrefixChars);
+ }
+
+ return;
+}
diff --git a/pki/base/symkey/src/com/netscape/symkey/SymKey.h b/pki/base/symkey/src/com/netscape/symkey/SymKey.h
new file mode 100644
index 000000000..2f98d0444
--- /dev/null
+++ b/pki/base/symkey/src/com/netscape/symkey/SymKey.h
@@ -0,0 +1,45 @@
+// --- BEGIN COPYRIGHT BLOCK ---
+// This program is free software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation; version 2 of the License.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+//
+// (C) 2007 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+
+#ifndef _TKSSYMKEY_H_
+#define _TKSSYMKEY_H_
+
+extern PK11SlotInfo *defaultSlot;
+
+typedef enum {
+ enc,
+ mac,
+ kek
+ } keyType;
+#define KEYLENGTH 16
+#define PREFIXLENGHT 128
+#define KEYNAMELENGTH PREFIXLENGHT+7
+
+extern char masterKeyPrefix[PREFIXLENGHT];
+
+void GetDiversificationData(jbyte *cuidValue,BYTE *KDC,keyType keytype);
+PK11SymKey * ReturnSymKey( PK11SlotInfo *slot, char *keyname);
+void GetKeyName(jbyte *keyVersion,char *keyname);
+PK11SymKey * ComputeCardKeyOnToken(PK11SymKey *masterKey, BYTE* data);
+PRStatus EncryptDataWithCardKey(PK11SymKey *card_key, Buffer &input, Buffer &output);
+PK11SlotInfo *ReturnSlot(char *tokenNameChars);
+PK11SymKey *ComputeCardKey(PK11SymKey *masterKey, unsigned char *data, PK11SlotInfo *slot);
+
+#define DES2_WORKAROUND
+#endif /* _TKSSYMKEY_H_ */
+