The new SecretDecoderRing.

This commit is contained in:
nicolson%netscape.com 2002-10-17 00:33:42 +00:00
parent 9327ee2bc2
commit c30e440420
13 changed files with 993 additions and 2 deletions

View File

@ -47,6 +47,7 @@ org.mozilla.jss.pkcs11.PK11RSAPublicKey
org.mozilla.jss.pkcs11.PK11DSAPublicKey
org.mozilla.jss.pkcs11.PK11SecureRandom
org.mozilla.jss.provider.java.security.JSSKeyStoreSpi
org.mozilla.jss.SecretDecoderRing.KeyManager
org.mozilla.jss.ssl.SSLSocket
org.mozilla.jss.ssl.SSLServerSocket
org.mozilla.jss.ssl.SocketBase
@ -70,6 +71,7 @@ org.mozilla.jss.pkix.cms
org.mozilla.jss.pkix.crmf
org.mozilla.jss.provider.java.security
org.mozilla.jss.provider.javax.crypto
org.mozilla.jss.SecretDecoderRing
org.mozilla.jss.ssl
org.mozilla.jss.tests
org.mozilla.jss.util
@ -282,7 +284,7 @@ sub javadoc {
ensure_dir_exists("$dist_dir/jssdoc");
my $targets = join(" ", @packages);
print "$targets\n";
print_do("$javadoc -private -breakiterator -sourcepath . -d $dist_dir/jssdoc $html_header_opt $targets");
print_do("$javadoc -breakiterator -sourcepath . -d $dist_dir/jssdoc $html_header_opt $targets");
print_do("cp $dist_dir/jssdoc/index.html $dist_dir/jssdoc/index.html.bak");
print_do("cp $dist_dir/jssdoc/overview-summary.html $dist_dir/jssdoc/index.html");
}

View File

@ -37,6 +37,7 @@ SHARED_LIBRARY_LIBS=yes
SHARED_LIBRARY_DIRS = \
../org/mozilla/jss/crypto \
../org/mozilla/jss/SecretDecoderRing \
../org/mozilla/jss \
../org/mozilla/jss/pkcs11 \
../org/mozilla/jss/ssl \

View File

@ -250,7 +250,7 @@ Java_org_mozilla_jss_ssl_SocketProxy_releaseNativeResources;
;+ local:
;+ *;
;+};
;+JSS_3.2.1 { # JSS 3.2.1 release
;+JSS_3.3 { # JSS 3.3 release
;+ global:
Java_org_mozilla_jss_ssl_SSLSocket_getImplementedCipherSuites;
Java_org_mozilla_jss_ssl_SSLSocket_getCipherPreferenceDefault;
@ -259,6 +259,10 @@ Java_org_mozilla_jss_ssl_SSLSocket_getCipherPreference;
Java_org_mozilla_jss_CryptoManager_configureOCSPNative;
Java_org_mozilla_jss_pkcs11_PK11SymKey_getLength;
Java_org_mozilla_jss_provider_java_security_JSSKeyStoreSpi_getCertObject;
Java_org_mozilla_jss_provider_java_security_JSSKeyStoreSpi_engineGetKeyNative;
Java_org_mozilla_jss_SecretDecoderRing_KeyManager_generateKeyNative;
Java_org_mozilla_jss_SecretDecoderRing_KeyManager_lookupKeyNative;
Java_org_mozilla_jss_SecretDecoderRing_KeyManager_deleteKeyNative;
;+ local:
;+ *;
;+};

View File

@ -0,0 +1,131 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* 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 Network Security Services for Java.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.jss.SecretDecoderRing;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import org.mozilla.jss.asn1.*;
import org.mozilla.jss.pkix.primitive.*;
import org.mozilla.jss.CryptoManager;
import org.mozilla.jss.crypto.CryptoToken;
import org.mozilla.jss.crypto.EncryptionAlgorithm;
import org.mozilla.jss.crypto.TokenException;
import java.io.*;
/**
* Decrypts data with the SecretDecoderRing.
*/
public class Decryptor {
private CryptoToken token;
private KeyManager keyManager;
/**
* Creates a Decryptor for use with the given CryptoToken.
*/
public Decryptor(CryptoToken token) {
this.token = token;
this.keyManager = new KeyManager(token);
}
/**
* Decrypts the given ciphertext. It must have been created previously
* with the SecretDecoderRing, either the JSS version or the NSS version.
* The key used for decryption must exist on the token that was passed
* into the constructor. The token will be searched for a key whose keyID
* matches the keyID in the encoded SecretDecoderRing result.
*
* @param ciphertext A DER-encoded Encoding object, created from a previous
* call to Encryptor.encrypt(), or with the NSS SecretDecoderRing.
* @return The decrypted plaintext.
* @throws InvalidKeyException If no key can be found with the matching
* keyID.
*/
public byte[] decrypt(byte[] ciphertext)
throws CryptoManager.NotInitializedException,
GeneralSecurityException, TokenException
{
CryptoManager cm = CryptoManager.getInstance();
CryptoToken savedToken = cm.getThreadToken();
try {
cm.setThreadToken(token);
//
// decode ASN1
//
Encoding encoding = (Encoding)
ASN1Util.decode(Encoding.getTemplate(), ciphertext);
//
// lookup the algorithm
//
EncryptionAlgorithm alg = EncryptionAlgorithm.fromOID(
encoding.getEncryptionOID() );
//
// Lookup the key
//
SecretKey key = keyManager.lookupKey(alg, encoding.getKeyID());
if( key == null ) {
throw new InvalidKeyException("No matching key found");
}
//
// do the decryption
//
IvParameterSpec ivSpec = new IvParameterSpec(encoding.getIv());
Cipher cipher = Cipher.getInstance(alg.toString(),
Encryptor.PROVIDER);
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] paddedPtext = cipher.doFinal(encoding.getCiphertext());
return org.mozilla.jss.crypto.Cipher.unPad(paddedPtext,
alg.getBlockSize() );
} catch(InvalidBERException ibe) {
throw new GeneralSecurityException(ibe.toString());
} catch(IllegalStateException ise) {
throw new GeneralSecurityException(ise.toString());
} catch(org.mozilla.jss.crypto.BadPaddingException bpe) {
throw new javax.crypto.BadPaddingException(bpe.getMessage());
} finally {
cm.setThreadToken(savedToken);
}
}
}

View File

@ -0,0 +1,159 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* 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 Network Security Services for Java.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.jss.SecretDecoderRing;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import org.mozilla.jss.asn1.*;
import org.mozilla.jss.pkix.primitive.*;
import org.mozilla.jss.CryptoManager;
import org.mozilla.jss.crypto.CryptoToken;
import org.mozilla.jss.crypto.EncryptionAlgorithm;
import java.io.*;
/**
* An ASN.1 class for encoding the SecretDecoderRing result.
* This class is used internally by the SecretDecoderRing.
* You need not use this class directly in order to use the SecretDecoderRing.
*/
public class Encoding implements ASN1Value {
private SEQUENCE seq = new SEQUENCE();
private byte[] iv;
private OBJECT_IDENTIFIER encOID;
private byte[] ctext;
private byte[] keyID;
public Encoding(byte[] keyID, byte[] iv, OBJECT_IDENTIFIER encOID,
byte[] ctext)
{
this.keyID = keyID;
this.iv = iv;
this.encOID = encOID;
this.ctext = ctext;
AlgorithmIdentifier algID = new AlgorithmIdentifier(
encOID, new OCTET_STRING(iv) );
seq.addElement(new OCTET_STRING(keyID));
seq.addElement(algID);
seq.addElement(new OCTET_STRING(ctext));
}
public byte[] getKeyID() {
return keyID;
}
public byte[] getIv() {
return iv;
}
public OBJECT_IDENTIFIER getEncryptionOID() {
return encOID;
}
public byte[] getCiphertext() {
return ctext;
}
public static final Tag TAG = SEQUENCE.TAG;
public Tag getTag() {
return TAG;
}
public void encode(OutputStream ostream) throws IOException {
encode(TAG, ostream);
}
public void encode(Tag implicitTag, OutputStream ostream)
throws IOException
{
seq.encode(implicitTag, ostream);
}
private static final Template templateInstance = new Template();
public static Template getTemplate() {
return templateInstance;
}
/**
* An ASN.1 class for decoding the SecretDecoderRing result.
* This class is used internally by the SecretDecoderRing.
* You need not use this class directly in order to use the
* SecretDecoderRing.
*/
public static class Template extends SEQUENCE.Template {
private SEQUENCE.Template template;
public Template() {
template = new SEQUENCE.Template();
template.addElement(OCTET_STRING.getTemplate() );
template.addElement(AlgorithmIdentifier.getTemplate() );
template.addElement(OCTET_STRING.getTemplate() );
}
public boolean tagMatch(Tag tag) {
return TAG.equals(tag);
}
public ASN1Value decode(InputStream istream)
throws IOException, InvalidBERException
{
return decode(TAG, istream);
}
public ASN1Value decode(Tag implicitTag, InputStream istream)
throws IOException, InvalidBERException
{
SEQUENCE seq = (SEQUENCE) template.decode(implicitTag, istream);
OCTET_STRING keyID = (OCTET_STRING) seq.elementAt(0);
AlgorithmIdentifier algID = (AlgorithmIdentifier)
seq.elementAt(1);
OCTET_STRING ivOS = (OCTET_STRING)
((ANY)algID.getParameters()).decodeWith(
OCTET_STRING.getTemplate());
OCTET_STRING ctextOS = (OCTET_STRING)seq.elementAt(2);
return new Encoding(keyID.toByteArray(),
ivOS.toByteArray(), algID.getOID(),
ctextOS.toByteArray());
}
}
}

View File

@ -0,0 +1,149 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* 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 Network Security Services for Java.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.jss.SecretDecoderRing;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import org.mozilla.jss.asn1.*;
import org.mozilla.jss.pkix.primitive.*;
import org.mozilla.jss.CryptoManager;
import org.mozilla.jss.crypto.CryptoToken;
import org.mozilla.jss.crypto.EncryptionAlgorithm;
import org.mozilla.jss.crypto.TokenException;
import java.io.*;
/**
* Encrypts data with the SecretDecoderRing.
*/
public class Encryptor {
private CryptoToken token;
private byte[] keyID;
private SecretKey key;
private EncryptionAlgorithm alg;
private KeyManager keyManager;
/**
* The default encryption algorithm, currently DES3_CBC.
*/
public static final EncryptionAlgorithm DEFAULT_ENCRYPTION_ALG
= EncryptionAlgorithm.DES3_CBC;
static final String PROVIDER = "Mozilla-JSS";
static final String RNG_ALG = "pkcs11prng";
/**
* Creates an Encryptor on the given CryptoToken, using the key with
* the given keyID and algorithm
* @param token The CryptoToken to use for encryption. The key must
* reside on this token.
* @param keyID The keyID of the key to use for encryption. This key
* must have been generated on this token with KeyManager.
* @param alg The EncryptionAlgorithm this key will be used for.
* @throws InvalidKeyException If no key exists on this token with this
* keyID.
*/
public Encryptor(CryptoToken token, byte[] keyID, EncryptionAlgorithm alg)
throws TokenException, InvalidKeyException
{
this.token = token;
this.keyID = keyID;
this.alg = alg;
this.keyManager = new KeyManager(token);
// make sure this key exists on the token
key = keyManager.lookupKey(alg, keyID);
// make sure key matches algorithm
// !!! not sure how to do this
}
/**
* Encrypts a byte array.
* @param plaintext The plaintext bytes to be encrypted.
* @return The ciphertext. This is actually a DER-encoded Encoding
* object. It contains the keyID, AlgorithmIdentifier, and the encrypted
* plaintext. It is compatible with the SDRResult created by NSS's
* SecretDecoderRing.
*/
public byte[] encrypt(byte[] plaintext) throws
CryptoManager.NotInitializedException,
GeneralSecurityException,
InvalidBERException
{
CryptoManager cm = CryptoManager.getInstance();
CryptoToken savedToken = cm.getThreadToken();
try {
cm.setThreadToken(token);
//
// generate an IV
//
byte[] iv = new byte[alg.getIVLength()];
SecureRandom rng = SecureRandom.getInstance(RNG_ALG,
PROVIDER);
rng.nextBytes(iv);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
//
// do the encryption
//
Cipher cipher = Cipher.getInstance(alg.toString(),PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] paddedPtext =
org.mozilla.jss.crypto.Cipher.pad(
plaintext, alg.getBlockSize() );
byte[] rawCtext = cipher.doFinal(paddedPtext);
//
// package the encrypted content and IV
//
Encoding encoding =
new Encoding(keyID, iv, alg.toOID(), rawCtext);
return ASN1Util.encode(encoding);
} catch(IllegalStateException ise ) {
throw new GeneralSecurityException(ise.toString());
} finally {
cm.setThreadToken(savedToken);
}
}
}

View File

@ -0,0 +1,193 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* 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 Netscape Security Services for Java.
*
* The Initial Developer of the Original Code is Netscape Communications
* Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "_jni/org_mozilla_jss_SecretDecoderRing_KeyManager.h"
#include <nspr.h>
#include <secitem.h>
#include <jss_exceptions.h>
#include <jssutil.h>
#include <pk11func.h>
#include <pk11util.h>
#include <Algorithm.h>
JNIEXPORT void JNICALL
Java_org_mozilla_jss_SecretDecoderRing_KeyManager_generateKeyNative
(JNIEnv *env, jobject this, jobject tokenObj, jobject algObj,
jbyteArray keyIDba, jint keySize)
{
PK11SlotInfo *slot = NULL;
CK_MECHANISM_TYPE mech;
PK11SymKey *symk = NULL;
SECItem *keyID = NULL;
/* get the slot */
if( JSS_PK11_getTokenSlotPtr(env, tokenObj, &slot) != PR_SUCCESS ) {
goto finish;
}
if( PK11_Authenticate(slot, PR_TRUE /*load certs*/, NULL /*wincx*/)
!= SECSuccess)
{
JSS_throwMsgPrErr(env, TOKEN_EXCEPTION,
"Failed to login to token");
goto finish;
}
/* get the key ID */
keyID = JSS_ByteArrayToSECItem(env, keyIDba);
if( keyID == NULL ) {
ASSERT_OUTOFMEM(env);
goto finish;
}
/* get the algorithm */
mech = JSS_getPK11MechFromAlg(env, algObj);
if( mech == CKM_INVALID_MECHANISM) {
JSS_throwMsgPrErr(env, TOKEN_EXCEPTION, "Failed to find PKCS #11 "
"mechanism for key generation algorithm");
goto finish;
}
/* generate the key */
symk = PK11_TokenKeyGen(slot, mech, NULL /*param*/, keySize, keyID,
PR_TRUE /* isToken */, NULL /*wincx*/);
if( symk == NULL ) {
JSS_throwMsgPrErr(env, TOKEN_EXCEPTION,
"Failed to generate token symmetric key");
goto finish;
}
finish:
if( symk != NULL ) {
PK11_FreeSymKey(symk);
}
if( keyID != NULL ) {
SECITEM_FreeItem(keyID, PR_TRUE /*freeit*/);
}
return;
}
JNIEXPORT jobject JNICALL
Java_org_mozilla_jss_SecretDecoderRing_KeyManager_lookupKeyNative
(JNIEnv *env, jobject this, jobject tokenObj, jobject algObj,
jbyteArray keyIDba)
{
PK11SlotInfo *slot = NULL;
PK11SymKey *symk = NULL;
SECItem *keyID = NULL;
jobject symkObj = NULL;
CK_MECHANISM_TYPE mech;
/* get the slot */
if( JSS_PK11_getTokenSlotPtr(env, tokenObj, &slot) != PR_SUCCESS ) {
goto finish;
}
if( PK11_Authenticate(slot, PR_TRUE /*load certs*/, NULL /*wincx*/)
!= SECSuccess)
{
JSS_throwMsgPrErr(env, TOKEN_EXCEPTION,
"Failed to login to token");
goto finish;
}
/* get the key ID */
keyID = JSS_ByteArrayToSECItem(env, keyIDba);
if( keyID == NULL ) {
ASSERT_OUTOFMEM(env);
goto finish;
}
/* get the algorithm */
mech = JSS_getPK11MechFromAlg(env, algObj);
if( mech == CKM_INVALID_MECHANISM) {
JSS_throwMsgPrErr(env, TOKEN_EXCEPTION, "Failed to find PKCS #11 "
"mechanism for key generation algorithm");
goto finish;
}
symk = PK11_FindFixedKey(slot, mech, keyID, NULL /*wincx*/);
if( symk != NULL ) {
symkObj = JSS_PK11_wrapSymKey(env, &symk);
}
finish:
if( symk != NULL ) {
PK11_FreeSymKey(symk);
}
if( keyID != NULL ) {
SECITEM_FreeItem(keyID, PR_TRUE /*freeit*/);
}
return symkObj;
}
JNIEXPORT void JNICALL
Java_org_mozilla_jss_SecretDecoderRing_KeyManager_deleteKeyNative
(JNIEnv *env, jobject this, jobject tokenObj, jobject key)
{
PK11SlotInfo *slot = NULL;
PK11SymKey *symk = NULL;
SECStatus status;
/* get the slot */
if( JSS_PK11_getTokenSlotPtr(env, tokenObj, &slot) != PR_SUCCESS ) {
goto finish;
}
if( PK11_Authenticate(slot, PR_TRUE /*load certs*/, NULL /*wincx*/)
!= SECSuccess)
{
JSS_throwMsgPrErr(env, TOKEN_EXCEPTION,
"Failed to login to token");
goto finish;
}
/* get the key pointer */
if( JSS_PK11_getSymKeyPtr(env, key, &symk) != PR_SUCCESS) {
goto finish;
}
if( PK11_DeleteTokenSymKey(symk) != SECSuccess ) {
JSS_throwMsgPrErr(env, TOKEN_EXCEPTION,
"Failed to delete token symmetric key");
goto finish;
}
finish:
/* don't free symk or slot, they are owned by their Java objects */
return;
}

View File

@ -0,0 +1,180 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* 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 Network Security Services for Java.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.jss.SecretDecoderRing;
import java.security.*;
import javax.crypto.*;
import org.mozilla.jss.crypto.*;
import org.mozilla.jss.util.Assert;
/**
* Creates, finds, and deletes keys for SecretDecoderRing.
*/
public class KeyManager {
private static final int KEYID_LEN = 16;
private static final String RNG_ALG = "pkcs11prng";
private static final String RNG_PROVIDER = "Mozilla-JSS";
/**
* The default key generation algorithm, currently DES3.
*/
public static final KeyGenAlgorithm DEFAULT_KEYGEN_ALG =
KeyGenAlgorithm.DES3;
/**
* The default key size. This is only relevant for algorithms
* with variable-length keys, such as AES.
*/
public static final int DEFAULT_KEYSIZE = 0;
private CryptoToken token;
/**
* Creates a new KeyManager using the given CryptoToken.
* @param token The token on which this KeyManager operates.
*/
public KeyManager(CryptoToken token) {
this.token = token;
}
/**
* Generates an SDR key with the default algorithm and key size.
* The default algorithm is stored in the constant DEFAULT_KEYGEN_ALG.
* The default key size is stored in the constant DEFAULT_KEYSIZE.
* @return The keyID of the generated key. A random keyID will be chosen
* that is not currently used on the token. The keyID must be stored
* by the application in order to use this key for encryption in the
* future.
*/
public byte[] generateKey() throws TokenException {
return generateKey(DEFAULT_KEYGEN_ALG, DEFAULT_KEYSIZE);
}
/**
* Generates an SDR key with the given algorithm and key size.
* @return The keyID of the generated key. A random keyID will be chosen
* that is not currently used on the token. The keyID must be stored
* by the application in order to use this key for encryption in the
* future.
*/
public byte[] generateKey(KeyGenAlgorithm alg, int keySize)
throws TokenException
{
byte[] keyID = generateUnusedKeyID();
generateKeyNative(token, alg, keyID, keySize);
return keyID;
}
private native void generateKeyNative(CryptoToken token,
KeyGenAlgorithm alg, byte[] keyID, int keySize);
/**
* Generates a key ID that is currently unused on this token.
* The caller is responsible for synchronization issues that may arise
* if keys are generated by different threads.
*/
private byte[] generateUnusedKeyID() throws TokenException {
try {
SecureRandom rng = SecureRandom.getInstance(RNG_ALG, RNG_PROVIDER);
byte[] keyID = new byte[KEYID_LEN];
do {
rng.nextBytes(keyID);
} while( keyExists(keyID) );
return keyID;
} catch(NoSuchAlgorithmException nsae) {
throw new RuntimeException("No such algorithm: " + RNG_ALG);
} catch(NoSuchProviderException nspe) {
throw new RuntimeException("No such provider: " + RNG_PROVIDER);
}
}
private boolean keyExists(byte[] keyid) throws TokenException {
return (lookupKey(Encryptor.DEFAULT_ENCRYPTION_ALG, keyid) != null);
}
/**
* Looks up the key on this token with the given algorithm and key ID.
* @param alg The algorithm that this key will be used for.
* This is necessary because it will be stored along with the
* key for later use by the security library. It should match
* the actual algorithm of the key you are looking for. If you
* pass in a different algorithm and try to use the key that is returned,
* the results are undefined.
* @return The key, or <tt>null</tt> if the key is not found.
*/
public SecretKey lookupKey(EncryptionAlgorithm alg, byte[] keyid)
throws TokenException
{
SymmetricKey k = lookupKeyNative(token, alg, keyid);
if( k == null ) {
return null;
} else {
return new SecretKeyFacade(k);
}
}
private native SymmetricKey lookupKeyNative(CryptoToken token,
EncryptionAlgorithm alg, byte[] keyid) throws TokenException;
/**
* Deletes the key with the given keyID from this token.
* @throws InvalidKeyException If the key does not exist on this token.
*/
public void deleteKey(byte[] keyID) throws TokenException,
InvalidKeyException
{
deleteKey(lookupKey(Encryptor.DEFAULT_ENCRYPTION_ALG, keyID));
}
/**
* Deletes this key from this token.
* @throws InvalidKeyException If the key does not reside on this token,
* or is not a JSS key.
*/
public void deleteKey(SecretKey key) throws TokenException,
InvalidKeyException
{
if( ! (key instanceof SecretKeyFacade) ) {
throw new InvalidKeyException("Key must be a JSS key");
}
deleteKeyNative(token, ((SecretKeyFacade)key).key);
}
private native void deleteKeyNative(CryptoToken token, SymmetricKey key)
throws TokenException;
}

View File

@ -0,0 +1,72 @@
#! gmake
# 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.
#
#######################################################################
# (1) Include initial platform-independent assignments (MANDATORY). #
#######################################################################
include manifest.mn
#######################################################################
# (2) Include "global" configuration information. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/config.mk
#######################################################################
# (3) Include "component" configuration information. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/$(MODULE)/config/config.mk
#######################################################################
# (4) Include "local" platform-dependent assignments (OPTIONAL). #
#######################################################################
include config.mk
#######################################################################
# (5) Execute "global" rules. (OPTIONAL) #
#######################################################################
include $(CORE_DEPTH)/coreconf/rules.mk
#######################################################################
# (6) Execute "component" rules. (OPTIONAL) #
#######################################################################
#######################################################################
# (7) Execute "local" rules. (OPTIONAL). #
#######################################################################

View File

@ -0,0 +1,37 @@
#
# 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.
#
TARGETS=$(LIBRARY)
SHARED_LIBRARY=
IMPORT_LIBRARY=
NO_MD_RELEASE = 1

View File

@ -0,0 +1,48 @@
#
# 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.
#
CORE_DEPTH = ../../../../..
MODULE = jss
NS_USE_JDK = 1
REQUIRES = nspr20 nss
PACKAGE = org/mozilla/jss/SecretDecoderRing
CSRCS = KeyManager.c \
$(NULL)
LIBRARY_NAME = jsssdr

View File

@ -0,0 +1,14 @@
<html>
<body>
A facility for encrypting and decrypting small amounts of data with
a symmetric key. This is most commonly used for encrypting password files
to implement single sign-on.
<p>KeyManager is used to create, lookup, and delete the symmetric keys used
for SecretDecoderRing. Encryptor is used to encrypt data. Decryptor is used
to decrypt data that was previously encrypted with Encryptor. Encoding
and Encoding.Template are used internally, but they were made public
because they may occasionally be useful to applications.
</body>
</html>

View File

@ -42,6 +42,7 @@ REQUIRES = nspr20 nss
DIRS = \
util \
crypto \
SecretDecoderRing \
pkcs11 \
ssl \
provider \