Search in sources :

Example 76 with KeyGenerator

use of javax.crypto.KeyGenerator in project Corgi by kevinYin.

the class AES method getRawKey.

/**
 * 获取128位的加密密钥
 *
 * @param seed
 * @return
 * @throws Exception
 */
private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(seed);
    // 256 bits or 128 bits,192bits
    kgen.init(128, sr);
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    return raw;
}
Also used : SecretKey(javax.crypto.SecretKey) SecureRandom(java.security.SecureRandom) KeyGenerator(javax.crypto.KeyGenerator)

Example 77 with KeyGenerator

use of javax.crypto.KeyGenerator in project MTweaks-KernelAdiutorMOD by morogoku.

the class SecurityActivity method loadFingerprint.

private void loadFingerprint() {
    try {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
        mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
        keyStore.load(null);
        keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT).setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build());
        keyGenerator.generateKey();
        SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
        mCipher.init(Cipher.ENCRYPT_MODE, key);
    } catch (KeyStoreException | NoSuchProviderException | NoSuchAlgorithmException | NoSuchPaddingException | UnrecoverableKeyException | InvalidKeyException | CertificateException | InvalidAlgorithmParameterException | IOException e) {
        return;
    }
    mCryptoObject = new FingerprintManagerCompat.CryptoObject(mCipher);
    FrameLayout fingerprintParent = (FrameLayout) findViewById(R.id.fingerprint_parent);
    final SwirlView swirlView = new SwirlView(new ContextThemeWrapper(this, R.style.Swirl));
    swirlView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    fingerprintParent.addView(swirlView);
    fingerprintParent.setVisibility(View.VISIBLE);
    mFingerprintUiHelper = new FingerprintUiHelper.FingerprintUiHelperBuilder(mFingerprintManagerCompat).build(swirlView, new FingerprintUiHelper.Callback() {

        @Override
        public void onAuthenticated() {
            try {
                mCipher.doFinal(SECRET_MESSAGE.getBytes());
                mPasswordWrong.setVisibility(View.GONE);
                setResult(1);
                finish();
            } catch (IllegalBlockSizeException | BadPaddingException e) {
                e.printStackTrace();
                swirlView.setState(SwirlView.State.ERROR);
            }
        }

        @Override
        public void onError() {
        }
    });
    mFingerprintUiHelper.startListening(mCryptoObject);
}
Also used : FingerprintManagerCompat(android.support.v4.hardware.fingerprint.FingerprintManagerCompat) SwirlView(com.mattprecious.swirl.SwirlView) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) KeyGenerator(javax.crypto.KeyGenerator) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) KeyGenParameterSpec(android.security.keystore.KeyGenParameterSpec) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) KeyStore(java.security.KeyStore) SecretKey(javax.crypto.SecretKey) ContextThemeWrapper(android.support.v7.view.ContextThemeWrapper) FrameLayout(android.widget.FrameLayout) NoSuchProviderException(java.security.NoSuchProviderException)

Example 78 with KeyGenerator

use of javax.crypto.KeyGenerator in project data-transfer-project by google.

the class SecretKeyGenerator method generateKeyAndEncode.

/**
 * Generate a new symmetric key to use throughout the life of a job session.
 */
public static String generateKeyAndEncode() {
    try {
        KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
        SecretKey key = generator.generateKey();
        return BaseEncoding.base64Url().encode(key.getEncoded());
    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException for: {}", ALGORITHM, e);
        throw new RuntimeException("Error creating key generator", e);
    }
}
Also used : SecretKey(javax.crypto.SecretKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyGenerator(javax.crypto.KeyGenerator)

Example 79 with KeyGenerator

use of javax.crypto.KeyGenerator in project AmazeFileManager by TeamAmaze.

the class CryptUtil method getSecretKey.

/**
 * Gets a secret key from Android key store.
 * If no key has been generated with a given alias then generate a new one
 * @return
 * @throws KeyStoreException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws NoSuchProviderException
 * @throws InvalidAlgorithmParameterException
 * @throws UnrecoverableKeyException
 */
@RequiresApi(api = Build.VERSION_CODES.M)
private static Key getSecretKey() throws GeneralSecurityException, IOException {
    KeyStore keyStore = KeyStore.getInstance(KEY_STORE_ANDROID);
    keyStore.load(null);
    if (!keyStore.containsAlias(KEY_ALIAS_AMAZE)) {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEY_STORE_ANDROID);
        KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(KEY_ALIAS_AMAZE, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT);
        builder.setBlockModes(KeyProperties.BLOCK_MODE_GCM);
        builder.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE);
        builder.setRandomizedEncryptionRequired(false);
        keyGenerator.init(builder.build());
        return keyGenerator.generateKey();
    } else {
        return keyStore.getKey(KEY_ALIAS_AMAZE, null);
    }
}
Also used : KeyGenParameterSpec(android.security.keystore.KeyGenParameterSpec) KeyStore(java.security.KeyStore) KeyGenerator(javax.crypto.KeyGenerator) RequiresApi(android.support.annotation.RequiresApi)

Example 80 with KeyGenerator

use of javax.crypto.KeyGenerator in project pdfbox by apache.

the class PublicKeySecurityHandler method prepareDocumentForEncryption.

/**
 * Prepare the document for encryption.
 *
 * @param doc The document that will be encrypted.
 *
 * @throws IOException If there is an error while encrypting.
 */
@Override
public void prepareDocumentForEncryption(PDDocument doc) throws IOException {
    if (keyLength == 256) {
        throw new IOException("256 bit key length is not supported yet for public key security");
    }
    try {
        PDEncryption dictionary = doc.getEncryption();
        if (dictionary == null) {
            dictionary = new PDEncryption();
        }
        dictionary.setFilter(FILTER);
        dictionary.setLength(this.keyLength);
        dictionary.setVersion(2);
        // remove CF, StmF, and StrF entries that may be left from a previous encryption
        dictionary.removeV45filters();
        dictionary.setSubFilter(SUBFILTER);
        // create the 20 bytes seed
        byte[] seed = new byte[20];
        KeyGenerator key;
        try {
            key = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            // should never happen
            throw new RuntimeException(e);
        }
        key.init(192, new SecureRandom());
        SecretKey sk = key.generateKey();
        // create the 20 bytes seed
        System.arraycopy(sk.getEncoded(), 0, seed, 0, 20);
        byte[][] recipientsField = computeRecipientsField(seed);
        dictionary.setRecipients(recipientsField);
        int sha1InputLength = seed.length;
        for (int j = 0; j < dictionary.getRecipientsLength(); j++) {
            COSString string = dictionary.getRecipientStringAt(j);
            sha1InputLength += string.getBytes().length;
        }
        byte[] sha1Input = new byte[sha1InputLength];
        System.arraycopy(seed, 0, sha1Input, 0, 20);
        int sha1InputOffset = 20;
        for (int j = 0; j < dictionary.getRecipientsLength(); j++) {
            COSString string = dictionary.getRecipientStringAt(j);
            System.arraycopy(string.getBytes(), 0, sha1Input, sha1InputOffset, string.getBytes().length);
            sha1InputOffset += string.getBytes().length;
        }
        MessageDigest sha1 = MessageDigests.getSHA1();
        byte[] mdResult = sha1.digest(sha1Input);
        this.encryptionKey = new byte[this.keyLength / 8];
        System.arraycopy(mdResult, 0, this.encryptionKey, 0, this.keyLength / 8);
        doc.setEncryptionDictionary(dictionary);
        doc.getDocument().setEncryptionDictionary(dictionary.getCOSDictionary());
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecretKey(javax.crypto.SecretKey) MessageDigest(java.security.MessageDigest) KeyGenerator(javax.crypto.KeyGenerator) COSString(org.apache.pdfbox.cos.COSString)

Aggregations

KeyGenerator (javax.crypto.KeyGenerator)464 SecretKey (javax.crypto.SecretKey)343 Test (org.junit.Test)106 ArrayList (java.util.ArrayList)104 SecureRandom (java.security.SecureRandom)99 Document (org.w3c.dom.Document)98 InputStream (java.io.InputStream)95 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)93 ByteArrayOutputStream (java.io.ByteArrayOutputStream)87 NodeList (org.w3c.dom.NodeList)82 Cipher (javax.crypto.Cipher)79 ByteArrayInputStream (java.io.ByteArrayInputStream)75 XMLStreamReader (javax.xml.stream.XMLStreamReader)68 XMLSecurityProperties (org.apache.xml.security.stax.ext.XMLSecurityProperties)68 DocumentBuilder (javax.xml.parsers.DocumentBuilder)62 Key (java.security.Key)58 QName (javax.xml.namespace.QName)47 IOException (java.io.IOException)45 SecurePart (org.apache.xml.security.stax.ext.SecurePart)40 SecretKeySpec (javax.crypto.spec.SecretKeySpec)39