Example usage for javax.crypto KeyGenerator getInstance

List of usage examples for javax.crypto KeyGenerator getInstance

Introduction

In this page you can find the example usage for javax.crypto KeyGenerator getInstance.

Prototype

public static final KeyGenerator getInstance(String algorithm, Provider provider)
        throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyGenerator object that generates secret keys for the specified algorithm.

Usage

From source file:com.example.android.fingerprintdialog.MainActivity.java

/**
 * Creates a symmetric key in the Android Key Store which can only be used after the user has
 * authenticated with fingerprint.//w  w w .j  av  a  2  s .c  o  m
 */
@TargetApi(VERSION_CODES.M)
public void createKey() {
    // The enrolling flow for fingerprint. This is where you ask the user to set up fingerprint
    // for your flow. Use of keys is necessary if you need to know if the set of
    // enrolled fingerprints has changed.
    try {
        mKeyStore = KeyStore.getInstance("AndroidKeyStore");
        mKeyStore.load(null);

        // Set the alias of the entry in Android KeyStore where the key will appear
        // and the constrains (purposes) in the constructor of the Builder
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,
                "AndroidKeyStore");
        keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                        .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                        // Require the user to authenticate with a fingerprint to authorize every use
                        // of the key
                        .setUserAuthenticationRequired(true)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build());
        keyGenerator.generateKey();
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | KeyStoreException
            | CertificateException | NoSuchProviderException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.kixeye.chassis.transport.WebSocketTransportTest.java

@Test
public void testWebSocketServiceWithJsonWithPskEncryption() throws Exception {
    // create AES shared key cipher
    Security.addProvider(new BouncyCastleProvider());
    KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC");
    kgen.init(128);/*from  w  w  w  .ja v  a  2 s.  c o  m*/
    SecretKey key = kgen.generateKey();
    byte[] aesKey = key.getEncoded();

    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("websocket.enabled", "true");
    properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("websocket.hostname", "localhost");

    properties.put("http.enabled", "false");
    properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
    properties.put("http.hostname", "localhost");

    properties.put("websocket.crypto.enabled", "true");
    properties.put("websocket.crypto.cipherProvider", "BC");
    properties.put("websocket.crypto.cipherTransformation", "AES/ECB/PKCS7Padding");
    properties.put("websocket.crypto.secretKeyAlgorithm", "AES");
    properties.put("websocket.crypto.secretKeyData", BaseEncoding.base16().encode(aesKey));

    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    StandardEnvironment environment = new StandardEnvironment();
    environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
    context.setEnvironment(environment);
    context.register(PropertySourcesPlaceholderConfigurer.class);
    context.register(TransportConfiguration.class);
    context.register(TestWebSocketService.class);

    WebSocketClient wsClient = new WebSocketClient();

    try {
        context.refresh();

        final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class);

        final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class);

        messageRegistry.registerType("stuff", TestObject.class);

        wsClient.start();

        QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry,
                context.getBean(WebSocketPskFrameProcessor.class));

        Session session = wsClient.connect(webSocket, new URI(
                "ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName()))
                .get(5000, TimeUnit.MILLISECONDS);

        Envelope envelope = new Envelope("getStuff", null, null,
                Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), null);

        byte[] rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        byte[] rawStuff = serDe.serialize(new TestObject("more stuff"));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("stuff", response.value);

        envelope = new Envelope("getStuff", null, null, null);

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        response = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(response);
        Assert.assertEquals("more stuff", response.value);

        rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100)));

        envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff));

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code);

        envelope = new Envelope("expectedError", null, null, null);

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code);
        Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description);

        envelope = new Envelope("unexpectedError", null, null, null);

        rawEnvelope = serDe.serialize(envelope);
        rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key,
                "AES/ECB/PKCS7Padding", "BC");

        session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope));

        error = webSocket.getResponse(5, TimeUnit.SECONDS);

        Assert.assertNotNull(error);
        Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code);
    } finally {
        try {
            wsClient.stop();
        } finally {
            context.close();
        }
    }
}

From source file:org.cesecore.keys.token.SoftCryptoToken.java

@Override
public void generateKey(final String algorithm, final int keysize, final String alias)
        throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException,
        CryptoTokenOfflineException, InvalidKeyException, InvalidAlgorithmParameterException,
        SignatureException, CertificateException, IOException, NoSuchPaddingException,
        IllegalBlockSizeException {
    if (StringUtils.isNotEmpty(alias)) {
        // Soft crypto tokens must do very special things for secret keys, since PKCS#12 keystores are ot designed to hold
        // symmetric keys, we wrap the symmetric key with an RSA key and store it in properties

        // Generate the key
        KeyGenerator generator = KeyGenerator.getInstance(algorithm, getEncProviderName());
        generator.init(keysize);//from ww w .j  a  va 2 s .c  o  m
        Key key = generator.generateKey();
        // Wrap it
        // Find wrapping key
        PublicKey pubK = null;
        try {
            pubK = getPublicKey("symwrap");
        } catch (CryptoTokenOfflineException e) {
            // No such key, generate it
            generateKeyPair("2048", "symwrap");
            pubK = getPublicKey("symwrap");
        }

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", getEncProviderName());
        cipher.init(Cipher.WRAP_MODE, pubK);
        byte[] out = cipher.wrap(key);

        String str = new String(Hex.encode(out));
        Properties prop = getProperties();
        prop.setProperty(alias, str);
        setProperties(prop);
    } else {
        log.debug("Trying to generate keys with empty alias.");
    }
}

From source file:org.cesecore.keys.util.KeyStoreTools.java

/** Generates symmetric keys in the Keystore token.
 * //from ww w. j  a  v a  2s  . c o  m
 * @param algorithm symmetric algorithm specified in http://download.oracle.com/javase/1.5.0/docs/api/index.html, suggest AES, DESede or DES
 * @param keysize keysize of symmetric key, suggest 128 or 256 for AES, 64 for 168 for DESede and 64 for DES
 * @param keyEntryName the alias the key will get in the keystore
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws KeyStoreException 
 */
public void generateKey(final String algorithm, final int keysize, final String keyEntryName)
        throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException {
    KeyGenerator generator = KeyGenerator.getInstance(algorithm, this.providerName);
    generator.init(keysize);
    Key key = generator.generateKey();
    setKeyEntry(keyEntryName, key, null);
}

From source file:com.rnd.snapsplit.view.OwedFragment.java

@Nullable
@Override/*from www.j  ava  2  s  . co m*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //super.onCreate(savedInstanceState);
    view = inflater.inflate(R.layout.activity_owed, container, false);
    activity = getActivity();
    profile = new Profile(getContext());
    ((Toolbar) getActivity().findViewById(R.id.tool_bar_hamburger)).setVisibility(View.VISIBLE);

    mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
    mMessageRecyclerView = (RecyclerView) view.findViewById(R.id.messageRecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(getContext());
    //mLinearLayoutManager.setStackFromEnd(true);
    mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference().child("requests");
    mFirebaseAdapter = new FirebaseRecyclerAdapter<PaymentRequest, MessageViewHolder>(PaymentRequest.class,
            R.layout.list_owed, MessageViewHolder.class,
            mFirebaseDatabaseReference.orderByChild("requestEpochDate")) {

        @Override
        protected PaymentRequest parseSnapshot(DataSnapshot snapshot) {
            PaymentRequest pr = super.parseSnapshot(snapshot);
            if (pr != null) {
                pr.setId(snapshot.getKey());
                return pr;
            }
            return null;
        }

        @Override
        protected void populateViewHolder(final MessageViewHolder viewHolder, PaymentRequest pr, int position) {
            mProgressBar.setVisibility(ProgressBar.INVISIBLE);
            if (pr != null && pr.getReceipientPhoneNo().equals(profile.getPhoneNumber())) {

                if (pr.getStrReceiptPic() != null && !pr.getStrReceiptPic().equals("")) {
                    String encodedReceipt = pr.getStrReceiptPic();
                    byte[] encodeByte = Base64.decode(encodedReceipt, Base64.DEFAULT);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
                    viewHolder.receiptIcon.setImageBitmap(bitmap);
                }
                viewHolder.pr = pr;
                viewHolder.id = pr.getId();
                viewHolder.description.setText(pr.getDescription());
                viewHolder.from.setText(
                        "Request sent by: " + pr.getRequestorName() + " - " + pr.getRequestorPhoneNumber());
                viewHolder.share.setText("Your Share: HKD" + String.format("%.2f", pr.getShareAmount()));
                viewHolder.splitAmount
                        .setText("Total Amount: HKD" + String.format("%.2f", pr.getTotalAmount()));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy' 'HH:mm:ss");
                String date = null;
                Date temp = new Date(Long.parseLong(pr.getRequestEpochDate()) * (-1));
                date = simpleDateFormat.format(temp);
                viewHolder.date.setText(date);
            } else {
                ViewGroup.LayoutParams params = viewHolder.item.getLayoutParams();
                params.height = 0;
                viewHolder.item.setLayoutParams(params);
            }

            // log a view action on it
            //FirebaseUserActions.getInstance().end(getMessageViewAction(fd));
        }

        @Override
        public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            MessageViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);
            viewHolder.setOnLongClickListener(new MessageViewHolder.LongClickListener() {
                @Override
                public void onLongClick(View view, int position, String id, PaymentRequest pr) {
                    AlertDialog.Builder ImageDialog = new AlertDialog.Builder(getActivity());
                    ImageDialog.setTitle("Receipt Preview - " + pr.getDescription());
                    ImageView showImage = new ImageView(getActivity());
                    Bitmap bitmap = null;
                    if (pr.getStrReceiptPic() != null && !pr.getStrReceiptPic().equals("")) {
                        String encodedReceipt = pr.getStrReceiptPic();
                        byte[] encodeByte = Base64.decode(encodedReceipt, Base64.DEFAULT);
                        bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
                    }
                    if (bitmap != null) {
                        showImage.setImageBitmap(bitmap);
                    }
                    ImageDialog.setView(showImage);

                    ImageDialog.setNegativeButton("Close Preview", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {
                        }
                    });
                    ImageDialog.show();
                }
            });
            viewHolder.setOnClickListener(new MessageViewHolder.ClickListener() {
                @Override
                public void onItemClick(View view, int position, String id, PaymentRequest pr) {
                    //Toast.makeText(getActivity(), "Item clicked at " + position, Toast.LENGTH_SHORT).show();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("pr", pr);

                    if (initCipher(mCipher, DEFAULT_KEY_NAME)) {
                        // Show the fingerprint dialog. The user has the option to use the fingerprint with
                        // crypto, or you can fall back to using a server-side verified password.
                        DialogFragmentFingerprintAuthentication fragment = new DialogFragmentFingerprintAuthentication();
                        fragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher));
                        boolean useFingerprintPreference = mSharedPreferences
                                .getBoolean(getString(R.string.use_fingerprint_to_authenticate_key), true);
                        if (useFingerprintPreference) {
                            fragment.setStage(DialogFragmentFingerprintAuthentication.Stage.FINGERPRINT);
                        } else {
                            fragment.setStage(DialogFragmentFingerprintAuthentication.Stage.PASSWORD);
                        }
                        fragment.setArguments(bundle);
                        fragment.setTargetFragment(mFragment, 0);
                        fragment.show(getFragmentManager(), DIALOG_FRAGMENT_TAG);
                    } else {
                        // This happens if the lock screen has been disabled or or a fingerprint got
                        // enrolled. Thus show the dialog to authenticate with their password first
                        // and ask the user if they want to authenticate with fingerprints in the
                        // future
                        DialogFragmentFingerprintAuthentication fragment = new DialogFragmentFingerprintAuthentication();
                        fragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher));
                        fragment.setStage(
                                DialogFragmentFingerprintAuthentication.Stage.NEW_FINGERPRINT_ENROLLED);
                        fragment.setArguments(bundle);
                        fragment.setTargetFragment(mFragment, 0);
                        fragment.show(getFragmentManager(), DIALOG_FRAGMENT_TAG);
                    }
                }

            });
            return viewHolder;
        }

    };

    mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            int friendlyMessageCount = mFirebaseAdapter.getItemCount();
            int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
            // If the recycler view is initially being loaded or the user is at the bottom of the list, scroll
            // to the bottom of the list to show the newly added message.
            if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1)
                    && lastVisiblePosition == (positionStart - 1))) {
                mMessageRecyclerView.scrollToPosition(positionStart);
            }
        }
    });

    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
    mMessageRecyclerView.setAdapter(mFirebaseAdapter);

    try {
        mKeyStore = KeyStore.getInstance("AndroidKeyStore");
    } catch (KeyStoreException e) {
        throw new RuntimeException("Failed to get an instance of KeyStore", e);
    }
    try {
        mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        throw new RuntimeException("Failed to get an instance of KeyGenerator", e);
    }
    //Cipher defaultCipher;
    Cipher cipherNotInvalidated;
    try {
        mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
                + KeyProperties.ENCRYPTION_PADDING_PKCS7);
        cipherNotInvalidated = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
                + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        throw new RuntimeException("Failed to get an instance of Cipher", e);
    }
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());

    KeyguardManager keyguardManager = getActivity().getSystemService(KeyguardManager.class);
    FingerprintManager fingerprintManager = getActivity().getSystemService(FingerprintManager.class);

    if (!keyguardManager.isKeyguardSecure()) {
        // Show a message that the user hasn't set up a fingerprint or lock screen.
        Toast.makeText(getActivity(),
                "Secure lock screen hasn't set up.\n"
                        + "Go to 'Settings -> Security -> Fingerprint' to set up a fingerprint",
                Toast.LENGTH_LONG).show();
        //return;
    }

    // Now the protection level of USE_FINGERPRINT permission is normal instead of dangerous.
    // See http://developer.android.com/reference/android/Manifest.permission.html#USE_FINGERPRINT
    // The line below prevents the false positive inspection from Android Studio
    // noinspection ResourceType
    if (!fingerprintManager.hasEnrolledFingerprints()) {
        // This happens when no fingerprints are registered.
        Toast.makeText(getActivity(),
                "Go to 'Settings -> Security -> Fingerprint' and register at least one fingerprint",
                Toast.LENGTH_LONG).show();
        //return;
    }

    createKey(DEFAULT_KEY_NAME, true);
    createKey(KEY_NAME_NOT_INVALIDATED, false);

    return view;

}

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

/**
 * Instantiates the encryptor and digester using the configuration properties. If the properties
 * are not found, reasonable defaults are used.
 * /*from w w w.  jav  a 2s.c  o  m*/
 * @param provider
 *            The provider to use (ex. BC)
 * @param keyStore
 *            The keystore from which to load the secret encryption key
 * @param keyPassword
 *            The secret key password
 * @throws Exception
 */
private void configureEncryption(Provider provider, KeyStore keyStore, char[] keyPassword) throws Exception {
    SecretKey secretKey = null;

    if (!keyStore.containsAlias(SECRET_KEY_ALIAS)) {
        logger.debug("encryption key not found, generating new one");
        KeyGenerator keyGenerator = KeyGenerator.getInstance(encryptionConfig.getEncryptionAlgorithm(),
                provider);
        keyGenerator.init(encryptionConfig.getEncryptionKeyLength());
        secretKey = keyGenerator.generateKey();
        KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(secretKey);
        keyStore.setEntry(SECRET_KEY_ALIAS, entry, new KeyStore.PasswordProtection(keyPassword));
    } else {
        logger.debug("found encryption key in keystore");
        secretKey = (SecretKey) keyStore.getKey(SECRET_KEY_ALIAS, keyPassword);
    }

    /*
     * Now that we have a secret key, store it in the encryption settings so that we can use it
     * to encryption things client side.
     */
    encryptionConfig.setSecretKey(secretKey.getEncoded());

    encryptor = new KeyEncryptor();
    encryptor.setProvider(provider);
    encryptor.setKey(secretKey);
    encryptor.setFormat(Output.BASE64);

    digester = new Digester();
    digester.setProvider(provider);
    digester.setAlgorithm(encryptionConfig.getDigestAlgorithm());
    digester.setFormat(Output.BASE64);
}