Search in sources :

Example 86 with ProviderException

use of java.security.ProviderException in project platform_frameworks_base by android.

the class AndroidKeyStoreKeyPairGeneratorSpi method generateSelfSignedCertificateWithFakeSignature.

@SuppressWarnings("deprecation")
private X509Certificate generateSelfSignedCertificateWithFakeSignature(PublicKey publicKey) throws IOException, CertificateParsingException {
    V3TBSCertificateGenerator tbsGenerator = new V3TBSCertificateGenerator();
    ASN1ObjectIdentifier sigAlgOid;
    AlgorithmIdentifier sigAlgId;
    byte[] signature;
    switch(mKeymasterAlgorithm) {
        case KeymasterDefs.KM_ALGORITHM_EC:
            sigAlgOid = X9ObjectIdentifiers.ecdsa_with_SHA256;
            sigAlgId = new AlgorithmIdentifier(sigAlgOid);
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERInteger(0));
            v.add(new DERInteger(0));
            signature = new DERSequence().getEncoded();
            break;
        case KeymasterDefs.KM_ALGORITHM_RSA:
            sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
            sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE);
            signature = new byte[1];
            break;
        default:
            throw new ProviderException("Unsupported key algorithm: " + mKeymasterAlgorithm);
    }
    try (ASN1InputStream publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded())) {
        tbsGenerator.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject()));
    }
    tbsGenerator.setSerialNumber(new ASN1Integer(mSpec.getCertificateSerialNumber()));
    X509Principal subject = new X509Principal(mSpec.getCertificateSubject().getEncoded());
    tbsGenerator.setSubject(subject);
    tbsGenerator.setIssuer(subject);
    tbsGenerator.setStartDate(new Time(mSpec.getCertificateNotBefore()));
    tbsGenerator.setEndDate(new Time(mSpec.getCertificateNotAfter()));
    tbsGenerator.setSignature(sigAlgId);
    TBSCertificate tbsCertificate = tbsGenerator.generateTBSCertificate();
    ASN1EncodableVector result = new ASN1EncodableVector();
    result.add(tbsCertificate);
    result.add(sigAlgId);
    result.add(new DERBitString(signature));
    return new X509CertificateObject(Certificate.getInstance(new DERSequence(result)));
}
Also used : ASN1InputStream(com.android.org.bouncycastle.asn1.ASN1InputStream) ProviderException(java.security.ProviderException) Time(com.android.org.bouncycastle.asn1.x509.Time) DERBitString(com.android.org.bouncycastle.asn1.DERBitString) ASN1Integer(com.android.org.bouncycastle.asn1.ASN1Integer) AlgorithmIdentifier(com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERInteger(com.android.org.bouncycastle.asn1.DERInteger) DERSequence(com.android.org.bouncycastle.asn1.DERSequence) X509CertificateObject(com.android.org.bouncycastle.jce.provider.X509CertificateObject) X509Principal(com.android.org.bouncycastle.jce.X509Principal) ASN1EncodableVector(com.android.org.bouncycastle.asn1.ASN1EncodableVector) V3TBSCertificateGenerator(com.android.org.bouncycastle.asn1.x509.V3TBSCertificateGenerator) TBSCertificate(com.android.org.bouncycastle.asn1.x509.TBSCertificate) ASN1ObjectIdentifier(com.android.org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 87 with ProviderException

use of java.security.ProviderException in project platform_frameworks_base by android.

the class AndroidKeyStoreKeyPairGeneratorSpi method initialize.

@SuppressWarnings("deprecation")
@Override
public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException {
    resetAll();
    boolean success = false;
    try {
        if (params == null) {
            throw new InvalidAlgorithmParameterException("Must supply params of type " + KeyGenParameterSpec.class.getName() + " or " + KeyPairGeneratorSpec.class.getName());
        }
        KeyGenParameterSpec spec;
        boolean encryptionAtRestRequired = false;
        int keymasterAlgorithm = mOriginalKeymasterAlgorithm;
        if (params instanceof KeyGenParameterSpec) {
            spec = (KeyGenParameterSpec) params;
        } else if (params instanceof KeyPairGeneratorSpec) {
            // Legacy/deprecated spec
            KeyPairGeneratorSpec legacySpec = (KeyPairGeneratorSpec) params;
            try {
                KeyGenParameterSpec.Builder specBuilder;
                String specKeyAlgorithm = legacySpec.getKeyType();
                if (specKeyAlgorithm != null) {
                    // Spec overrides the generator's default key algorithm
                    try {
                        keymasterAlgorithm = KeyProperties.KeyAlgorithm.toKeymasterAsymmetricKeyAlgorithm(specKeyAlgorithm);
                    } catch (IllegalArgumentException e) {
                        throw new InvalidAlgorithmParameterException("Invalid key type in parameters", e);
                    }
                }
                switch(keymasterAlgorithm) {
                    case KeymasterDefs.KM_ALGORITHM_EC:
                        specBuilder = new KeyGenParameterSpec.Builder(legacySpec.getKeystoreAlias(), KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY);
                        // Authorized to be used with any digest (including no digest).
                        // MD5 was never offered for Android Keystore for ECDSA.
                        specBuilder.setDigests(KeyProperties.DIGEST_NONE, KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA224, KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384, KeyProperties.DIGEST_SHA512);
                        break;
                    case KeymasterDefs.KM_ALGORITHM_RSA:
                        specBuilder = new KeyGenParameterSpec.Builder(legacySpec.getKeystoreAlias(), KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY);
                        // Authorized to be used with any digest (including no digest).
                        specBuilder.setDigests(KeyProperties.DIGEST_NONE, KeyProperties.DIGEST_MD5, KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA224, KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384, KeyProperties.DIGEST_SHA512);
                        // Authorized to be used with any encryption and signature padding
                        // schemes (including no padding).
                        specBuilder.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE, KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1, KeyProperties.ENCRYPTION_PADDING_RSA_OAEP);
                        specBuilder.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1, KeyProperties.SIGNATURE_PADDING_RSA_PSS);
                        // Disable randomized encryption requirement to support encryption
                        // padding NONE above.
                        specBuilder.setRandomizedEncryptionRequired(false);
                        break;
                    default:
                        throw new ProviderException("Unsupported algorithm: " + mKeymasterAlgorithm);
                }
                if (legacySpec.getKeySize() != -1) {
                    specBuilder.setKeySize(legacySpec.getKeySize());
                }
                if (legacySpec.getAlgorithmParameterSpec() != null) {
                    specBuilder.setAlgorithmParameterSpec(legacySpec.getAlgorithmParameterSpec());
                }
                specBuilder.setCertificateSubject(legacySpec.getSubjectDN());
                specBuilder.setCertificateSerialNumber(legacySpec.getSerialNumber());
                specBuilder.setCertificateNotBefore(legacySpec.getStartDate());
                specBuilder.setCertificateNotAfter(legacySpec.getEndDate());
                encryptionAtRestRequired = legacySpec.isEncryptionRequired();
                specBuilder.setUserAuthenticationRequired(false);
                spec = specBuilder.build();
            } catch (NullPointerException | IllegalArgumentException e) {
                throw new InvalidAlgorithmParameterException(e);
            }
        } else {
            throw new InvalidAlgorithmParameterException("Unsupported params class: " + params.getClass().getName() + ". Supported: " + KeyGenParameterSpec.class.getName() + ", " + KeyPairGeneratorSpec.class.getName());
        }
        mEntryAlias = spec.getKeystoreAlias();
        mEntryUid = spec.getUid();
        mSpec = spec;
        mKeymasterAlgorithm = keymasterAlgorithm;
        mEncryptionAtRestRequired = encryptionAtRestRequired;
        mKeySizeBits = spec.getKeySize();
        initAlgorithmSpecificParameters();
        if (mKeySizeBits == -1) {
            mKeySizeBits = getDefaultKeySize(keymasterAlgorithm);
        }
        checkValidKeySize(keymasterAlgorithm, mKeySizeBits);
        if (spec.getKeystoreAlias() == null) {
            throw new InvalidAlgorithmParameterException("KeyStore entry alias not provided");
        }
        String jcaKeyAlgorithm;
        try {
            jcaKeyAlgorithm = KeyProperties.KeyAlgorithm.fromKeymasterAsymmetricKeyAlgorithm(keymasterAlgorithm);
            mKeymasterPurposes = KeyProperties.Purpose.allToKeymaster(spec.getPurposes());
            mKeymasterBlockModes = KeyProperties.BlockMode.allToKeymaster(spec.getBlockModes());
            mKeymasterEncryptionPaddings = KeyProperties.EncryptionPadding.allToKeymaster(spec.getEncryptionPaddings());
            if (((spec.getPurposes() & KeyProperties.PURPOSE_ENCRYPT) != 0) && (spec.isRandomizedEncryptionRequired())) {
                for (int keymasterPadding : mKeymasterEncryptionPaddings) {
                    if (!KeymasterUtils.isKeymasterPaddingSchemeIndCpaCompatibleWithAsymmetricCrypto(keymasterPadding)) {
                        throw new InvalidAlgorithmParameterException("Randomized encryption (IND-CPA) required but may be violated" + " by padding scheme: " + KeyProperties.EncryptionPadding.fromKeymaster(keymasterPadding) + ". See " + KeyGenParameterSpec.class.getName() + " documentation.");
                    }
                }
            }
            mKeymasterSignaturePaddings = KeyProperties.SignaturePadding.allToKeymaster(spec.getSignaturePaddings());
            if (spec.isDigestsSpecified()) {
                mKeymasterDigests = KeyProperties.Digest.allToKeymaster(spec.getDigests());
            } else {
                mKeymasterDigests = EmptyArray.INT;
            }
            // Check that user authentication related parameters are acceptable. This method
            // will throw an IllegalStateException if there are issues (e.g., secure lock screen
            // not set up).
            KeymasterUtils.addUserAuthArgs(new KeymasterArguments(), mSpec.isUserAuthenticationRequired(), mSpec.getUserAuthenticationValidityDurationSeconds(), mSpec.isUserAuthenticationValidWhileOnBody(), mSpec.isInvalidatedByBiometricEnrollment());
        } catch (IllegalArgumentException | IllegalStateException e) {
            throw new InvalidAlgorithmParameterException(e);
        }
        mJcaKeyAlgorithm = jcaKeyAlgorithm;
        mRng = random;
        mKeyStore = KeyStore.getInstance();
        success = true;
    } finally {
        if (!success) {
            resetAll();
        }
    }
}
Also used : KeyPairGeneratorSpec(android.security.KeyPairGeneratorSpec) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) KeymasterArguments(android.security.keymaster.KeymasterArguments) RSAKeyGenParameterSpec(java.security.spec.RSAKeyGenParameterSpec) ProviderException(java.security.ProviderException) DERBitString(com.android.org.bouncycastle.asn1.DERBitString)

Example 88 with ProviderException

use of java.security.ProviderException in project platform_frameworks_base by android.

the class AndroidKeyStoreSignatureSpiBase method engineVerify.

@Override
protected final boolean engineVerify(byte[] signature) throws SignatureException {
    if (mCachedException != null) {
        throw new SignatureException(mCachedException);
    }
    try {
        ensureKeystoreOperationInitialized();
    } catch (InvalidKeyException e) {
        throw new SignatureException(e);
    }
    boolean verified;
    try {
        byte[] output = mMessageStreamer.doFinal(EmptyArray.BYTE, 0, 0, signature, // no additional entropy needed -- verification is deterministic
        null);
        if (output.length != 0) {
            throw new ProviderException("Signature verification unexpected produced output: " + output.length + " bytes");
        }
        verified = true;
    } catch (KeyStoreException e) {
        switch(e.getErrorCode()) {
            case KeymasterDefs.KM_ERROR_VERIFICATION_FAILED:
                verified = false;
                break;
            default:
                throw new SignatureException(e);
        }
    }
    resetWhilePreservingInitState();
    return verified;
}
Also used : ProviderException(java.security.ProviderException) SignatureException(java.security.SignatureException) KeyStoreException(android.security.KeyStoreException) InvalidKeyException(java.security.InvalidKeyException)

Example 89 with ProviderException

use of java.security.ProviderException in project platform_frameworks_base by android.

the class AndroidKeyStoreSignatureSpiBase method ensureKeystoreOperationInitialized.

private void ensureKeystoreOperationInitialized() throws InvalidKeyException {
    if (mMessageStreamer != null) {
        return;
    }
    if (mCachedException != null) {
        return;
    }
    if (mKey == null) {
        throw new IllegalStateException("Not initialized");
    }
    KeymasterArguments keymasterInputArgs = new KeymasterArguments();
    addAlgorithmSpecificParametersToBegin(keymasterInputArgs);
    OperationResult opResult = mKeyStore.begin(mKey.getAlias(), mSigning ? KeymasterDefs.KM_PURPOSE_SIGN : KeymasterDefs.KM_PURPOSE_VERIFY, // permit aborting this operation if keystore runs out of resources
    true, keymasterInputArgs, // no additional entropy for begin -- only finish might need some
    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");
    }
    mMessageStreamer = createMainDataStreamer(mKeyStore, opResult.token);
}
Also used : KeymasterArguments(android.security.keymaster.KeymasterArguments) ProviderException(java.security.ProviderException) OperationResult(android.security.keymaster.OperationResult) InvalidKeyException(java.security.InvalidKeyException)

Example 90 with ProviderException

use of java.security.ProviderException in project XobotOS by xamarin.

the class RandomBitsSupplier method getUnixDeviceRandom.

/**
     * On platforms with "random" devices available,
     * the method reads random bytes from the device.  <BR>
     *
     * In case of any runtime failure ProviderException gets thrown.
     */
private static synchronized byte[] getUnixDeviceRandom(int numBytes) {
    byte[] bytes = new byte[numBytes];
    int total = 0;
    int bytesRead;
    int offset = 0;
    try {
        for (; ; ) {
            bytesRead = fis.read(bytes, offset, numBytes - total);
            // hence, if it is happened there is some internal problem
            if (bytesRead == -1) {
                throw new ProviderException("bytesRead == -1");
            }
            total += bytesRead;
            offset += bytesRead;
            if (total >= numBytes) {
                break;
            }
        }
    } catch (IOException e) {
        // device was removed in runtime, or something else
        throw new ProviderException("ATTENTION: IOException in RandomBitsSupplier.getLinuxRandomBits(): " + e);
    }
    return bytes;
}
Also used : ProviderException(java.security.ProviderException) IOException(java.io.IOException)

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