Search in sources :

Example 51 with ProviderException

use of java.security.ProviderException in project jdk8u_jdk by JetBrains.

the class DHKeyAgreement method engineGenerateSecret.

/**
     * Generates the shared secret, and places it into the buffer
     * <code>sharedSecret</code>, beginning at <code>offset</code>.
     *
     * <p>If the <code>sharedSecret</code> buffer is too small to hold the
     * result, a <code>ShortBufferException</code> is thrown.
     * In this case, this call should be repeated with a larger output buffer.
     *
     * <p>This method resets this <code>KeyAgreementSpi</code> object,
     * so that it
     * can be reused for further key agreements. Unless this key agreement is
     * reinitialized with one of the <code>engineInit</code> methods, the same
     * private information and algorithm parameters will be used for
     * subsequent key agreements.
     *
     * @param sharedSecret the buffer for the shared secret
     * @param offset the offset in <code>sharedSecret</code> where the
     * shared secret will be stored
     *
     * @return the number of bytes placed into <code>sharedSecret</code>
     *
     * @exception IllegalStateException if this key agreement has not been
     * completed yet
     * @exception ShortBufferException if the given output buffer is too small
     * to hold the secret
     */
protected int engineGenerateSecret(byte[] sharedSecret, int offset) throws IllegalStateException, ShortBufferException {
    if (generateSecret == false) {
        throw new IllegalStateException("Key agreement has not been completed yet");
    }
    if (sharedSecret == null) {
        throw new ShortBufferException("No buffer provided for shared secret");
    }
    BigInteger modulus = init_p;
    int expectedLen = (modulus.bitLength() + 7) >>> 3;
    if ((sharedSecret.length - offset) < expectedLen) {
        throw new ShortBufferException("Buffer too short for shared secret");
    }
    // Reset the key agreement after checking for ShortBufferException
    // above, so user can recover w/o losing internal state
    generateSecret = false;
    /*
         * NOTE: BigInteger.toByteArray() returns a byte array containing
         * the two's-complement representation of this BigInteger with
         * the most significant byte is in the zeroth element. This
         * contains the minimum number of bytes required to represent
         * this BigInteger, including at least one sign bit whose value
         * is always 0.
         *
         * Keys are always positive, and the above sign bit isn't
         * actually used when representing keys.  (i.e. key = new
         * BigInteger(1, byteArray))  To obtain an array containing
         * exactly expectedLen bytes of magnitude, we strip any extra
         * leading 0's, or pad with 0's in case of a "short" secret.
         */
    byte[] secret = this.y.modPow(this.x, modulus).toByteArray();
    if (secret.length == expectedLen) {
        System.arraycopy(secret, 0, sharedSecret, offset, secret.length);
    } else {
        // Array too short, pad it w/ leading 0s
        if (secret.length < expectedLen) {
            System.arraycopy(secret, 0, sharedSecret, offset + (expectedLen - secret.length), secret.length);
        } else {
            // Array too long, check and trim off the excess
            if ((secret.length == (expectedLen + 1)) && secret[0] == 0) {
                // ignore the leading sign byte
                System.arraycopy(secret, 1, sharedSecret, offset, expectedLen);
            } else {
                throw new ProviderException("Generated secret is out-of-range");
            }
        }
    }
    return expectedLen;
}
Also used : ProviderException(java.security.ProviderException) ShortBufferException(javax.crypto.ShortBufferException) BigInteger(java.math.BigInteger)

Example 52 with ProviderException

use of java.security.ProviderException in project android_frameworks_base by crdroidandroid.

the class AndroidKeyStoreHmacSpi method engineDoFinal.

@Override
protected byte[] engineDoFinal() {
    try {
        ensureKeystoreOperationInitialized();
    } catch (InvalidKeyException e) {
        throw new ProviderException("Failed to reinitialize MAC", e);
    }
    byte[] result;
    try {
        result = mChunkedStreamer.doFinal(null, 0, 0, // no signature provided -- this invocation will generate one
        null, // no additional entropy needed -- HMAC is deterministic
        null);
    } catch (KeyStoreException e) {
        throw new ProviderException("Keystore operation failed", e);
    }
    resetWhilePreservingInitState();
    return result;
}
Also used : ProviderException(java.security.ProviderException) KeyStoreException(android.security.KeyStoreException) InvalidKeyException(java.security.InvalidKeyException)

Example 53 with ProviderException

use of java.security.ProviderException in project android_frameworks_base by crdroidandroid.

the class AndroidKeyStoreAuthenticatedAESCipherSpi method loadAlgorithmSpecificParametersFromBeginResult.

@Override
protected final void loadAlgorithmSpecificParametersFromBeginResult(@NonNull KeymasterArguments keymasterArgs) {
    mIvHasBeenUsed = true;
    // NOTE: Keymaster doesn't always return an IV, even if it's used.
    byte[] returnedIv = keymasterArgs.getBytes(KeymasterDefs.KM_TAG_NONCE, null);
    if ((returnedIv != null) && (returnedIv.length == 0)) {
        returnedIv = null;
    }
    if (mIv == null) {
        mIv = returnedIv;
    } else if ((returnedIv != null) && (!Arrays.equals(returnedIv, mIv))) {
        throw new ProviderException("IV in use differs from provided IV");
    }
}
Also used : ProviderException(java.security.ProviderException)

Example 54 with ProviderException

use of java.security.ProviderException in project android_frameworks_base by crdroidandroid.

the class AndroidKeyStoreHmacSpi method ensureKeystoreOperationInitialized.

private void ensureKeystoreOperationInitialized() throws InvalidKeyException {
    if (mChunkedStreamer != null) {
        return;
    }
    if (mKey == null) {
        throw new IllegalStateException("Not initialized");
    }
    KeymasterArguments keymasterArgs = new KeymasterArguments();
    keymasterArgs.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, KeymasterDefs.KM_ALGORITHM_HMAC);
    keymasterArgs.addEnum(KeymasterDefs.KM_TAG_DIGEST, mKeymasterDigest);
    keymasterArgs.addUnsignedInt(KeymasterDefs.KM_TAG_MAC_LENGTH, mMacSizeBits);
    OperationResult opResult = mKeyStore.begin(mKey.getAlias(), KeymasterDefs.KM_PURPOSE_SIGN, true, keymasterArgs, // no additional entropy needed for HMAC because it's deterministic
    null, mKey.getUid());
    if (opResult == null) {
        throw new KeyStoreConnectException();
    }
    // Store operation token and handle regardless of the error code returned by KeyStore to
    // ensure that the operation gets aborted immediately if the code below throws an exception.
    mOperationToken = opResult.token;
    mOperationHandle = opResult.operationHandle;
    // If necessary, throw an exception due to KeyStore operation having failed.
    InvalidKeyException e = KeyStoreCryptoOperationUtils.getInvalidKeyExceptionForInit(mKeyStore, mKey, opResult.resultCode);
    if (e != null) {
        throw e;
    }
    if (mOperationToken == null) {
        throw new ProviderException("Keystore returned null operation token");
    }
    if (mOperationHandle == 0) {
        throw new ProviderException("Keystore returned invalid operation handle");
    }
    mChunkedStreamer = new KeyStoreCryptoOperationChunkedStreamer(new KeyStoreCryptoOperationChunkedStreamer.MainDataStream(mKeyStore, mOperationToken));
}
Also used : KeymasterArguments(android.security.keymaster.KeymasterArguments) ProviderException(java.security.ProviderException) OperationResult(android.security.keymaster.OperationResult) InvalidKeyException(java.security.InvalidKeyException)

Example 55 with ProviderException

use of java.security.ProviderException in project android_frameworks_base by crdroidandroid.

the class AndroidKeyStoreKeyGeneratorSpi method engineGenerateKey.

@Override
protected SecretKey engineGenerateKey() {
    KeyGenParameterSpec spec = mSpec;
    if (spec == null) {
        throw new IllegalStateException("Not initialized");
    }
    KeymasterArguments args = new KeymasterArguments();
    args.addUnsignedInt(KeymasterDefs.KM_TAG_KEY_SIZE, mKeySizeBits);
    args.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, mKeymasterAlgorithm);
    args.addEnums(KeymasterDefs.KM_TAG_PURPOSE, mKeymasterPurposes);
    args.addEnums(KeymasterDefs.KM_TAG_BLOCK_MODE, mKeymasterBlockModes);
    args.addEnums(KeymasterDefs.KM_TAG_PADDING, mKeymasterPaddings);
    args.addEnums(KeymasterDefs.KM_TAG_DIGEST, mKeymasterDigests);
    KeymasterUtils.addUserAuthArgs(args, spec.isUserAuthenticationRequired(), spec.getUserAuthenticationValidityDurationSeconds(), spec.isUserAuthenticationValidWhileOnBody(), spec.isInvalidatedByBiometricEnrollment());
    KeymasterUtils.addMinMacLengthAuthorizationIfNecessary(args, mKeymasterAlgorithm, mKeymasterBlockModes, mKeymasterDigests);
    args.addDateIfNotNull(KeymasterDefs.KM_TAG_ACTIVE_DATETIME, spec.getKeyValidityStart());
    args.addDateIfNotNull(KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME, spec.getKeyValidityForOriginationEnd());
    args.addDateIfNotNull(KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME, spec.getKeyValidityForConsumptionEnd());
    if (((spec.getPurposes() & KeyProperties.PURPOSE_ENCRYPT) != 0) && (!spec.isRandomizedEncryptionRequired())) {
        // Permit caller-provided IV when encrypting with this key
        args.addBoolean(KeymasterDefs.KM_TAG_CALLER_NONCE);
    }
    byte[] additionalEntropy = KeyStoreCryptoOperationUtils.getRandomBytesToMixIntoKeystoreRng(mRng, (mKeySizeBits + 7) / 8);
    int flags = 0;
    String keyAliasInKeystore = Credentials.USER_SECRET_KEY + spec.getKeystoreAlias();
    KeyCharacteristics resultingKeyCharacteristics = new KeyCharacteristics();
    boolean success = false;
    try {
        Credentials.deleteAllTypesForAlias(mKeyStore, spec.getKeystoreAlias(), spec.getUid());
        int errorCode = mKeyStore.generateKey(keyAliasInKeystore, args, additionalEntropy, spec.getUid(), flags, resultingKeyCharacteristics);
        if (errorCode != KeyStore.NO_ERROR) {
            throw new ProviderException("Keystore operation failed", KeyStore.getKeyStoreException(errorCode));
        }
        @KeyProperties.KeyAlgorithmEnum String keyAlgorithmJCA;
        try {
            keyAlgorithmJCA = KeyProperties.KeyAlgorithm.fromKeymasterSecretKeyAlgorithm(mKeymasterAlgorithm, mKeymasterDigest);
        } catch (IllegalArgumentException e) {
            throw new ProviderException("Failed to obtain JCA secret key algorithm name", e);
        }
        SecretKey result = new AndroidKeyStoreSecretKey(keyAliasInKeystore, spec.getUid(), keyAlgorithmJCA);
        success = true;
        return result;
    } finally {
        if (!success) {
            Credentials.deleteAllTypesForAlias(mKeyStore, spec.getKeystoreAlias(), spec.getUid());
        }
    }
}
Also used : KeymasterArguments(android.security.keymaster.KeymasterArguments) KeyGenParameterSpec(android.security.keystore.KeyGenParameterSpec) ProviderException(java.security.ProviderException) SecretKey(javax.crypto.SecretKey) KeyCharacteristics(android.security.keymaster.KeyCharacteristics)

Aggregations

ProviderException (java.security.ProviderException)128 KeymasterArguments (android.security.keymaster.KeymasterArguments)30 InvalidKeyException (java.security.InvalidKeyException)26 OperationResult (android.security.keymaster.OperationResult)25 KeyStoreException (android.security.KeyStoreException)20 KeyCharacteristics (android.security.keymaster.KeyCharacteristics)20 DERBitString (com.android.org.bouncycastle.asn1.DERBitString)15 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)15 BigInteger (java.math.BigInteger)13 IOException (java.io.IOException)12 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)12 ASN1Integer (com.android.org.bouncycastle.asn1.ASN1Integer)10 DERInteger (com.android.org.bouncycastle.asn1.DERInteger)10 ByteArrayOutputStream (java.io.ByteArrayOutputStream)10 RSAKeyGenParameterSpec (java.security.spec.RSAKeyGenParameterSpec)10 GeneralSecurityException (java.security.GeneralSecurityException)6 KeyStoreException (java.security.KeyStoreException)6 NoSuchProviderException (java.security.NoSuchProviderException)6 KeymasterCertificateChain (android.security.keymaster.KeymasterCertificateChain)5 KeyProtection (android.security.keystore.KeyProtection)5