Search in sources :

Example 91 with SecretKey

use of javax.crypto.SecretKey in project UltimateAndroid by cymcsg.

the class TripleDES method decrypt.

public static String decrypt(byte[] message) throws Exception {
    byte[] values = Base64decodingByte(message, 0);
    final MessageDigest md = MessageDigest.getInstance("SHA-1");
    final byte[] digestOfPassword = md.digest(token.getBytes("utf-8"));
    final byte[] keyBytes = copyOf(digestOfPassword, 24);
    for (int j = 0, k = 16; j < 8; ) {
        keyBytes[k++] = keyBytes[j++];
    }
    final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
    String s1 = "12345678";
    byte[] bytes = s1.getBytes();
    final IvParameterSpec iv = new IvParameterSpec(bytes);
    final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    decipher.init(Cipher.DECRYPT_MODE, key, iv);
    final byte[] plainText = decipher.doFinal(values);
    return new String(plainText, "UTF-8");
}
Also used : SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) MessageDigest(java.security.MessageDigest)

Example 92 with SecretKey

use of javax.crypto.SecretKey in project SeaStar by 13120241790.

the class BackAES method newencrypt.

/*********************************** 第二种 ***********************************************/
public static byte[] newencrypt(String content, String password) {
    try {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128, new SecureRandom(password.getBytes()));
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        // 创建AES加密编码器
        Cipher cipher = Cipher.getInstance("AES");
        byte[] byteContent = content.getBytes("UTF-8");
        // 初始化AES加密
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] result = cipher.doFinal(byteContent);
        // AES加密结果
        return result;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) SecureRandom(java.security.SecureRandom) Cipher(javax.crypto.Cipher) KeyGenerator(javax.crypto.KeyGenerator)

Example 93 with SecretKey

use of javax.crypto.SecretKey in project SeaStar by 13120241790.

the class BackAES method newdecrypt.

/*
	 * @param content 待解密内容,格式为byte数组
	 * 
	 * @param password AES解密使用的密钥
	 * 
	 * @return
	 */
public static byte[] newdecrypt(byte[] content, String password) {
    try {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128, new SecureRandom(password.getBytes()));
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        // 创建AES加密编码器
        Cipher cipher = Cipher.getInstance("AES");
        // 初始化AES加密
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] result = cipher.doFinal(content);
        // 得到AES解密结果
        return result;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) SecureRandom(java.security.SecureRandom) Cipher(javax.crypto.Cipher) KeyGenerator(javax.crypto.KeyGenerator)

Example 94 with SecretKey

use of javax.crypto.SecretKey in project nhin-d by DirectProject.

the class PKCS11SecretKeyManager method addAESKey.

private void addAESKey() {
    final String input = JOptionPane.showInputDialog(this, "Key Alias Name:", "Generate New random AES Secret Key", JOptionPane.OK_CANCEL_OPTION);
    if (input != null && !input.trim().isEmpty()) {
        // generate a new random secret key
        try {
            final KeyGenerator keyGen = KeyGenerator.getInstance("AES");
            // cryptograph. secure random 
            final SecureRandom random = new SecureRandom();
            keyGen.init(random);
            final SecretKey key = keyGen.generateKey();
            mgr.clearKey(input);
            mgr.setKey(input, key);
            updateKeyTableData();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Failed to add random new AES key: " + e.getMessage(), "Add Key Error", JOptionPane.ERROR_MESSAGE);
        }
    }
}
Also used : SecretKey(javax.crypto.SecretKey) SecureRandom(java.security.SecureRandom) KeyGenerator(javax.crypto.KeyGenerator) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException)

Example 95 with SecretKey

use of javax.crypto.SecretKey in project nhin-d by DirectProject.

the class PKCS11Commands method importPrivateKeyFile.

//@Command(name = "ImportP12FileForTempKey", usage = IMPORT_P12_FILE_FOR_TEMP_KEY)
public void importPrivateKeyFile(String[] args) {
    if (!(mgr instanceof WrappableKeyProtectionManager)) {
        System.out.println("Key store manager does not support wrapping.");
        return;
    }
    final WrappableKeyProtectionManager wrapMgr = (WrappableKeyProtectionManager) mgr;
    final String fileName = StringArrayUtil.getRequiredValue(args, 0);
    final String keyStorePass = StringArrayUtil.getOptionalValue(args, 1, "");
    final String privKeyPass = StringArrayUtil.getOptionalValue(args, 2, "");
    try {
        final KeyStore pkcs11Store = mgr.getKS();
        final String providerName = pkcs11Store.getProvider().getName();
        System.out.println("Provider Name: " + providerName);
        /*
			 * 1. Create an AES128 secret key on the HSM that will be used to 
			 * encrypt and decrypt private key data.  Use the PrivKeyProtKey entry to store it
			 */
        final KeyGenerator keyGen = KeyGenerator.getInstance("AES", providerName);
        keyGen.init(128);
        final SecretKey keyStoreSecretKey = keyGen.generateKey();
        /*
			 * 2. Get an existing private key that was generated and is stored in a p12 file.  
			 * For real operations, the private key may be generated on an HSM and exported in wrapped format for
			 * storage in a database.  For this test, we'll just use an existing private key in a p12 file and 
			 * wrap it on the HSM.
			 */
        final KeyStore store = KeyStore.getInstance("pkcs12");
        store.load(FileUtils.openInputStream(new File(fileName)), keyStorePass.toCharArray());
        // there should only be on entry
        final String alias = store.aliases().nextElement();
        final PrivateKey entry = (PrivateKey) store.getKey(alias, privKeyPass.toCharArray());
        /*
			 * 3. "Wrap" the private using secret key and AES128 encryption and write it to a file.  The encryption is done
			 * on the HSM so the secret key never leaves the HSM token.  We aren't actually "wrapping" the private key because
			 * it's not on the HSM.  Using "encrypt" instead.
			 */
        /*
			final Cipher wrapCipher = Cipher.getInstance("AES/CBC/PKCS5Padding", providerName);
			wrapCipher.init(Cipher.WRAP_MODE, keyStoreSecretKey, iv);
			byte[] wrappedKey = wrapCipher.wrap(entry);
			*/
        byte[] wrappedKey = wrapMgr.wrapWithSecretKey(keyStoreSecretKey, entry);
        /*
			 * 4. Now we have a wrap key in a file.  Let's install it into the token using the 
			 * secret key on the HSM.  This should return us with a private key object, but we should
			 * not be able to get access to the actual unencrypted key data.
			 */
        byte[] encryptedKey = wrappedKey;
        /*
			final Cipher unwrapCipher = Cipher.getInstance("AES/CBC/PKCS5Padding", providerName);
			unwrapCipher.init(Cipher.UNWRAP_MODE, keyStoreSecretKey, iv);
			@SuppressWarnings("unused")
			final PrivateKey securedPrivateKey = (PrivateKey)unwrapCipher.unwrap(encryptedKey, "RSA", Cipher.PRIVATE_KEY);
			*/
        @SuppressWarnings("unused") final PrivateKey securedPrivateKey = (PrivateKey) wrapMgr.unwrapWithSecretKey(keyStoreSecretKey, encryptedKey, "RSA", Cipher.PRIVATE_KEY);
        System.out.println("Successfully created an unwrapped private key");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : WrappableKeyProtectionManager(org.nhindirect.common.crypto.WrappableKeyProtectionManager) SecretKey(javax.crypto.SecretKey) PrivateKey(java.security.PrivateKey) KeyStore(java.security.KeyStore) KeyGenerator(javax.crypto.KeyGenerator) File(java.io.File)

Aggregations

SecretKey (javax.crypto.SecretKey)491 Cipher (javax.crypto.Cipher)176 SecretKeySpec (javax.crypto.spec.SecretKeySpec)141 KeyGenerator (javax.crypto.KeyGenerator)121 SecretKeyFactory (javax.crypto.SecretKeyFactory)89 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)87 SecureRandom (java.security.SecureRandom)61 InvalidKeyException (java.security.InvalidKeyException)58 PBEKeySpec (javax.crypto.spec.PBEKeySpec)58 IvParameterSpec (javax.crypto.spec.IvParameterSpec)46 IOException (java.io.IOException)44 Test (org.junit.Test)40 PBEParameterSpec (javax.crypto.spec.PBEParameterSpec)35 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)34 KeyStore (java.security.KeyStore)32 PrivateKey (java.security.PrivateKey)30 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)30 KeyStoreException (java.security.KeyStoreException)29 BadPaddingException (javax.crypto.BadPaddingException)29 Mac (javax.crypto.Mac)29