Search in sources :

Example 1 with X509EncodedKeySpec

use of java.security.spec.X509EncodedKeySpec in project OpenAttestation by OpenAttestation.

the class X509Util method decodeDerPublicKey.

public static PublicKey decodeDerPublicKey(byte[] publicKeyBytes) throws CryptographyException {
    try {
        // throws NoSuchAlgorithmException
        KeyFactory factory = KeyFactory.getInstance("RSA");
        // throws InvalidKeySpecException
        PublicKey publicKey = factory.generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        return publicKey;
    } catch (Exception e) {
        throw new CryptographyException(e);
    }
}
Also used : PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) KeyFactory(java.security.KeyFactory) CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 2 with X509EncodedKeySpec

use of java.security.spec.X509EncodedKeySpec in project android_frameworks_base by ParanoidAndroid.

the class PackageParser method parseVerifier.

private static VerifierInfo parseVerifier(Resources res, XmlPullParser parser, AttributeSet attrs, int flags, String[] outError) throws XmlPullParserException, IOException {
    final TypedArray sa = res.obtainAttributes(attrs, com.android.internal.R.styleable.AndroidManifestPackageVerifier);
    final String packageName = sa.getNonResourceString(com.android.internal.R.styleable.AndroidManifestPackageVerifier_name);
    final String encodedPublicKey = sa.getNonResourceString(com.android.internal.R.styleable.AndroidManifestPackageVerifier_publicKey);
    sa.recycle();
    if (packageName == null || packageName.length() == 0) {
        Slog.i(TAG, "verifier package name was null; skipping");
        return null;
    } else if (encodedPublicKey == null) {
        Slog.i(TAG, "verifier " + packageName + " public key was null; skipping");
    }
    EncodedKeySpec keySpec;
    try {
        final byte[] encoded = Base64.decode(encodedPublicKey, Base64.DEFAULT);
        keySpec = new X509EncodedKeySpec(encoded);
    } catch (IllegalArgumentException e) {
        Slog.i(TAG, "Could not parse verifier " + packageName + " public key; invalid Base64");
        return null;
    }
    /* First try the key as an RSA key. */
    try {
        final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        final PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return new VerifierInfo(packageName, publicKey);
    } catch (NoSuchAlgorithmException e) {
        Log.wtf(TAG, "Could not parse public key because RSA isn't included in build");
        return null;
    } catch (InvalidKeySpecException e) {
    // Not a RSA public key.
    }
    /* Now try it as a DSA key. */
    try {
        final KeyFactory keyFactory = KeyFactory.getInstance("DSA");
        final PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return new VerifierInfo(packageName, publicKey);
    } catch (NoSuchAlgorithmException e) {
        Log.wtf(TAG, "Could not parse public key because DSA isn't included in build");
        return null;
    } catch (InvalidKeySpecException e) {
    // Not a DSA public key.
    }
    return null;
}
Also used : PublicKey(java.security.PublicKey) TypedArray(android.content.res.TypedArray) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyFactory(java.security.KeyFactory) EncodedKeySpec(java.security.spec.EncodedKeySpec) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec)

Example 3 with X509EncodedKeySpec

use of java.security.spec.X509EncodedKeySpec in project XobotOS by xamarin.

the class JDKKeyStore method decodeKey.

private Key decodeKey(DataInputStream dIn) throws IOException {
    int keyType = dIn.read();
    String format = dIn.readUTF();
    String algorithm = dIn.readUTF();
    byte[] enc = new byte[dIn.readInt()];
    KeySpec spec;
    dIn.readFully(enc);
    if (format.equals("PKCS#8") || format.equals("PKCS8")) {
        spec = new PKCS8EncodedKeySpec(enc);
    } else if (format.equals("X.509") || format.equals("X509")) {
        spec = new X509EncodedKeySpec(enc);
    } else if (format.equals("RAW")) {
        return new SecretKeySpec(enc, algorithm);
    } else {
        throw new IOException("Key format " + format + " not recognised!");
    }
    try {
        switch(keyType) {
            case KEY_PRIVATE:
                return KeyFactory.getInstance(algorithm, BouncyCastleProvider.PROVIDER_NAME).generatePrivate(spec);
            case KEY_PUBLIC:
                return KeyFactory.getInstance(algorithm, BouncyCastleProvider.PROVIDER_NAME).generatePublic(spec);
            case KEY_SECRET:
                return SecretKeyFactory.getInstance(algorithm, BouncyCastleProvider.PROVIDER_NAME).generateSecret(spec);
            default:
                throw new IOException("Key type " + keyType + " not recognised!");
        }
    } catch (Exception e) {
        throw new IOException("Exception creating key: " + e.toString());
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) SecretKeySpec(javax.crypto.spec.SecretKeySpec) KeySpec(java.security.spec.KeySpec) PBEKeySpec(javax.crypto.spec.PBEKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 4 with X509EncodedKeySpec

use of java.security.spec.X509EncodedKeySpec in project OpenAM by OpenRock.

the class PEMDecoder method decodeRSAPublicKey.

/**
     * Decodes a PEM encoded Public Key.
     *
     * @param encodedKey The Base64 encoded public key bytes.
     * @return The decoded Public Key.
     * @throws NoSuchAlgorithmException If the key cannot be decoded.
     * @throws InvalidKeySpecException If the key cannot be decoded.
     */
public RSAPublicKey decodeRSAPublicKey(String encodedKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
    if (encodedKey == null) {
        return null;
    }
    encodedKey = encodedKey.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "").trim();
    byte[] decodedKey = Base64.decode(encodedKey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
    return (RSAPublicKey) keyFactory.generatePublic(keySpec);
}
Also used : RSAPublicKey(java.security.interfaces.RSAPublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) KeyFactory(java.security.KeyFactory)

Example 5 with X509EncodedKeySpec

use of java.security.spec.X509EncodedKeySpec in project android_frameworks_base by ResurrectionRemix.

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)

Aggregations

X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)343 KeyFactory (java.security.KeyFactory)228 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)154 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)142 PublicKey (java.security.PublicKey)129 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)82 PrivateKey (java.security.PrivateKey)50 RSAPublicKey (java.security.interfaces.RSAPublicKey)48 IOException (java.io.IOException)39 InvalidKeyException (java.security.InvalidKeyException)37 KeyPair (java.security.KeyPair)30 Cipher (javax.crypto.Cipher)26 Signature (java.security.Signature)25 EncodedKeySpec (java.security.spec.EncodedKeySpec)21 NoSuchProviderException (java.security.NoSuchProviderException)14 ECPublicKey (java.security.interfaces.ECPublicKey)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 SecretKey (javax.crypto.SecretKey)13 BigInteger (java.math.BigInteger)12 Key (java.security.Key)12