Search in sources :

Example 61 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project LuaViewSDK by alibaba.

the class DecryptUtil method aes.

/**
     * 使用aes256进行解密
     *
     * @param encrypted
     * @return
     */
public static byte[] aes(final byte[] keys, final byte[] encrypted) {
    try {
        //get cipher
        Cipher cipher = AppCache.getCache(CACHE_PUBLIC_KEY).get(Constants.PUBLIC_KEY_PATH_CIPHER);
        if (cipher == null) {
            final SecretKeySpec skeySpec = new SecretKeySpec(keys, ALGORITHM_AES);
            final IvParameterSpec ivParameterSpec = new IvParameterSpec(cIv);
            cipher = Cipher.getInstance(ALGORITHM_AES);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
            //cache cipher
            AppCache.getCache(CACHE_PUBLIC_KEY).put(Constants.PUBLIC_KEY_PATH_CIPHER, cipher);
        }
        return cipher.doFinal(encrypted);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 62 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project android_frameworks_base by ParanoidAndroid.

the class Pm method runInstall.

private void runInstall() {
    int installFlags = PackageManager.INSTALL_ALL_USERS;
    String installerPackageName = null;
    String opt;
    String algo = null;
    byte[] iv = null;
    byte[] key = null;
    String macAlgo = null;
    byte[] macKey = null;
    byte[] tag = null;
    String originatingUriString = null;
    String referrer = null;
    while ((opt = nextOption()) != null) {
        if (opt.equals("-l")) {
            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
        } else if (opt.equals("-r")) {
            installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
        } else if (opt.equals("-i")) {
            installerPackageName = nextOptionData();
            if (installerPackageName == null) {
                System.err.println("Error: no value specified for -i");
                return;
            }
        } else if (opt.equals("-t")) {
            installFlags |= PackageManager.INSTALL_ALLOW_TEST;
        } else if (opt.equals("-s")) {
            // Override if -s option is specified.
            installFlags |= PackageManager.INSTALL_EXTERNAL;
        } else if (opt.equals("-f")) {
            // Override if -s option is specified.
            installFlags |= PackageManager.INSTALL_INTERNAL;
        } else if (opt.equals("-d")) {
            installFlags |= PackageManager.INSTALL_ALLOW_DOWNGRADE;
        } else if (opt.equals("--algo")) {
            algo = nextOptionData();
            if (algo == null) {
                System.err.println("Error: must supply argument for --algo");
                return;
            }
        } else if (opt.equals("--iv")) {
            iv = hexToBytes(nextOptionData());
            if (iv == null) {
                System.err.println("Error: must supply argument for --iv");
                return;
            }
        } else if (opt.equals("--key")) {
            key = hexToBytes(nextOptionData());
            if (key == null) {
                System.err.println("Error: must supply argument for --key");
                return;
            }
        } else if (opt.equals("--macalgo")) {
            macAlgo = nextOptionData();
            if (macAlgo == null) {
                System.err.println("Error: must supply argument for --macalgo");
                return;
            }
        } else if (opt.equals("--mackey")) {
            macKey = hexToBytes(nextOptionData());
            if (macKey == null) {
                System.err.println("Error: must supply argument for --mackey");
                return;
            }
        } else if (opt.equals("--tag")) {
            tag = hexToBytes(nextOptionData());
            if (tag == null) {
                System.err.println("Error: must supply argument for --tag");
                return;
            }
        } else if (opt.equals("--originating-uri")) {
            originatingUriString = nextOptionData();
            if (originatingUriString == null) {
                System.err.println("Error: must supply argument for --originating-uri");
                return;
            }
        } else if (opt.equals("--referrer")) {
            referrer = nextOptionData();
            if (referrer == null) {
                System.err.println("Error: must supply argument for --referrer");
                return;
            }
        } else {
            System.err.println("Error: Unknown option: " + opt);
            return;
        }
    }
    final ContainerEncryptionParams encryptionParams;
    if (algo != null || iv != null || key != null || macAlgo != null || macKey != null || tag != null) {
        if (algo == null || iv == null || key == null) {
            System.err.println("Error: all of --algo, --iv, and --key must be specified");
            return;
        }
        if (macAlgo != null || macKey != null || tag != null) {
            if (macAlgo == null || macKey == null || tag == null) {
                System.err.println("Error: all of --macalgo, --mackey, and --tag must " + "be specified");
                return;
            }
        }
        try {
            final SecretKey encKey = new SecretKeySpec(key, "RAW");
            final SecretKey macSecretKey;
            if (macKey == null || macKey.length == 0) {
                macSecretKey = null;
            } else {
                macSecretKey = new SecretKeySpec(macKey, "RAW");
            }
            encryptionParams = new ContainerEncryptionParams(algo, new IvParameterSpec(iv), encKey, macAlgo, null, macSecretKey, tag, -1, -1, -1);
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            return;
        }
    } else {
        encryptionParams = null;
    }
    final Uri apkURI;
    final Uri verificationURI;
    final Uri originatingURI;
    final Uri referrerURI;
    if (originatingUriString != null) {
        originatingURI = Uri.parse(originatingUriString);
    } else {
        originatingURI = null;
    }
    if (referrer != null) {
        referrerURI = Uri.parse(referrer);
    } else {
        referrerURI = null;
    }
    // Populate apkURI, must be present
    final String apkFilePath = nextArg();
    System.err.println("\tpkg: " + apkFilePath);
    if (apkFilePath != null) {
        apkURI = Uri.fromFile(new File(apkFilePath));
    } else {
        System.err.println("Error: no package specified");
        return;
    }
    // Populate verificationURI, optionally present
    final String verificationFilePath = nextArg();
    if (verificationFilePath != null) {
        System.err.println("\tver: " + verificationFilePath);
        verificationURI = Uri.fromFile(new File(verificationFilePath));
    } else {
        verificationURI = null;
    }
    PackageInstallObserver obs = new PackageInstallObserver();
    try {
        VerificationParams verificationParams = new VerificationParams(verificationURI, originatingURI, referrerURI, VerificationParams.NO_UID, null);
        mPm.installPackageWithVerificationAndEncryption(apkURI, obs, installFlags, installerPackageName, verificationParams, encryptionParams);
        synchronized (obs) {
            while (!obs.finished) {
                try {
                    obs.wait();
                } catch (InterruptedException e) {
                }
            }
            if (obs.result == PackageManager.INSTALL_SUCCEEDED) {
                System.out.println("Success");
            } else {
                System.err.println("Failure [" + installFailureToString(obs.result) + "]");
            }
        }
    } catch (RemoteException e) {
        System.err.println(e.toString());
        System.err.println(PM_NOT_RUNNING_ERR);
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) ContainerEncryptionParams(android.content.pm.ContainerEncryptionParams) VerificationParams(android.content.pm.VerificationParams) Uri(android.net.Uri) SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) RemoteException(android.os.RemoteException) File(java.io.File) IPackageInstallObserver(android.content.pm.IPackageInstallObserver)

Example 63 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project android_frameworks_base by ParanoidAndroid.

the class AndroidKeyStoreTest method testKeyStore_KeyOperations_Wrap_Encrypted_Success.

public void testKeyStore_KeyOperations_Wrap_Encrypted_Success() throws Exception {
    setupPassword();
    mKeyStore.load(null, null);
    setupKey();
    // Test key usage
    Entry e = mKeyStore.getEntry(TEST_ALIAS_1, null);
    assertNotNull(e);
    assertTrue(e instanceof PrivateKeyEntry);
    PrivateKeyEntry privEntry = (PrivateKeyEntry) e;
    PrivateKey privKey = privEntry.getPrivateKey();
    assertNotNull(privKey);
    PublicKey pubKey = privEntry.getCertificate().getPublicKey();
    Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    c.init(Cipher.WRAP_MODE, pubKey);
    byte[] expectedKey = new byte[] { 0x00, 0x05, (byte) 0xAA, (byte) 0x0A5, (byte) 0xFF, 0x55, 0x0A };
    SecretKey expectedSecret = new SecretKeySpec(expectedKey, "AES");
    byte[] wrappedExpected = c.wrap(expectedSecret);
    c.init(Cipher.UNWRAP_MODE, privKey);
    SecretKey actualSecret = (SecretKey) c.unwrap(wrappedExpected, "AES", Cipher.SECRET_KEY);
    assertEquals(Arrays.toString(expectedSecret.getEncoded()), Arrays.toString(actualSecret.getEncoded()));
}
Also used : TrustedCertificateEntry(java.security.KeyStore.TrustedCertificateEntry) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry) Entry(java.security.KeyStore.Entry) SecretKey(javax.crypto.SecretKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Cipher(javax.crypto.Cipher) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry)

Example 64 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project android-pbe by nelenkov.

the class Crypto method deriveKeyPad.

// Illustration code only: don't use in production!
public static SecretKey deriveKeyPad(String password) {
    try {
        long start = System.currentTimeMillis();
        byte[] keyBytes = new byte[KEY_LENGTH / 8];
        // explicitly fill with zeros
        Arrays.fill(keyBytes, (byte) 0x0);
        // if password is shorter then key length, it will be zero-padded
        // to key length
        byte[] passwordBytes = password.getBytes("UTF-8");
        int length = passwordBytes.length < keyBytes.length ? passwordBytes.length : keyBytes.length;
        System.arraycopy(passwordBytes, 0, keyBytes, 0, length);
        SecretKey result = new SecretKeySpec(keyBytes, "AES");
        long elapsed = System.currentTimeMillis() - start;
        Log.d(TAG, String.format("Padding key derivation took %d [ms].", elapsed));
        return result;
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
Also used : SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 65 with SecretKeySpec

use of javax.crypto.spec.SecretKeySpec in project android-pbe by nelenkov.

the class Crypto method deriveKeyPbkdf2.

public static SecretKey deriveKeyPbkdf2(byte[] salt, String password) {
    try {
        long start = System.currentTimeMillis();
        KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, ITERATION_COUNT, KEY_LENGTH);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(PBKDF2_DERIVATION_ALGORITHM);
        byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
        Log.d(TAG, "key bytes: " + toHex(keyBytes));
        SecretKey result = new SecretKeySpec(keyBytes, "AES");
        long elapsed = System.currentTimeMillis() - start;
        Log.d(TAG, String.format("PBKDF2 key derivation took %d [ms].", elapsed));
        return result;
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) SecretKeySpec(javax.crypto.spec.SecretKeySpec) KeySpec(java.security.spec.KeySpec) PBEKeySpec(javax.crypto.spec.PBEKeySpec) GeneralSecurityException(java.security.GeneralSecurityException) SecretKeyFactory(javax.crypto.SecretKeyFactory)

Aggregations

SecretKeySpec (javax.crypto.spec.SecretKeySpec)498 Cipher (javax.crypto.Cipher)194 SecretKey (javax.crypto.SecretKey)142 Mac (javax.crypto.Mac)110 IvParameterSpec (javax.crypto.spec.IvParameterSpec)106 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)94 InvalidKeyException (java.security.InvalidKeyException)67 IOException (java.io.IOException)44 Key (java.security.Key)36 SecureRandom (java.security.SecureRandom)30 Test (org.junit.Test)30 UnsupportedEncodingException (java.io.UnsupportedEncodingException)29 GeneralSecurityException (java.security.GeneralSecurityException)27 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)27 MessageDigest (java.security.MessageDigest)25 BadPaddingException (javax.crypto.BadPaddingException)25 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)25 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)18 PrivateKey (java.security.PrivateKey)18 PublicKey (java.security.PublicKey)16