This commit is contained in:
nicolson%netscape.com 2001-06-12 21:11:33 +00:00
Родитель 706dcde7af
Коммит 2ddef9db33
5 изменённых файлов: 30 добавлений и 599 удалений

Просмотреть файл

@ -216,126 +216,6 @@ loser:
}
#if 0
/***********************************************************************
* simpleInitialize
*
* Initializes NSPR and the RNG only.
*
* RETURNS
* PR_SUCCESS for success, PR_FAILURE otherwise. If not successful,
* an exception will be thrown.
*/
static PRStatus
simpleInitialize(JNIEnv *env)
{
/* initialize is synchronized, so this is thread-safe */
static PRBool initialized = PR_FALSE;
/* initialize values used to calculate concurrency */
PRUint32 mask = 0;
PRUint32 template = 0x00000001;
PRUintn cpus = 0;
PRUintn concurrency = 0;
if(initialized) {
return PR_SUCCESS;
}
/* On AIX, HP, and Linux, we need to do nasty signal handling in order
* to have NSPR play nice with the JVM and kernel.
*/
#if defined(AIX) || defined(HPUX) || defined(LINUX)
if( handleSigChild(env) != PR_SUCCESS ) {
return PR_FAILURE;
}
#endif
/* NOTE: Removed PR_Init() function since NSPR now self-initializes. */
/* PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 0); */
/* Obtain the mask containing the number of CPUs */
if( PR_GetThreadAffinityMask( PR_GetCurrentThread(), &mask ) ) {
JSS_throwMsg( env, SECURITY_EXCEPTION,
"Failed to calculate number of CPUs" );
return PR_FAILURE;
}
/* Count the bits to calculate the number of CPUs in the machine */
while( mask != 0 ) {
cpus += ( mask & template );
mask >>= 1;
}
/* Specify the concurrency */
#if defined(WIN32) && !defined(WIN95) /* WINNT (fiberous) */
/* Always specify at least a concurrency of 2 for (fiberous) Windows NT */
if( cpus <= 1 ) {
concurrency = 2;
} else {
concurrency = cpus;
}
#else
if( cpus <= 1 ) {
concurrency = 1;
} else {
concurrency = cpus;
}
#endif
/* Set the concurrency */
PR_SetConcurrency( concurrency );
RNG_RNGInit();
RNG_SystemInfoForRNG();
initialized = PR_TRUE;
return PR_SUCCESS;
}
/*
* CryptoManager.initialize
*
* Initializes NSPR and the RNG only.
*/
JNIEXPORT void JNICALL
Java_org_mozilla_jss_CryptoManager_initializeNative
(JNIEnv *env, jclass clazz)
{
if(simpleInitialize(env) != PR_SUCCESS ) {
PR_ASSERT( (*env)->ExceptionOccurred(env) );
return;
}
}
#endif
#if 0
/*
* Callback for key database name. Name is passed in through void* argument.
*/
static char*
keyDBNameCallback(void *arg, int dbVersion)
{
PR_ASSERT(arg!=NULL);
if(dbVersion==3) {
return PL_strdup((char*)arg);
} else {
return PL_strdup("");
}
}
static char*
certDBNameCallback(void *arg, int dbVersion)
{
PR_ASSERT(arg!=NULL);
if(dbVersion == 7) {
return PL_strdup((char*)arg);
} else {
return PL_strdup("");
}
}
#endif
/**********************************************************************
* This is the PasswordCallback object that will be used to login
@ -445,39 +325,40 @@ Java_org_mozilla_jss_CryptoManager_initializeAllNative
);
szConfigDir = (char*) (*env)->GetStringUTFChars(env, configDir, NULL);
if( certPrefix != NULL && keyPrefix != NULL && secmodName != NULL ) {
/*
* Set up arguments to NSS_Initialize
*/
szCertPrefix = (char*) (*env)->GetStringUTFChars(env, certPrefix, NULL);
szKeyPrefix = (char*) (*env)->GetStringUTFChars(env, keyPrefix, NULL);
szSecmodName = (char*) (*env)->GetStringUTFChars(env, secmodName, NULL);
initFlags = 0;
if( readOnly ) {
initFlags |= NSS_INIT_READONLY;
}
if( ! NSS_IsInitialized() ) {
szConfigDir = (char*) (*env)->GetStringUTFChars(env, configDir, NULL);
if( certPrefix != NULL && keyPrefix != NULL && secmodName != NULL ) {
/*
* Set up arguments to NSS_Initialize
*/
szCertPrefix = (char*) (*env)->GetStringUTFChars(env, certPrefix, NULL);
szKeyPrefix = (char*) (*env)->GetStringUTFChars(env, keyPrefix, NULL);
szSecmodName = (char*) (*env)->GetStringUTFChars(env, secmodName, NULL);
initFlags = 0;
if( readOnly ) {
initFlags |= NSS_INIT_READONLY;
}
/*
* Initialize NSS.
*/
rv = NSS_Initialize(szConfigDir, szCertPrefix, szKeyPrefix,
szSecmodName, initFlags);
} else {
if( readOnly ) {
rv = NSS_Init(szConfigDir);
/*
* Initialize NSS.
*/
rv = NSS_Initialize(szConfigDir, szCertPrefix, szKeyPrefix,
szSecmodName, initFlags);
} else {
rv = NSS_InitReadWrite(szConfigDir);
if( readOnly ) {
rv = NSS_Init(szConfigDir);
} else {
rv = NSS_InitReadWrite(szConfigDir);
}
}
if( rv != SECSuccess ) {
JSS_throwMsg(env, SECURITY_EXCEPTION,
"Unable to initialize security library");
goto finish;
}
}
if( rv != SECSuccess ) {
JSS_throwMsg(env, SECURITY_EXCEPTION,
"Unable to initialize security library");
goto finish;
}
/*
* Set default password callback. This is the only place this
* should ever be called if you are using Ninja.
@ -516,13 +397,6 @@ Java_org_mozilla_jss_CryptoManager_initializeAllNative
}
JSS_javaVM = VMs[0];
#if 0
if( NSS_SetDomesticPolicy() != SECSuccess ) {
JSS_throwMsg(env, SECURITY_EXCEPTION, "Unable to set domestic policy");
goto finish;
}
#endif
initialized = PR_TRUE;
finish:

Просмотреть файл

@ -97,8 +97,7 @@ Java_org_mozilla_jss_pkcs11_PK11MessageDigest_initHMAC
}
/* copy the key, setting the CKA_SIGN attribute */
newKey = pk11_CopyToSlot(PK11_GetSlotFromKey(origKey), mech, CKA_SIGN,
origKey);
newKey = PK11_CopySymKeyForSigning(origKey, mech);
if( newKey == NULL ) {
JSS_throwMsg(env, DIGEST_EXCEPTION,
"Unable to set CKA_SIGN attribute on symmetric key");

Просмотреть файл

@ -56,64 +56,6 @@ typedef struct pk11KeyCallbackStr {
void *wincx;
} pk11KeyCallback;
/* Traverse slots callback */
typedef struct pk11TraverseSlotStr {
SECStatus (*callback)(PK11SlotInfo *,CK_OBJECT_HANDLE, void *);
void *callbackArg;
CK_ATTRIBUTE *findTemplate;
int templateCount;
} pk11TraverseSlot;
SECStatus pk11_DoKeys(PK11SlotInfo*, CK_OBJECT_HANDLE, void*);
SECStatus PK11_TraverseSlot(PK11SlotInfo *, void*);
/***********************************************************************
* PK11_TraversePrivateKeysInSlot
*
* This is an HCL hack that traverses all the private keys on a slot.
*
* INPUTS
* slot
* The PKCS #11 slot whose private keys you want to traverse.
* callback
* A callback function that will be called for each key.
* arg
* An argument that will be passed to the callback function.
*/
static SECStatus
PK11_TraversePrivateKeysInSlot( PK11SlotInfo *slot,
SECStatus(* callback)(SECKEYPrivateKey*, void*), void *arg)
{
pk11KeyCallback perKeyCB;
pk11TraverseSlot perObjectCB;
CK_OBJECT_CLASS privkClass = CKO_PRIVATE_KEY;
CK_ATTRIBUTE theTemplate[1];
int templateSize = 1;
theTemplate[0].type = CKA_CLASS;
theTemplate[0].pValue = &privkClass;
theTemplate[0].ulValueLen = sizeof(privkClass);
if(slot==NULL) {
#ifdef DEBUG
PR_fprintf(PR_STDERR,
"Null slot passed to PK11_TraversePrivateKeysInSlot\n");
PR_ASSERT(PR_FALSE);
#endif
return SECSuccess;
}
perObjectCB.callback = pk11_DoKeys;
perObjectCB.callbackArg = &perKeyCB;
perObjectCB.findTemplate = theTemplate;
perObjectCB.templateCount = templateSize;
perKeyCB.callback = callback;
perKeyCB.callbackArg = arg;
perKeyCB.wincx = NULL;
return PK11_TraverseSlot(slot, &perObjectCB);
}
/**********************************************************************
* Callback information for keyTraversalCallback
*/

Просмотреть файл

@ -1,128 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape Security Services for Java.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
/* This program demonstrates how to sign data with keys from JSS
* The token name can be either the name of a hardware token, or
* one of the internal tokens:
* Internal Crypto Services Token
* Internal Key Storage Token (keys stored in key3.db)
*/
import org.mozilla.jss.crypto.*;
import org.mozilla.jss.crypto.Signature;
import org.mozilla.jss.crypto.KeyPairGenerator;
import java.security.*;
import java.security.cert.X509Certificate;
import java.io.*;
import java.lang.*;
import java.util.*;
import org.mozilla.jss.util.*;
import org.mozilla.jss.pkcs11.*;
import org.mozilla.jss.*;
public class SigTest {
public static void usage() {
System.out.println(
"Usage: java org.mozilla.jss.crypto.SigTest <dbdir> <tokenname>");
}
public static void main(String args[]) {
CryptoToken token;
CryptoManager manager;
byte[] data = new byte[] {1,2,3,4,5,6,7,8,9};
byte[] signature;
Signature signer;
PublicKey pubk;
KeyPairGenerator kpgen;
KeyPair keyPair;
if(args.length != 2) {
usage();
return;
}
String dbdir = args[0];
String tokenname = args[1];
try {
CryptoManager.InitializationValues vals = new
CryptoManager.InitializationValues(args[0], "foobar-", "foobar-",
"../secmodule.db");
CryptoManager.initialize(vals);
manager = CryptoManager.getInstance();
/* Print out list of available tokens */
Enumeration en = manager.getAllTokens();
System.out.println("Available tokens:");
while (en.hasMoreElements()) {
PK11Token p = (PK11Token)en.nextElement();
System.out.println(" token : "+p.getName());
}
token = manager.getTokenByName(tokenname);
// Generate an RSA keypair
kpgen = token.getKeyPairGenerator(KeyPairAlgorithm.RSA);
kpgen.initialize(1024);
keyPair = kpgen.genKeyPair();
// RSA MD5
signer = token.getSignatureContext(
SignatureAlgorithm.RSASignatureWithMD5Digest);
System.out.println("Created a signing context");
signer.initSign(
(org.mozilla.jss.crypto.PrivateKey)keyPair.getPrivate());
System.out.println("initialized the signing operation");
signer.update(data);
System.out.println("updated signature with data");
signature = signer.sign();
System.out.println("Successfully signed!");
signer.initVerify(keyPair.getPublic());
System.out.println("initialized verification");
signer.update(data);
System.out.println("updated verification with data");
if( signer.verify(signature) ) {
System.out.println("Signature Verified Successfully!");
} else {
System.out.println("ERROR: Signature failed to verify.");
}
} catch(Exception e) {
e.printStackTrace();
}
}
}

Просмотреть файл

@ -1,256 +0,0 @@
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is the Netscape Security Services for Java.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL"), in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your
* version of this file only under the terms of the GPL and not to
* allow others to use your version of this file under the MPL,
* indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient
* may use your version of this file under either the MPL or the
* GPL.
*/
/* This program demonstrates how to use JSS to enumerate
* crypto tokens, how to login and logout of tokens, and how
* to change the password on a token
*/
import org.mozilla.jss.pkcs11.*;
import org.mozilla.jss.util.*;
import org.mozilla.jss.crypto.*;
import org.mozilla.jss.*;
import java.io.*;
import java.awt.*;
import java.security.cert.*;
public class TokenAccessTest {
public static void main(String[] args) throws Throwable {
CryptoToken tok;
CryptoToken intTok;
CryptoManager manager;
Password pass1=null, pass2=null;
KeyPairGenerator keyPairGenerator;
java.security.KeyPair keyPair;
java.util.Enumeration items;
char[] passchar1 = {'f', 'o', 'o', 'b', 'a', 'r'};
char[] passchar2 = {'n', 'e', 't', 's', 'c', 'a', 'p', 'e'};
if(args.length != 1) {
System.err.println("Usage: java TokenAccessTest <dbdir>");
return;
}
CryptoManager.InitializationValues vals = new
CryptoManager.InitializationValues( args[0]+"/secmodule.db",
args[0]+"/key3.db",
args[0]+"/cert7.db");
CryptoManager.initialize(vals);
try {
manager = CryptoManager.getInstance();
} catch( CryptoManager.NotInitializedException e ) {
System.out.println("CryptoManager not initialized");
return;
}
try {
tok = manager.getTokenByName("asdffda");
System.out.println("ERROR: found a nonexistent token");
} catch (NoSuchTokenException e) {
System.out.println("Good, could not find non-existent token");
}
try {
items = manager.getModules();
System.out.println("Modules:");
while(items.hasMoreElements()) {
System.out.println("\t"+
((PK11Module)items.nextElement()).getName() );
}
items = manager.getAllTokens();
System.out.println("All Tokens:");
while(items.hasMoreElements()) {
System.out.println("\t"+
((CryptoToken)items.nextElement()).getName() );
}
items = manager.getExternalTokens();
System.out.println("External Tokens:");
while(items.hasMoreElements()) {
System.out.println("\t"+
((CryptoToken)items.nextElement()).getName() );
}
tok = manager.getTokenByName("Internal Key Storage Token");
System.out.println("Good, found internal DB token");
if( tok.equals(manager.getInternalKeyStorageToken()) ) {
System.out.println("Good, it really is the key storage token");
} else {
System.out.println("ERROR: it's not the same as the key "+
"storage token!");
}
if( ((PK11Token)tok).isInternalKeyStorageToken() ) {
System.out.println("Good, "+tok.getName()+" knows "+
"what it is");
} else {
System.out.println("ERROR: "+tok.getName()+" doesn't know"+
" it is key storage token");
}
intTok = manager.getInternalCryptoToken();
if( ((PK11Token)intTok).isInternalCryptoToken() ) {
System.out.println("Good, "+tok.getName()+
" knows it is the internal token");
} else {
System.out.println("ERROR: "+tok.getName()+
" doesn't know what that it is the internal token");
}
if(tok.isLoggedIn() == false) {
System.out.println("Good, isLoggedIn correctly says we're"+
" not logged in");
} else {
System.out.println("ERROR: isLoggedIn incorrectly says we're"+
" logged in");
}
System.out.println("Good, successfully opened token \""+
tok.getName()+"\"");
pass1 = new Password( (char[]) passchar1.clone());
pass2 = new Password( new char[]{0} );
tok.initPassword(pass2, pass1);
pass1.clear();
pass2.clear();
System.out.println("Good, initialized PIN");
tok.logout();
try {
pass1 = new Password( (char[]) passchar2.clone());
tok.login(pass1);
System.out.println("ERROR: Successfully logged in with wrong"+
" PIN");
} catch (IncorrectPasswordException e) {
System.out.println("Good, unable to login with wrong PIN");
} finally {
pass1.clear();
}
pass1 = new Password( (char[]) passchar1.clone());
tok.login(pass1);
pass1.clear();
System.out.println("Good, logged in");
if(tok.isLoggedIn() == true) {
System.out.println("Good, isLoggedIn correctly says we're"+
" logged in");
} else {
System.out.println("ERROR: isLoggedIn incorrectly says we're"+
" not logged in");
}
pass1 = new Password( (char[]) passchar1.clone());
pass2 = new Password( (char[]) passchar2.clone());
tok.changePassword(pass1, pass2);
pass1.clear(); pass2.clear();
System.out.println("Good, changed PIN");
try {
pass1 = new Password( (char[]) passchar1.clone());
tok.login(pass1);
// Should still be logged in
System.out.println("Good, logging in with wrong PIN ok if "+
" already logged in");
} catch (IncorrectPasswordException e) {
System.out.println("ERROR: logged in second time with wrong"+
"PIN, but we should still be logged in");
} finally {
pass1.clear();
}
try {
tok.logout();
System.out.println("Good, logged out successfully.");
} catch (TokenException e) {
System.out.println("ERROR: failed to logout from token");
}
if(tok.isLoggedIn() == false) {
System.out.println("Good, isLoggedIn correctly says we're"+
" not logged in");
} else {
System.out.println("ERROR: isLoggedIn incorrectly says we're"+
" logged in");
}
try {
tok.logout();
System.out.println("ERROR: logged out twice in a row");
} catch (TokenException e) {
System.out.println("Good, got an exception when we tried"+
" to log out twice in a row");
}
try {
pass1 = new Password( (char[]) passchar1.clone());
tok.login(pass1);
pass1.clear();
System.out.println("ERROR: logged in with wrong pw");
} catch (IncorrectPasswordException e) {
System.out.println("Good, logging in with wrong PIN gave err");
}
System.out.println("Test completed");
tok = null;
} catch (IncorrectPasswordException e) {
System.out.println("Got an incorrect PIN: "+e);
} catch (AlreadyInitializedException e) {
System.out.println(
"ERROR: This test only works with uninitialized databases");
} catch (TokenException e) {
System.out.println("Token error: " + e);
} catch (NoSuchTokenException e) {
System.out.println("ERROR: could not find internal DB token");
} finally {
if(pass1 != null) {
pass1.clear();
}
if(pass2 != null) {
pass2.clear();
}
}
//System.gc();
//NativeProxy.assertRegistryEmpty();
//System.runFinalization();
}
}