Search in sources :

Example 41 with AlgorithmParameters

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

the class RC2AlgorithmParameters method main.

public static void main(String[] args) throws Exception {
    byte[] iv_1 = { (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x33, (byte) 0x33 };
    // check that RC2 is supported by our provider
    AlgorithmParameters rc2Params = AlgorithmParameters.getInstance("RC2", "SunJCE");
    // check that getAlgorithm returns "RC2"
    if (!rc2Params.getAlgorithm().equals("RC2")) {
        throw new Exception("getAlgorithm() returned " + rc2Params.getAlgorithm() + " instead of RC2");
    }
    // test parameters with effective key size and iv
    byte[] encoded = testParams(rc2Params, new RC2ParameterSpec(2, iv_1));
    // test parameters with just iv
    encoded = testParams(AlgorithmParameters.getInstance("RC2"), new RC2ParameterSpec(0, iv_1));
    // test vectors in RFC 2268
    runTests(tests);
}
Also used : RC2ParameterSpec(javax.crypto.spec.RC2ParameterSpec) IOException(java.io.IOException) AlgorithmParameters(java.security.AlgorithmParameters)

Example 42 with AlgorithmParameters

use of java.security.AlgorithmParameters in project android_frameworks_base by AOSPA.

the class AndroidKeyStoreUnauthenticatedAESCipherSpi method engineGetParameters.

@Nullable
@Override
protected final AlgorithmParameters engineGetParameters() {
    if (!mIvRequired) {
        return null;
    }
    if ((mIv != null) && (mIv.length > 0)) {
        try {
            AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
            params.init(new IvParameterSpec(mIv));
            return params;
        } catch (NoSuchAlgorithmException e) {
            throw new ProviderException("Failed to obtain AES AlgorithmParameters", e);
        } catch (InvalidParameterSpecException e) {
            throw new ProviderException("Failed to initialize AES AlgorithmParameters with an IV", e);
        }
    }
    return null;
}
Also used : ProviderException(java.security.ProviderException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidParameterSpecException(java.security.spec.InvalidParameterSpecException) AlgorithmParameters(java.security.AlgorithmParameters) Nullable(android.annotation.Nullable)

Example 43 with AlgorithmParameters

use of java.security.AlgorithmParameters in project android_frameworks_base by ResurrectionRemix.

the class ESTHandler method buildCSR.

private byte[] buildCSR(ByteBuffer octetBuffer, OMADMAdapter omadmAdapter, HTTPHandler httpHandler) throws IOException, GeneralSecurityException {
    //Security.addProvider(new BouncyCastleProvider());
    Log.d(TAG, "/csrattrs:");
    /*
        byte[] octets = new byte[octetBuffer.remaining()];
        octetBuffer.duplicate().get(octets);
        for (byte b : octets) {
            System.out.printf("%02x ", b & 0xff);
        }
        */
    Collection<Asn1Object> csrs = Asn1Decoder.decode(octetBuffer);
    for (Asn1Object asn1Object : csrs) {
        Log.d(TAG, asn1Object.toString());
    }
    if (csrs.size() != 1) {
        throw new IOException("Unexpected object count in CSR attributes response: " + csrs.size());
    }
    Asn1Object sequence = csrs.iterator().next();
    if (sequence.getClass() != Asn1Constructed.class) {
        throw new IOException("Unexpected CSR attribute container: " + sequence);
    }
    String keyAlgo = null;
    Asn1Oid keyAlgoOID = null;
    String sigAlgo = null;
    String curveName = null;
    Asn1Oid pubCrypto = null;
    int keySize = -1;
    Map<Asn1Oid, ASN1Encodable> idAttributes = new HashMap<>();
    for (Asn1Object child : sequence.getChildren()) {
        if (child.getTag() == Asn1Decoder.TAG_OID) {
            Asn1Oid oid = (Asn1Oid) child;
            OidMappings.SigEntry sigEntry = OidMappings.getSigEntry(oid);
            if (sigEntry != null) {
                sigAlgo = sigEntry.getSigAlgo();
                keyAlgoOID = sigEntry.getKeyAlgo();
                keyAlgo = OidMappings.getJCEName(keyAlgoOID);
            } else if (oid.equals(OidMappings.sPkcs9AtChallengePassword)) {
                byte[] tlsUnique = httpHandler.getTLSUnique();
                if (tlsUnique != null) {
                    idAttributes.put(oid, new DERPrintableString(Base64.encodeToString(tlsUnique, Base64.DEFAULT)));
                } else {
                    Log.w(TAG, "Cannot retrieve TLS unique channel binding");
                }
            }
        } else if (child.getTag() == Asn1Decoder.TAG_SEQ) {
            Asn1Oid oid = null;
            Set<Asn1Oid> oidValues = new HashSet<>();
            List<Asn1Object> values = new ArrayList<>();
            for (Asn1Object attributeSeq : child.getChildren()) {
                if (attributeSeq.getTag() == Asn1Decoder.TAG_OID) {
                    oid = (Asn1Oid) attributeSeq;
                } else if (attributeSeq.getTag() == Asn1Decoder.TAG_SET) {
                    for (Asn1Object value : attributeSeq.getChildren()) {
                        if (value.getTag() == Asn1Decoder.TAG_OID) {
                            oidValues.add((Asn1Oid) value);
                        } else {
                            values.add(value);
                        }
                    }
                }
            }
            if (oid == null) {
                throw new IOException("Invalid attribute, no OID");
            }
            if (oid.equals(OidMappings.sExtensionRequest)) {
                for (Asn1Oid subOid : oidValues) {
                    if (OidMappings.isIDAttribute(subOid)) {
                        if (subOid.equals(OidMappings.sMAC)) {
                            idAttributes.put(subOid, new DERIA5String(omadmAdapter.getMAC()));
                        } else if (subOid.equals(OidMappings.sIMEI)) {
                            idAttributes.put(subOid, new DERIA5String(omadmAdapter.getImei()));
                        } else if (subOid.equals(OidMappings.sMEID)) {
                            idAttributes.put(subOid, new DERBitString(omadmAdapter.getMeid()));
                        } else if (subOid.equals(OidMappings.sDevID)) {
                            idAttributes.put(subOid, new DERPrintableString(omadmAdapter.getDevID()));
                        }
                    }
                }
            } else if (OidMappings.getCryptoID(oid) != null) {
                pubCrypto = oid;
                if (!values.isEmpty()) {
                    for (Asn1Object value : values) {
                        if (value.getTag() == Asn1Decoder.TAG_INTEGER) {
                            keySize = (int) ((Asn1Integer) value).getValue();
                        }
                    }
                }
                if (oid.equals(OidMappings.sAlgo_EC)) {
                    if (oidValues.isEmpty()) {
                        throw new IOException("No ECC curve name provided");
                    }
                    for (Asn1Oid value : oidValues) {
                        curveName = OidMappings.getJCEName(value);
                        if (curveName != null) {
                            break;
                        }
                    }
                    if (curveName == null) {
                        throw new IOException("Found no ECC curve for " + oidValues);
                    }
                }
            }
        }
    }
    if (keyAlgoOID == null) {
        throw new IOException("No public key algorithm specified");
    }
    if (pubCrypto != null && !pubCrypto.equals(keyAlgoOID)) {
        throw new IOException("Mismatching key algorithms");
    }
    if (keyAlgoOID.equals(OidMappings.sAlgo_RSA)) {
        if (keySize < MinRSAKeySize) {
            if (keySize >= 0) {
                Log.i(TAG, "Upgrading suggested RSA key size from " + keySize + " to " + MinRSAKeySize);
            }
            keySize = MinRSAKeySize;
        }
    }
    Log.d(TAG, String.format("pub key '%s', signature '%s', ECC curve '%s', id-atts %s", keyAlgo, sigAlgo, curveName, idAttributes));
    /*
          Ruckus:
            SEQUENCE:
              OID=1.2.840.113549.1.1.11 (algo_id_sha256WithRSAEncryption)

          RFC-7030:
            SEQUENCE:
              OID=1.2.840.113549.1.9.7 (challengePassword)
              SEQUENCE:
                OID=1.2.840.10045.2.1 (algo_id_ecPublicKey)
                SET:
                  OID=1.3.132.0.34 (secp384r1)
              SEQUENCE:
                OID=1.2.840.113549.1.9.14 (extensionRequest)
                SET:
                  OID=1.3.6.1.1.1.1.22 (mac-address)
              OID=1.2.840.10045.4.3.3 (eccdaWithSHA384)

              1L, 3L, 6L, 1L, 1L, 1L, 1L, 22
         */
    // ECC Does not appear to be supported currently
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgo);
    if (curveName != null) {
        AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(keyAlgo);
        algorithmParameters.init(new ECNamedCurveGenParameterSpec(curveName));
        kpg.initialize(algorithmParameters.getParameterSpec(ECNamedCurveGenParameterSpec.class));
    } else {
        kpg.initialize(keySize);
    }
    KeyPair kp = kpg.generateKeyPair();
    X500Principal subject = new X500Principal("CN=Android, O=Google, C=US");
    mClientKey = kp.getPrivate();
    // !!! Map the idAttributes into an ASN1Set of values to pass to
    // the PKCS10CertificationRequest - this code is using outdated BC classes and
    // has *not* been tested.
    ASN1Set attributes;
    if (!idAttributes.isEmpty()) {
        ASN1EncodableVector payload = new DEREncodableVector();
        for (Map.Entry<Asn1Oid, ASN1Encodable> entry : idAttributes.entrySet()) {
            DERObjectIdentifier type = new DERObjectIdentifier(entry.getKey().toOIDString());
            ASN1Set values = new DERSet(entry.getValue());
            Attribute attribute = new Attribute(type, values);
            payload.add(attribute);
        }
        attributes = new DERSet(payload);
    } else {
        attributes = null;
    }
    return new PKCS10CertificationRequest(sigAlgo, subject, kp.getPublic(), attributes, mClientKey).getEncoded();
}
Also used : DERSet(com.android.org.bouncycastle.asn1.DERSet) ASN1Set(com.android.org.bouncycastle.asn1.ASN1Set) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) Attribute(com.android.org.bouncycastle.asn1.x509.Attribute) DERBitString(com.android.org.bouncycastle.asn1.DERBitString) DERPrintableString(com.android.org.bouncycastle.asn1.DERPrintableString) DERIA5String(com.android.org.bouncycastle.asn1.DERIA5String) DERSet(com.android.org.bouncycastle.asn1.DERSet) DERIA5String(com.android.org.bouncycastle.asn1.DERIA5String) Asn1Integer(com.android.hotspot2.asn1.Asn1Integer) DERPrintableString(com.android.org.bouncycastle.asn1.DERPrintableString) ASN1EncodableVector(com.android.org.bouncycastle.asn1.ASN1EncodableVector) List(java.util.List) ArrayList(java.util.ArrayList) ASN1Encodable(com.android.org.bouncycastle.asn1.ASN1Encodable) PKCS10CertificationRequest(com.android.org.bouncycastle.jce.PKCS10CertificationRequest) Asn1Oid(com.android.hotspot2.asn1.Asn1Oid) KeyPair(java.security.KeyPair) ECNamedCurveGenParameterSpec(com.android.org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec) DEREncodableVector(com.android.org.bouncycastle.asn1.DEREncodableVector) DERBitString(com.android.org.bouncycastle.asn1.DERBitString) IOException(java.io.IOException) KeyPairGenerator(java.security.KeyPairGenerator) DERObjectIdentifier(com.android.org.bouncycastle.asn1.DERObjectIdentifier) Asn1Object(com.android.hotspot2.asn1.Asn1Object) OidMappings(com.android.hotspot2.asn1.OidMappings) ASN1Set(com.android.org.bouncycastle.asn1.ASN1Set) X500Principal(javax.security.auth.x500.X500Principal) Map(java.util.Map) HashMap(java.util.HashMap) AlgorithmParameters(java.security.AlgorithmParameters)

Example 44 with AlgorithmParameters

use of java.security.AlgorithmParameters in project oxAuth by GluuFederation.

the class AbstractCryptoProvider method getPublicKey.

public PublicKey getPublicKey(String alias, JSONObject jwks) throws Exception {
    java.security.PublicKey publicKey = null;
    JSONArray webKeys = jwks.getJSONArray(JSON_WEB_KEY_SET);
    for (int i = 0; i < webKeys.length(); i++) {
        JSONObject key = webKeys.getJSONObject(i);
        if (alias.equals(key.getString(KEY_ID))) {
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(key.getString(ALGORITHM));
            if (signatureAlgorithm != null) {
                if (signatureAlgorithm.getFamily().equals(SignatureAlgorithmFamily.RSA)) {
                    publicKey = new RSAPublicKeyImpl(new BigInteger(1, Base64Util.base64urldecode(key.getString(MODULUS))), new BigInteger(1, Base64Util.base64urldecode(key.getString(EXPONENT))));
                } else if (signatureAlgorithm.getFamily().equals(SignatureAlgorithmFamily.EC)) {
                    AlgorithmParameters parameters = AlgorithmParameters.getInstance(SignatureAlgorithmFamily.EC);
                    parameters.init(new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias()));
                    ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);
                    publicKey = KeyFactory.getInstance(SignatureAlgorithmFamily.EC).generatePublic(new ECPublicKeySpec(new ECPoint(new BigInteger(1, Base64Util.base64urldecode(key.getString(X))), new BigInteger(1, Base64Util.base64urldecode(key.getString(Y)))), ecParameters));
                }
            }
        }
    }
    return publicKey;
}
Also used : RSAPublicKeyImpl(sun.security.rsa.RSAPublicKeyImpl) JSONArray(org.codehaus.jettison.json.JSONArray) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) PublicKey(java.security.PublicKey) SignatureAlgorithm(org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm) ECPoint(java.security.spec.ECPoint) ECPoint(java.security.spec.ECPoint) ECPublicKeySpec(java.security.spec.ECPublicKeySpec) JSONObject(org.codehaus.jettison.json.JSONObject) ECParameterSpec(java.security.spec.ECParameterSpec) BigInteger(java.math.BigInteger) AlgorithmParameters(java.security.AlgorithmParameters)

Example 45 with AlgorithmParameters

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

the class PKCS12KeyStore method engineLoad.

/**
     * Loads the keystore from the given input stream.
     *
     * <p>If a password is given, it is used to check the integrity of the
     * keystore data. Otherwise, the integrity of the keystore is not checked.
     *
     * @param stream the input stream from which the keystore is loaded
     * @param password the (optional) password used to check the integrity of
     * the keystore.
     *
     * @exception IOException if there is an I/O or format problem with the
     * keystore data
     * @exception NoSuchAlgorithmException if the algorithm used to check
     * the integrity of the keystore cannot be found
     * @exception CertificateException if any of the certificates in the
     * keystore could not be loaded
     */
public synchronized void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
    DataInputStream dis;
    CertificateFactory cf = null;
    ByteArrayInputStream bais = null;
    byte[] encoded = null;
    if (stream == null)
        return;
    // reset the counter
    counter = 0;
    DerValue val = new DerValue(stream);
    DerInputStream s = val.toDerInputStream();
    int version = s.getInteger();
    if (version != VERSION_3) {
        throw new IOException("PKCS12 keystore not in version 3 format");
    }
    entries.clear();
    /*
         * Read the authSafe.
         */
    byte[] authSafeData;
    ContentInfo authSafe = new ContentInfo(s);
    ObjectIdentifier contentType = authSafe.getContentType();
    if (contentType.equals((Object) ContentInfo.DATA_OID)) {
        authSafeData = authSafe.getData();
    } else /* signed data */
    {
        throw new IOException("public key protected PKCS12 not supported");
    }
    DerInputStream as = new DerInputStream(authSafeData);
    DerValue[] safeContentsArray = as.getSequence(2);
    int count = safeContentsArray.length;
    // reset the counters at the start
    privateKeyCount = 0;
    secretKeyCount = 0;
    certificateCount = 0;
    /*
         * Spin over the ContentInfos.
         */
    for (int i = 0; i < count; i++) {
        byte[] safeContentsData;
        ContentInfo safeContents;
        DerInputStream sci;
        byte[] eAlgId = null;
        sci = new DerInputStream(safeContentsArray[i].toByteArray());
        safeContents = new ContentInfo(sci);
        contentType = safeContents.getContentType();
        safeContentsData = null;
        if (contentType.equals((Object) ContentInfo.DATA_OID)) {
            if (debug != null) {
                debug.println("Loading PKCS#7 data content-type");
            }
            safeContentsData = safeContents.getData();
        } else if (contentType.equals((Object) ContentInfo.ENCRYPTED_DATA_OID)) {
            if (password == null) {
                if (debug != null) {
                    debug.println("Warning: skipping PKCS#7 encryptedData" + " content-type - no password was supplied");
                }
                continue;
            }
            if (debug != null) {
                debug.println("Loading PKCS#7 encryptedData content-type");
            }
            DerInputStream edi = safeContents.getContent().toDerInputStream();
            int edVersion = edi.getInteger();
            DerValue[] seq = edi.getSequence(2);
            ObjectIdentifier edContentType = seq[0].getOID();
            eAlgId = seq[1].toByteArray();
            if (!seq[2].isContextSpecific((byte) 0)) {
                throw new IOException("encrypted content not present!");
            }
            byte newTag = DerValue.tag_OctetString;
            if (seq[2].isConstructed())
                newTag |= 0x20;
            seq[2].resetTag(newTag);
            safeContentsData = seq[2].getOctetString();
            // parse Algorithm parameters
            DerInputStream in = seq[1].toDerInputStream();
            ObjectIdentifier algOid = in.getOID();
            AlgorithmParameters algParams = parseAlgParameters(algOid, in);
            while (true) {
                try {
                    // Use JCE
                    SecretKey skey = getPBEKey(password);
                    Cipher cipher = Cipher.getInstance(algOid.toString());
                    cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
                    safeContentsData = cipher.doFinal(safeContentsData);
                    break;
                } catch (Exception e) {
                    if (password.length == 0) {
                        // Retry using an empty password
                        // without a NULL terminator.
                        password = new char[1];
                        continue;
                    }
                    throw new IOException("keystore password was incorrect", new UnrecoverableKeyException("failed to decrypt safe contents entry: " + e));
                }
            }
        } else {
            throw new IOException("public key protected PKCS12" + " not supported");
        }
        DerInputStream sc = new DerInputStream(safeContentsData);
        loadSafeContents(sc, password);
    }
    // The MacData is optional.
    if (password != null && s.available() > 0) {
        MacData macData = new MacData(s);
        try {
            String algName = macData.getDigestAlgName().toUpperCase(Locale.ENGLISH);
            // Change SHA-1 to SHA1
            algName = algName.replace("-", "");
            // generate MAC (MAC key is created within JCE)
            Mac m = Mac.getInstance("HmacPBE" + algName);
            PBEParameterSpec params = new PBEParameterSpec(macData.getSalt(), macData.getIterations());
            SecretKey key = getPBEKey(password);
            m.init(key, params);
            m.update(authSafeData);
            byte[] macResult = m.doFinal();
            if (debug != null) {
                debug.println("Checking keystore integrity " + "(MAC algorithm: " + m.getAlgorithm() + ")");
            }
            if (!MessageDigest.isEqual(macData.getDigest(), macResult)) {
                throw new UnrecoverableKeyException("Failed PKCS12" + " integrity checking");
            }
        } catch (Exception e) {
            throw new IOException("Integrity check failed: " + e, e);
        }
    }
    /*
         * Match up private keys with certificate chains.
         */
    PrivateKeyEntry[] list = keyList.toArray(new PrivateKeyEntry[keyList.size()]);
    for (int m = 0; m < list.length; m++) {
        PrivateKeyEntry entry = list[m];
        if (entry.keyId != null) {
            ArrayList<X509Certificate> chain = new ArrayList<X509Certificate>();
            X509Certificate cert = findMatchedCertificate(entry);
            mainloop: while (cert != null) {
                // Check for loops in the certificate chain
                if (!chain.isEmpty()) {
                    for (X509Certificate chainCert : chain) {
                        if (cert.equals(chainCert)) {
                            if (debug != null) {
                                debug.println("Loop detected in " + "certificate chain. Skip adding " + "repeated cert to chain. Subject: " + cert.getSubjectX500Principal().toString());
                            }
                            break mainloop;
                        }
                    }
                }
                chain.add(cert);
                X500Principal issuerDN = cert.getIssuerX500Principal();
                if (issuerDN.equals(cert.getSubjectX500Principal())) {
                    break;
                }
                cert = certsMap.get(issuerDN);
            }
            /* Update existing KeyEntry in entries table */
            if (chain.size() > 0)
                entry.chain = chain.toArray(new Certificate[chain.size()]);
        }
    }
    if (debug != null) {
        if (privateKeyCount > 0) {
            debug.println("Loaded " + privateKeyCount + " protected private key(s)");
        }
        if (secretKeyCount > 0) {
            debug.println("Loaded " + secretKeyCount + " protected secret key(s)");
        }
        if (certificateCount > 0) {
            debug.println("Loaded " + certificateCount + " certificate(s)");
        }
    }
    certEntries.clear();
    certsMap.clear();
    keyList.clear();
}
Also used : CertificateFactory(java.security.cert.CertificateFactory) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ContentInfo(sun.security.pkcs.ContentInfo) DerValue(sun.security.util.DerValue) DerInputStream(sun.security.util.DerInputStream) PBEParameterSpec(javax.crypto.spec.PBEParameterSpec) ObjectIdentifier(sun.security.util.ObjectIdentifier) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) DestroyFailedException(javax.security.auth.DestroyFailedException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Mac(javax.crypto.Mac) X509Certificate(java.security.cert.X509Certificate) SecretKey(javax.crypto.SecretKey) X500Principal(javax.security.auth.x500.X500Principal) Cipher(javax.crypto.Cipher) AlgorithmParameters(java.security.AlgorithmParameters)

Aggregations

AlgorithmParameters (java.security.AlgorithmParameters)107 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)39 IOException (java.io.IOException)31 InvalidParameterSpecException (java.security.spec.InvalidParameterSpecException)22 Cipher (javax.crypto.Cipher)22 SecretKey (javax.crypto.SecretKey)18 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)13 NoSuchProviderException (java.security.NoSuchProviderException)12 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)11 Key (java.security.Key)11 SecureRandom (java.security.SecureRandom)10 EncryptedPrivateKeyInfo (javax.crypto.EncryptedPrivateKeyInfo)10 InvalidKeyException (java.security.InvalidKeyException)8 PBEParameterSpec (javax.crypto.spec.PBEParameterSpec)8 UnrecoverableKeyException (java.security.UnrecoverableKeyException)7 KeyPair (java.security.KeyPair)6 KeyPairGenerator (java.security.KeyPairGenerator)6 AlgorithmId (sun.security.x509.AlgorithmId)6 Nullable (android.annotation.Nullable)5 Asn1Integer (com.android.hotspot2.asn1.Asn1Integer)5