Search in sources :

Example 11 with SecretKeyFacade

use of org.mozilla.jss.crypto.SecretKeyFacade in project jss by dogtagpki.

the class JCAKeyWrap method main.

public static void main(String[] args) {
    if (args.length != 2) {
        usage();
        System.exit(1);
    }
    String dbdir = args[0];
    String passwdfile = args[1];
    try {
        JCAKeyWrap keyWrap = new JCAKeyWrap(dbdir, passwdfile);
        // If the IBMJCE provider exists tests with it otherwise
        // use the SunJCE provider.
        String otherProvider = new String("IBMJCE");
        String otherRSAProvider = new String("IBMJCE");
        Provider p = null;
        p = Security.getProvider(otherProvider);
        if (p == null) {
            otherProvider = new String("SunJCE");
            otherRSAProvider = new String("SunRsaSign");
            p = Security.getProvider(otherProvider);
            if (p == null) {
                System.out.println("unable to find IBMJCE or SunJCE " + "providers");
                Provider[] providers = Security.getProviders();
                for (int i = 0; i < providers.length; i++) {
                    System.out.println("Provider " + i + ": " + providers[i].getName());
                }
                System.exit(1);
            }
        }
        // Generate an RSA keypair
        KeyPairGenerator kpgen;
        kpgen = KeyPairGenerator.getInstance("RSA", MOZ_PROVIDER_NAME);
        kpgen.initialize(Policy.RSA_MINIMUM_KEY_SIZE);
        KeyPair rsaKeyPairNSS = kpgen.generateKeyPair();
        kpgen = KeyPairGenerator.getInstance("RSA", otherRSAProvider);
        kpgen.initialize(Policy.RSA_MINIMUM_KEY_SIZE);
        KeyPair rsaKeyPairOtherProvider = kpgen.generateKeyPair();
        javax.crypto.SecretKey tripleDESKey;
        KeyGenerator keyGen = KeyGenerator.getInstance("DESede", MOZ_PROVIDER_NAME);
        tripleDESKey = keyGen.generateKey();
        keyWrap.wrapSymetricKeyWithRSA(tripleDESKey, rsaKeyPairNSS, MOZ_PROVIDER_NAME, MOZ_PROVIDER_NAME);
        if (!keyWrap.isBFipsMode()) {
            keyWrap.wrapSymetricKeyWithRSA(tripleDESKey, rsaKeyPairNSS, MOZ_PROVIDER_NAME, otherProvider);
        }
        keyGen = KeyGenerator.getInstance("AES", MOZ_PROVIDER_NAME);
        javax.crypto.SecretKey aesKeyToWrap;
        keyGen.init(128);
        aesKeyToWrap = keyGen.generateKey();
        keyGen = KeyGenerator.getInstance("AES", MOZ_PROVIDER_NAME);
        int[] AESKeySize = { 128, 192, 256 };
        for (int k = 0; k < AESKeySize.length; k++) {
            // create AES key
            javax.crypto.SecretKey aesKey;
            keyGen.init(AESKeySize[k]);
            aesKey = keyGen.generateKey();
            keyGen = KeyGenerator.getInstance("AES", MOZ_PROVIDER_NAME);
            int keyStrength = (((SecretKeyFacade) aesKey).key.getStrength());
            // 128 key strength
            if (keyStrength == 128 && !keyWrap.isBFipsMode()) {
                keyWrap.wrapSymetricKey(tripleDESKey, "AES/CBC/PKCS5Padding", aesKey, MOZ_PROVIDER_NAME, otherProvider);
                keyWrap.wrapSymetricKey(aesKeyToWrap, "AES/CBC/PKCS5Padding", aesKey, MOZ_PROVIDER_NAME, otherProvider);
                keyWrap.wrapSymetricKeyWithRSA(aesKey, rsaKeyPairNSS, MOZ_PROVIDER_NAME, otherProvider);
            } else {
                keyWrap.wrapSymetricKey(tripleDESKey, "AES/CBC/PKCS5Padding", aesKey);
                keyWrap.wrapSymetricKey(aesKeyToWrap, "AES/CBC/PKCS5Padding", aesKey);
                keyWrap.wrapSymetricKeyWithRSA(aesKey, rsaKeyPairNSS);
            }
            aesKeyToWrap = aesKey;
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}
Also used : KeyPair(java.security.KeyPair) KeyPairGenerator(java.security.KeyPairGenerator) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) IncorrectPasswordException(org.mozilla.jss.util.IncorrectPasswordException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) TokenException(org.mozilla.jss.crypto.TokenException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NotInitializedException(org.mozilla.jss.NotInitializedException) InvalidKeyException(java.security.InvalidKeyException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Provider(java.security.Provider) SecretKeyFacade(org.mozilla.jss.crypto.SecretKeyFacade) SecretKey(javax.crypto.SecretKey) KeyGenerator(javax.crypto.KeyGenerator)

Example 12 with SecretKeyFacade

use of org.mozilla.jss.crypto.SecretKeyFacade in project jss by dogtagpki.

the class JSSCipherSpi method engineInit.

@Override
public void engineInit(int opmode, Key key, AlgorithmParameterSpec givenParams, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
    try {
        // throw away any previous state
        cipher = null;
        wrapper = null;
        params = givenParams;
        if (algFamily == null) {
            throw new InvalidAlgorithmParameterException("incorrectly specified algorithm");
        }
        if (opmode != Cipher.ENCRYPT_MODE && opmode != Cipher.DECRYPT_MODE && opmode != Cipher.WRAP_MODE && opmode != Cipher.UNWRAP_MODE) {
            throw new InvalidKeyException("Invalid opmode");
        }
        StringBuffer buf = new StringBuffer();
        buf.append(algFamily);
        if (algMode != null) {
            buf.append('/');
            buf.append(algMode);
        }
        if (algPadding != null) {
            buf.append('/');
            buf.append(algPadding);
        }
        if (opmode == Cipher.ENCRYPT_MODE || opmode == Cipher.DECRYPT_MODE) {
            if (!(key instanceof SecretKeyFacade)) {
                key = importKey(key);
            }
            SymmetricKey symkey = ((SecretKeyFacade) key).key;
            // lookup the encryption algorithm
            keyStrength = symkey.getStrength();
            encAlg = EncryptionAlgorithm.lookup(algFamily, algMode, algPadding, keyStrength);
            blockSize = encAlg.getBlockSize();
            if (!token.doesAlgorithm(encAlg)) {
                throw new NoSuchAlgorithmException(encAlg.toString() + " is not supported by this token " + token.getName());
            }
            cipher = token.getCipherContext(encAlg);
            if (opmode == Cipher.ENCRYPT_MODE) {
                if (params == noAlgParams) {
                    // we're supposed to generate some params
                    params = generateAlgParams(encAlg, blockSize);
                }
                cipher.initEncrypt(symkey, params);
            } else if (opmode == Cipher.DECRYPT_MODE) {
                if (params == noAlgParams) {
                    params = null;
                }
                cipher.initDecrypt(symkey, params);
            }
        } else {
            assert (opmode == Cipher.WRAP_MODE || opmode == Cipher.UNWRAP_MODE);
            wrapAlg = KeyWrapAlgorithm.fromString(buf.toString());
            blockSize = wrapAlg.getBlockSize();
            wrapper = token.getKeyWrapper(wrapAlg);
            // generate params if necessary
            if (params == noAlgParams) {
                if (opmode == Cipher.WRAP_MODE) {
                    params = generateAlgParams(wrapAlg, blockSize);
                } else {
                    assert (opmode == Cipher.UNWRAP_MODE);
                    params = null;
                }
            }
            if (key instanceof org.mozilla.jss.crypto.PrivateKey) {
                if (opmode != Cipher.UNWRAP_MODE) {
                    throw new InvalidKeyException("Private key can only be used for unwrapping");
                }
                wrapper.initUnwrap((org.mozilla.jss.crypto.PrivateKey) key, params);
            } else if (key instanceof PublicKey) {
                if (opmode != Cipher.WRAP_MODE) {
                    throw new InvalidKeyException("Public key can only be used for wrapping");
                }
                wrapper.initWrap((PublicKey) key, params);
            } else if (key instanceof org.mozilla.jss.crypto.SecretKeyFacade) {
                org.mozilla.jss.crypto.SecretKeyFacade sk = (org.mozilla.jss.crypto.SecretKeyFacade) key;
                if (opmode == Cipher.WRAP_MODE) {
                    wrapper.initWrap(sk.key, params);
                } else {
                    assert (opmode == Cipher.UNWRAP_MODE);
                    wrapper.initUnwrap(sk.key, params);
                }
            } else {
                throw new InvalidKeyException("Invalid key type: " + key.getClass().getName());
            }
        }
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidAlgorithmParameterException(e.getMessage());
    } catch (TokenException te) {
        throw new TokenRuntimeException(te.getMessage());
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PublicKey(java.security.PublicKey) SymmetricKey(org.mozilla.jss.crypto.SymmetricKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) SecretKeyFacade(org.mozilla.jss.crypto.SecretKeyFacade) SecretKeyFacade(org.mozilla.jss.crypto.SecretKeyFacade) TokenRuntimeException(org.mozilla.jss.crypto.TokenRuntimeException) TokenException(org.mozilla.jss.crypto.TokenException)

Example 13 with SecretKeyFacade

use of org.mozilla.jss.crypto.SecretKeyFacade in project jss by dogtagpki.

the class JSSCipherSpi method engineGetKeySize.

@Override
public int engineGetKeySize(Key key) throws InvalidKeyException {
    if (key instanceof PK11PrivKey) {
        return ((PK11PrivKey) key).getStrength();
    } else if (key instanceof PK11PubKey) {
        try {
            byte[] encoded = ((PK11PubKey) key).getEncoded();
            SubjectPublicKeyInfo.Template spkiTemp = new SubjectPublicKeyInfo.Template();
            SubjectPublicKeyInfo spki = (SubjectPublicKeyInfo) ASN1Util.decode(spkiTemp, encoded);
            BIT_STRING pk = spki.getSubjectPublicKey();
            return pk.getBits().length - pk.getPadCount();
        } catch (InvalidBERException e) {
            throw new InvalidKeyException("Exception while decoding " + "public key: " + e.getMessage());
        }
    } else if (key instanceof SecretKeyFacade) {
        SymmetricKey symkey = ((SecretKeyFacade) key).key;
        return symkey.getLength();
    } else {
        key = importKey(key);
        SymmetricKey symkey = ((SecretKeyFacade) key).key;
        return symkey.getLength();
    }
}
Also used : PK11PubKey(org.mozilla.jss.pkcs11.PK11PubKey) InvalidBERException(org.mozilla.jss.asn1.InvalidBERException) SecretKeyFacade(org.mozilla.jss.crypto.SecretKeyFacade) SymmetricKey(org.mozilla.jss.crypto.SymmetricKey) InvalidKeyException(java.security.InvalidKeyException) PK11PrivKey(org.mozilla.jss.pkcs11.PK11PrivKey) SubjectPublicKeyInfo(org.mozilla.jss.pkix.primitive.SubjectPublicKeyInfo) BIT_STRING(org.mozilla.jss.asn1.BIT_STRING)

Example 14 with SecretKeyFacade

use of org.mozilla.jss.crypto.SecretKeyFacade in project jss by dogtagpki.

the class JSSMacSpi method engineInit.

@Override
public void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException {
    try {
        SymmetricKey real_key = null;
        if (key instanceof SecretKeyFacade) {
            SecretKeyFacade facade = (SecretKeyFacade) key;
            real_key = facade.key;
        } else if (key instanceof SymmetricKey) {
            real_key = (SymmetricKey) key;
        } else if (key.getEncoded() != null) {
            SecretKeyFactory factory = SecretKeyFactory.getInstance(keyName, "Mozilla-JSS");
            SecretKeySpec spec = new SecretKeySpec(key.getEncoded(), keyName);
            Key manufactured = factory.generateSecret(spec);
            if (manufactured instanceof SecretKeyFacade) {
                SecretKeyFacade facade = (SecretKeyFacade) manufactured;
                real_key = facade.key;
            } else if (manufactured instanceof SymmetricKey) {
                real_key = (SymmetricKey) manufactured;
            } else {
                String msg = "Internal error while converting key: ";
                msg += "SecretKeyFactory gave unrecognized manufactured ";
                msg += "key type: " + manufactured.getClass().getName();
                throw new InvalidKeyException(msg);
            }
        } else {
            String msg = "Must use a key created by JSS; got ";
            msg += key.getClass().getName() + ". ";
            msg += "Try exporting the key data and importing it via ";
            msg += "SecretKeyFactory or use an exportable key type ";
            msg += "so JSS can do this automatically.";
            throw new InvalidKeyException(msg);
        }
        digest.initHMAC(real_key);
    } catch (DigestException de) {
        throw new InvalidKeyException("DigestException: " + de.getMessage(), de);
    } catch (NoSuchAlgorithmException nsae) {
        throw new InvalidKeyException("NoSuchAlgorithmException when importing key to JSS: " + nsae.getMessage(), nsae);
    } catch (NoSuchProviderException nspe) {
        throw new InvalidKeyException("NoSuchProviderException when importing key to JSS: " + nspe.getMessage(), nspe);
    } catch (InvalidKeySpecException ikse) {
        throw new InvalidKeyException("InvalidKeySpecException when importing key to JSS: " + ikse.getMessage(), ikse);
    }
}
Also used : SecretKeyFacade(org.mozilla.jss.crypto.SecretKeyFacade) SecretKeySpec(javax.crypto.spec.SecretKeySpec) DigestException(java.security.DigestException) SymmetricKey(org.mozilla.jss.crypto.SymmetricKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) InvalidKeyException(java.security.InvalidKeyException) NoSuchProviderException(java.security.NoSuchProviderException) SecretKeyFactory(javax.crypto.SecretKeyFactory) Key(java.security.Key) SymmetricKey(org.mozilla.jss.crypto.SymmetricKey)

Example 15 with SecretKeyFacade

use of org.mozilla.jss.crypto.SecretKeyFacade in project jss by dogtagpki.

the class JSSSecretKeyFactorySpi method engineGenerateSecret.

@Override
public SecretKey engineGenerateSecret(KeySpec spec) throws InvalidKeySpecException {
    try {
        if (spec instanceof PBEKeySpec || spec instanceof PBEKeyGenParams) {
            PBEKeyGenParams params;
            if (spec instanceof PBEKeySpec) {
                params = makePBEKeyGenParams((PBEKeySpec) spec);
            } else {
                params = (org.mozilla.jss.crypto.PBEKeyGenParams) spec;
            }
            org.mozilla.jss.crypto.KeyGenerator gen = token.getKeyGenerator(alg);
            gen.initialize(params);
            SymmetricKey symk = gen.generate();
            params.clear();
            return new SecretKeyFacade(symk);
        } else if (spec instanceof DESedeKeySpec) {
            if (alg != KeyGenAlgorithm.DES3) {
                throw new InvalidKeySpecException("Incorrect KeySpec type (" + spec.getClass().getName() + ") for algorithm (" + alg.toString() + ")");
            }
            return generateKeyFromBits(((DESedeKeySpec) spec).getKey(), SymmetricKey.Type.DES3);
        } else if (spec instanceof DESKeySpec) {
            if (alg != KeyGenAlgorithm.DES) {
                throw new InvalidKeySpecException("Incorrect KeySpec type (" + spec.getClass().getName() + ") for algorithm (" + alg.toString() + ")");
            }
            return generateKeyFromBits(((DESKeySpec) spec).getKey(), SymmetricKey.Type.DES);
        } else if (spec instanceof SecretKeySpec) {
            SecretKeySpec kspec = (SecretKeySpec) spec;
            SymmetricKey.Type type = SymmetricKey.Type.fromName(kspec.getAlgorithm());
            return generateKeyFromBits(kspec.getEncoded(), type);
        } else {
            throw new InvalidKeySpecException("Unsupported KeySpec: " + spec.getClass().getName());
        }
    } catch (TokenException te) {
        throw new TokenRuntimeException(te.getMessage());
    } catch (InvalidAlgorithmParameterException iape) {
        throw new InvalidKeySpecException("InvalidAlgorithmParameterException: " + iape.getMessage());
    } catch (IllegalStateException e) {
        throw (TokenRuntimeException) new TokenRuntimeException("IllegalStateException: " + e.getMessage()).initCause(e);
    } catch (CharConversionException e) {
        throw new InvalidKeySpecException("CharConversionException: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidKeySpecException("NoSuchAlgorithmException: " + e.getMessage(), e);
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) SymmetricKey(org.mozilla.jss.crypto.SymmetricKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CharConversionException(java.io.CharConversionException) PBEKeyGenParams(org.mozilla.jss.crypto.PBEKeyGenParams) SecretKeyFacade(org.mozilla.jss.crypto.SecretKeyFacade) TokenRuntimeException(org.mozilla.jss.crypto.TokenRuntimeException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) TokenException(org.mozilla.jss.crypto.TokenException) DESedeKeySpec(javax.crypto.spec.DESedeKeySpec) DESKeySpec(javax.crypto.spec.DESKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException)

Aggregations

SecretKeyFacade (org.mozilla.jss.crypto.SecretKeyFacade)17 InvalidKeyException (java.security.InvalidKeyException)11 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)10 SymmetricKey (org.mozilla.jss.crypto.SymmetricKey)10 TokenException (org.mozilla.jss.crypto.TokenException)8 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)6 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 BadPaddingException (javax.crypto.BadPaddingException)4 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)4 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)4 SecretKey (javax.crypto.SecretKey)4 CryptoToken (org.mozilla.jss.crypto.CryptoToken)4 TokenRuntimeException (org.mozilla.jss.crypto.TokenRuntimeException)4 Cipher (javax.crypto.Cipher)3 DESedeKeySpec (javax.crypto.spec.DESedeKeySpec)3 SecretKeySpec (javax.crypto.spec.SecretKeySpec)3 CryptoManager (org.mozilla.jss.CryptoManager)3 NotInitializedException (org.mozilla.jss.NotInitializedException)3 CharConversionException (java.io.CharConversionException)2