Search in sources :

Example 1 with SecretKeyFacade

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

the class JCAKeyWrap method wrapSymetricKeyWithRSA.

/**
 * @param symKey
 * @param keyPair
 * @param providerA
 * @param providerB
 * @throws Exception
 */
public void wrapSymetricKeyWithRSA(Key symKey, KeyPair keyPair, String providerA, String providerB) throws Exception {
    try {
        String symKeyType = new String(symKey.getAlgorithm());
        System.out.print("Wrap " + symKeyType + " " + ((SecretKeyFacade) symKey).key.getStrength() + " with RSA. ");
        // wrap key
        Cipher cipher = Cipher.getInstance("RSA", providerA);
        cipher.init(Cipher.WRAP_MODE, keyPair.getPublic());
        byte[] wrappedData = cipher.wrap(symKey);
        // unwrap key
        cipher = Cipher.getInstance("RSA", providerA);
        cipher.init(Cipher.UNWRAP_MODE, keyPair.getPrivate());
        SecretKey unwrappedKey = (javax.crypto.SecretKey) cipher.unwrap(wrappedData, symKeyType, Cipher.SECRET_KEY);
        testKeys(symKey, unwrappedKey, providerA, providerB);
    } catch (BadPaddingException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (IllegalBlockSizeException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (InvalidKeyException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (NoSuchAlgorithmException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (NoSuchPaddingException ex) {
        ex.printStackTrace();
        System.exit(1);
    }
}
Also used : SecretKey(javax.crypto.SecretKey) SecretKeyFacade(org.mozilla.jss.crypto.SecretKeyFacade) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) Cipher(javax.crypto.Cipher) BadPaddingException(javax.crypto.BadPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 2 with SecretKeyFacade

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

the class JCAKeyWrap method testKeys.

/**
 * @param keyA
 * @param keyB
 * @param providerA
 * @param providerB
 * @throws java.lang.Exception
 */
protected void testKeys(Key keyA, Key keyB, String providerA, String providerB) throws Exception {
    // ensure keys are equal
    if (bFipsMode) {
        // Keys are not extractable so just check key length
        if (((SecretKeyFacade) keyA).key.getStrength() != ((SecretKeyFacade) keyB).key.getStrength()) {
            throw new Exception("unwrapped key strength does not " + "match orginal");
        }
    } else if (!keysEqual(keyA, keyB)) {
        throw new Exception("unwrapped key " + "does not match original");
    }
    // As an extra test encrypt with keyA using ProviderA
    // and decrypt with with keyB using ProviderB
    String cipherAlg = testCipher(keyA.getAlgorithm());
    System.out.println("Test " + cipherAlg + " encrypt with " + providerA + " decrypt " + providerB);
    // if no padding is used plainText needs to be fixed length
    // block divisable by 8 bytes
    byte[] plaintext = plainText;
    if (cipherAlg.endsWith("PKCS5Padding")) {
        plaintext = plainTextPad;
    }
    // encrypt some text as a test with the key to be wrap
    Cipher cipher = Cipher.getInstance(cipherAlg, providerA);
    cipher.init(Cipher.ENCRYPT_MODE, keyA);
    byte[] encryptedText = cipher.doFinal(plaintext);
    // generate the algorithm Parameters; they need to be
    // the same for encrypt/decrypt if they are needed.
    AlgorithmParameters ap = null;
    byte[] encodedAlgParams = null;
    ap = cipher.getParameters();
    if (ap != null) {
        // get parameters to store away as example.
        encodedAlgParams = ap.getEncoded();
    }
    // use the unwrapped key for decryption
    cipher = Cipher.getInstance(cipherAlg, providerB);
    if (encodedAlgParams == null) {
        cipher.init(Cipher.DECRYPT_MODE, keyB);
    } else {
        // retrieve the algorithmParameters from the encoded array
        AlgorithmParameters aps = AlgorithmParameters.getInstance(keyB.getAlgorithm());
        aps.init(encodedAlgParams);
        cipher.init(Cipher.DECRYPT_MODE, keyB, aps);
    }
    byte[] recovered = new byte[plaintext.length];
    int rLen = cipher.update(encryptedText, 0, encryptedText.length, recovered, 0);
    rLen += cipher.doFinal(recovered, rLen);
    if (!java.util.Arrays.equals(plaintext, recovered)) {
        throw new Exception("key do not match. unable to encrypt/decrypt.");
    }
}
Also used : SecretKeyFacade(org.mozilla.jss.crypto.SecretKeyFacade) Cipher(javax.crypto.Cipher) 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) AlgorithmParameters(java.security.AlgorithmParameters)

Example 3 with SecretKeyFacade

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

the class CrossHMACTest method main.

/**
 * Main test method.
 * @param argv
 */
public static void main(String[] argv) {
    try {
        CrossHMACTest hmacTest = new CrossHMACTest(argv);
        // The secret key must be a JSS key. That is, it must be an
        // instanceof org.mozilla.jss.crypto.SecretKeyFacade.
        // Generate the secret key using PKCS # 5 password Based Encryption
        // we have to specify a salt and an iteration count.
        PBEKeySpec pbeKeySpec;
        SecretKeyFactory keyFac;
        SecretKeyFacade sk;
        byte[] salt = { (byte) 0x0a, (byte) 0x6d, (byte) 0x07, (byte) 0xba, (byte) 0x1e, (byte) 0xbd, (byte) 0x72, (byte) 0xf1 };
        int iterationCount = 7;
        pbeKeySpec = new PBEKeySpec("password".toCharArray(), salt, iterationCount);
        keyFac = SecretKeyFactory.getInstance("PBEWithSHA1AndDES3", "Mozilla-JSS");
        sk = (SecretKeyFacade) keyFac.generateSecret(pbeKeySpec);
        // ///////////////////////////////////////////////////////////
        // Test all available algorithms
        // ///////////////////////////////////////////////////////////
        String clearText = new String("FireFox and Thunderbird rule");
        for (int i = 0; i < JSS_HMAC_Algs.length; i++) {
            if (hmacTest.fipsMode()) {
                // https://bugzilla.mozilla.org/show_bug.cgi?id=436907
                if (!JSS_HMAC_Algs[i].equals("HmacSHA512")) {
                    hmacTest.doHMAC(JSS_HMAC_Algs[i], sk, clearText);
                }
            } else {
                // providers that also support the given algorithm
                if (!hmacTest.compareHMAC(JSS_HMAC_Algs[i], sk, clearText)) {
                    // no provider to compare results with so just test JSS
                    hmacTest.doHMAC(JSS_HMAC_Algs[i], sk, clearText);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}
Also used : SecretKeyFacade(org.mozilla.jss.crypto.SecretKeyFacade)

Example 4 with SecretKeyFacade

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

the class JSSCipherSpi method engineUnwrapSecret.

private Key engineUnwrapSecret(byte[] wrappedKey, String wrappedKeyAlg) throws InvalidKeyException, NoSuchAlgorithmException {
    try {
        int idx = wrappedKeyAlg.indexOf('/');
        if (idx != -1) {
            wrappedKeyAlg = wrappedKeyAlg.substring(0, idx);
        }
        SymmetricKey.Type wrappedKeyType = SymmetricKey.Type.fromName(wrappedKeyAlg);
        // Specify 0 for key length. This will use the default key length.
        // Won't work for algorithms without a default, like RC4, unless a
        // padded algorithm is used.
        SymmetricKey key = wrapper.unwrapSymmetric(wrappedKey, wrappedKeyType, 0);
        return new SecretKeyFacade(key);
    } catch (StringIndexOutOfBoundsException e) {
        throw new NoSuchAlgorithmException("Unknown algorithm: " + wrappedKeyAlg);
    } catch (TokenException te) {
        throw new TokenRuntimeException(te.getMessage());
    } catch (InvalidAlgorithmParameterException iape) {
        throw new NoSuchAlgorithmException("Invalid algorithm parameters" + iape.getMessage());
    }
}
Also used : SecretKeyFacade(org.mozilla.jss.crypto.SecretKeyFacade) TokenRuntimeException(org.mozilla.jss.crypto.TokenRuntimeException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) TokenException(org.mozilla.jss.crypto.TokenException) SymmetricKey(org.mozilla.jss.crypto.SymmetricKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 5 with SecretKeyFacade

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

the class JSSSecretKeyFactorySpi method engineTranslateKey.

@Override
public SecretKey engineTranslateKey(SecretKey key) throws InvalidKeyException {
    if (key instanceof SecretKeyFacade) {
        // try cloning the key
        try {
            SymmetricKey oldkey = ((SecretKeyFacade) key).key;
            CryptoToken owningToken = oldkey.getOwningToken();
            org.mozilla.jss.crypto.KeyGenerator keygen = token.getKeyGenerator(oldkey.getType().getKeyGenAlg());
            SymmetricKey newkey = keygen.clone(oldkey);
            return new SecretKeyFacade(newkey);
        } catch (SymmetricKey.NotExtractableException nee) {
            // no way around this, we fail
            throw new InvalidKeyException("key is not extractable");
        } catch (TokenException te) {
        // fall through and try doing it the long way
        } catch (NoSuchAlgorithmException nsae) {
            throw new InvalidKeyException("Unsupported algorithm: " + nsae.getMessage());
        }
    }
    // try extracting the key value and then creating a new key
    try {
        byte[] keyBits = key.getEncoded();
        if (keyBits == null) {
            throw new InvalidKeyException("Key is not extractable");
        }
        SymmetricKey.Type keyType = SymmetricKey.Type.fromName(key.getAlgorithm());
        return generateKeyFromBits(keyBits, keyType);
    } catch (NoSuchAlgorithmException nsae) {
        throw new InvalidKeyException("Unsupported algorithm: " + key.getAlgorithm());
    } catch (TokenException te) {
        throw new InvalidKeyException("Token failed to process key: " + te.getMessage());
    } catch (InvalidKeySpecException ikse) {
        throw new InvalidKeyException("Invalid key spec: " + ikse.getMessage());
    } catch (InvalidAlgorithmParameterException iape) {
        throw new InvalidKeyException("Invalid algorithm parameters: " + iape.getMessage());
    }
}
Also used : CryptoToken(org.mozilla.jss.crypto.CryptoToken) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) SymmetricKey(org.mozilla.jss.crypto.SymmetricKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) SecretKeyFacade(org.mozilla.jss.crypto.SecretKeyFacade) TokenException(org.mozilla.jss.crypto.TokenException) 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