Search in sources :

Example 26 with InvalidKeySpecException

use of java.security.spec.InvalidKeySpecException in project android_frameworks_base by AOSPA.

the class BackupManagerService method buildCharArrayKey.

private SecretKey buildCharArrayKey(String algorithm, char[] pwArray, byte[] salt, int rounds) {
    try {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
        KeySpec ks = new PBEKeySpec(pwArray, salt, rounds, PBKDF2_KEY_SIZE);
        return keyFactory.generateSecret(ks);
    } catch (InvalidKeySpecException e) {
        Slog.e(TAG, "Invalid key spec for PBKDF2!");
    } catch (NoSuchAlgorithmException e) {
        Slog.e(TAG, "PBKDF2 unavailable!");
    }
    return null;
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKeySpec(javax.crypto.spec.SecretKeySpec) KeySpec(java.security.spec.KeySpec) PBEKeySpec(javax.crypto.spec.PBEKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecretKeyFactory(javax.crypto.SecretKeyFactory)

Example 27 with InvalidKeySpecException

use of java.security.spec.InvalidKeySpecException in project android_frameworks_base by AOSPA.

the class ApkSignatureSchemeV2Verifier method verifySigner.

private static X509Certificate[] verifySigner(ByteBuffer signerBlock, Map<Integer, byte[]> contentDigests, CertificateFactory certFactory) throws SecurityException, IOException {
    ByteBuffer signedData = getLengthPrefixedSlice(signerBlock);
    ByteBuffer signatures = getLengthPrefixedSlice(signerBlock);
    byte[] publicKeyBytes = readLengthPrefixedByteArray(signerBlock);
    int signatureCount = 0;
    int bestSigAlgorithm = -1;
    byte[] bestSigAlgorithmSignatureBytes = null;
    List<Integer> signaturesSigAlgorithms = new ArrayList<>();
    while (signatures.hasRemaining()) {
        signatureCount++;
        try {
            ByteBuffer signature = getLengthPrefixedSlice(signatures);
            if (signature.remaining() < 8) {
                throw new SecurityException("Signature record too short");
            }
            int sigAlgorithm = signature.getInt();
            signaturesSigAlgorithms.add(sigAlgorithm);
            if (!isSupportedSignatureAlgorithm(sigAlgorithm)) {
                continue;
            }
            if ((bestSigAlgorithm == -1) || (compareSignatureAlgorithm(sigAlgorithm, bestSigAlgorithm) > 0)) {
                bestSigAlgorithm = sigAlgorithm;
                bestSigAlgorithmSignatureBytes = readLengthPrefixedByteArray(signature);
            }
        } catch (IOException | BufferUnderflowException e) {
            throw new SecurityException("Failed to parse signature record #" + signatureCount, e);
        }
    }
    if (bestSigAlgorithm == -1) {
        if (signatureCount == 0) {
            throw new SecurityException("No signatures found");
        } else {
            throw new SecurityException("No supported signatures found");
        }
    }
    String keyAlgorithm = getSignatureAlgorithmJcaKeyAlgorithm(bestSigAlgorithm);
    Pair<String, ? extends AlgorithmParameterSpec> signatureAlgorithmParams = getSignatureAlgorithmJcaSignatureAlgorithm(bestSigAlgorithm);
    String jcaSignatureAlgorithm = signatureAlgorithmParams.first;
    AlgorithmParameterSpec jcaSignatureAlgorithmParams = signatureAlgorithmParams.second;
    boolean sigVerified;
    try {
        PublicKey publicKey = KeyFactory.getInstance(keyAlgorithm).generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        Signature sig = Signature.getInstance(jcaSignatureAlgorithm);
        sig.initVerify(publicKey);
        if (jcaSignatureAlgorithmParams != null) {
            sig.setParameter(jcaSignatureAlgorithmParams);
        }
        sig.update(signedData);
        sigVerified = sig.verify(bestSigAlgorithmSignatureBytes);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | InvalidAlgorithmParameterException | SignatureException e) {
        throw new SecurityException("Failed to verify " + jcaSignatureAlgorithm + " signature", e);
    }
    if (!sigVerified) {
        throw new SecurityException(jcaSignatureAlgorithm + " signature did not verify");
    }
    // Signature over signedData has verified.
    byte[] contentDigest = null;
    signedData.clear();
    ByteBuffer digests = getLengthPrefixedSlice(signedData);
    List<Integer> digestsSigAlgorithms = new ArrayList<>();
    int digestCount = 0;
    while (digests.hasRemaining()) {
        digestCount++;
        try {
            ByteBuffer digest = getLengthPrefixedSlice(digests);
            if (digest.remaining() < 8) {
                throw new IOException("Record too short");
            }
            int sigAlgorithm = digest.getInt();
            digestsSigAlgorithms.add(sigAlgorithm);
            if (sigAlgorithm == bestSigAlgorithm) {
                contentDigest = readLengthPrefixedByteArray(digest);
            }
        } catch (IOException | BufferUnderflowException e) {
            throw new IOException("Failed to parse digest record #" + digestCount, e);
        }
    }
    if (!signaturesSigAlgorithms.equals(digestsSigAlgorithms)) {
        throw new SecurityException("Signature algorithms don't match between digests and signatures records");
    }
    int digestAlgorithm = getSignatureAlgorithmContentDigestAlgorithm(bestSigAlgorithm);
    byte[] previousSignerDigest = contentDigests.put(digestAlgorithm, contentDigest);
    if ((previousSignerDigest != null) && (!MessageDigest.isEqual(previousSignerDigest, contentDigest))) {
        throw new SecurityException(getContentDigestAlgorithmJcaDigestAlgorithm(digestAlgorithm) + " contents digest does not match the digest specified by a preceding signer");
    }
    ByteBuffer certificates = getLengthPrefixedSlice(signedData);
    List<X509Certificate> certs = new ArrayList<>();
    int certificateCount = 0;
    while (certificates.hasRemaining()) {
        certificateCount++;
        byte[] encodedCert = readLengthPrefixedByteArray(certificates);
        X509Certificate certificate;
        try {
            certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(encodedCert));
        } catch (CertificateException e) {
            throw new SecurityException("Failed to decode certificate #" + certificateCount, e);
        }
        certificate = new VerbatimX509Certificate(certificate, encodedCert);
        certs.add(certificate);
    }
    if (certs.isEmpty()) {
        throw new SecurityException("No certificates listed");
    }
    X509Certificate mainCertificate = certs.get(0);
    byte[] certificatePublicKeyBytes = mainCertificate.getPublicKey().getEncoded();
    if (!Arrays.equals(publicKeyBytes, certificatePublicKeyBytes)) {
        throw new SecurityException("Public key mismatch between certificate and signature record");
    }
    return certs.toArray(new X509Certificate[certs.size()]);
}
Also used : ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) BufferUnderflowException(java.nio.BufferUnderflowException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) DirectByteBuffer(java.nio.DirectByteBuffer) ByteBuffer(java.nio.ByteBuffer) X509Certificate(java.security.cert.X509Certificate) BigInteger(java.math.BigInteger) ByteArrayInputStream(java.io.ByteArrayInputStream) Signature(java.security.Signature) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 28 with InvalidKeySpecException

use of java.security.spec.InvalidKeySpecException in project android_frameworks_base by AOSPA.

the class AndroidKeyStoreProvider method getAndroidKeyStorePublicKey.

@NonNull
public static AndroidKeyStorePublicKey getAndroidKeyStorePublicKey(@NonNull String alias, int uid, @NonNull @KeyProperties.KeyAlgorithmEnum String keyAlgorithm, @NonNull byte[] x509EncodedForm) {
    PublicKey publicKey;
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
        publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(x509EncodedForm));
    } catch (NoSuchAlgorithmException e) {
        throw new ProviderException("Failed to obtain " + keyAlgorithm + " KeyFactory", e);
    } catch (InvalidKeySpecException e) {
        throw new ProviderException("Invalid X.509 encoding of public key", e);
    }
    if (KeyProperties.KEY_ALGORITHM_EC.equalsIgnoreCase(keyAlgorithm)) {
        return new AndroidKeyStoreECPublicKey(alias, uid, (ECPublicKey) publicKey);
    } else if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(keyAlgorithm)) {
        return new AndroidKeyStoreRSAPublicKey(alias, uid, (RSAPublicKey) publicKey);
    } else {
        throw new ProviderException("Unsupported Android Keystore public key algorithm: " + keyAlgorithm);
    }
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) ProviderException(java.security.ProviderException) NoSuchProviderException(java.security.NoSuchProviderException) RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyFactory(java.security.KeyFactory) NonNull(android.annotation.NonNull)

Example 29 with InvalidKeySpecException

use of java.security.spec.InvalidKeySpecException in project GNS by MobilityFirst.

the class BasicGuidEntry method generatePublicKey.

private static PublicKey generatePublicKey(String encodedPublic) throws EncryptionException {
    byte[] encodedPublicKey = Base64.decode(encodedPublic);
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(GNSProtocol.RSA_ALGORITHM.toString());
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
        return keyFactory.generatePublic(publicKeySpec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new EncryptionException("Failed to generate keypair", e);
    }
}
Also used : EncryptionException(edu.umass.cs.gnscommon.exceptions.client.EncryptionException) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyFactory(java.security.KeyFactory)

Example 30 with InvalidKeySpecException

use of java.security.spec.InvalidKeySpecException in project GNS by MobilityFirst.

the class KeyPairUtils method getGuidEntry.

/**
   * Retrieves the public/private key pair for the given user.
   *
   * @param gnsName the name of the GNS instance (e.g. "server.gns.name:8080")
   * @param username the user name
   * @return the GNSProtocol.GUID.toString() entry if found, null otherwise
   */
public static GuidEntry getGuidEntry(String gnsName, String username) {
    if (username == null) {
        return null;
    }
    if (IS_ANDROID) {
        return KeyPairUtilsAndroid.getGuidEntryFromPreferences(gnsName, username);
    }
    createSingleton();
    String guid = keyStorageObj.get(generateKey(gnsName, username, GUID), "");
    String publicString = keyStorageObj.get(generateKey(gnsName, username, PUBLIC), "");
    String privateString = keyStorageObj.get(generateKey(gnsName, username, PRIVATE), "");
    if (!guid.isEmpty() && !publicString.isEmpty() && !privateString.isEmpty()) {
        try {
            byte[] encodedPublicKey = DatatypeConverter.parseHexBinary(publicString);
            //byte[] encodedPublicKey = ByteUtils.hexStringToByteArray(publicString);
            byte[] encodedPrivateKey = DatatypeConverter.parseHexBinary(privateString);
            //byte[] encodedPrivateKey = ByteUtils.hexStringToByteArray(privateString);
            KeyFactory keyFactory = KeyFactory.getInstance(GNSProtocol.RSA_ALGORITHM.toString());
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
            PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
            PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
            return new GuidEntry(username, guid, publicKey, privateKey);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException | EncryptionException e) {
            System.out.println(e.toString());
            return null;
        }
    } else {
        return null;
    }
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) EncryptionException(edu.umass.cs.gnscommon.exceptions.client.EncryptionException) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyFactory(java.security.KeyFactory)

Aggregations

InvalidKeySpecException (java.security.spec.InvalidKeySpecException)483 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)306 KeyFactory (java.security.KeyFactory)199 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)155 InvalidKeyException (java.security.InvalidKeyException)116 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)108 IOException (java.io.IOException)98 PublicKey (java.security.PublicKey)90 PrivateKey (java.security.PrivateKey)77 SecretKeyFactory (javax.crypto.SecretKeyFactory)66 PBEKeySpec (javax.crypto.spec.PBEKeySpec)59 BigInteger (java.math.BigInteger)45 SignatureException (java.security.SignatureException)39 SecretKey (javax.crypto.SecretKey)38 BadPaddingException (javax.crypto.BadPaddingException)36 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)36 RSAPublicKeySpec (java.security.spec.RSAPublicKeySpec)35 NoSuchProviderException (java.security.NoSuchProviderException)34 KeySpec (java.security.spec.KeySpec)32 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)30