javax.crypto.KeyGenerator Java Examples

The following examples show how to use javax.crypto.KeyGenerator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SecurePreferences.java    From UtilsLib with MIT License 6 votes vote down vote up
@Deprecated
private static String generateAesKeyValue() throws NoSuchAlgorithmException {
    // Do *not* seed secureRandom! Automatically seeded from system entropy
    final SecureRandom random = new SecureRandom();

    // Use the largest AES key length which is supported by the OS
    final KeyGenerator generator = KeyGenerator.getInstance("AES");
    try {
        generator.init(KEY_SIZE, random);
    } catch (Exception e) {
        try {
            generator.init(192, random);
        } catch (Exception e1) {
            generator.init(128, random);
        }
    }
    return SecurePreferences.encode(generator.generateKey().getEncoded());
}
 
Example #2
Source File: WrongAAD.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public WrongAAD() throws Exception {
    // init a secret key
    KeyGenerator kg = KeyGenerator.getInstance("AES", PROVIDER);
    kg.init(KEY_SIZE);
    key = kg.generateKey();

    // generate a plain text
    plainText = Helper.generateBytes(TEXT_SIZE);

    // init AADs
    byte[] AAD = Helper.generateBytes(AAD_SIZE);

    // init a cipher
    encryptCipher = createCipher(Cipher.ENCRYPT_MODE, null);
    encryptCipher.updateAAD(AAD);
}
 
Example #3
Source File: ConstantIv.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void encryptIvNotInitialize3(String message) throws Exception {

        //IV
        IvParameterSpec ivSpec = new IvParameterSpec(new byte[16]);  //Oups. All 0s

        //Key
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        generator.init(128);
        SecretKey secretKey = generator.generateKey();

        //Encrypt
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
        cipher.update(message.getBytes());

        byte[] data = cipher.doFinal();
        System.out.println(HexUtil.toString(data));
    }
 
Example #4
Source File: LinkToolUtil.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Generate a secret key, and write it to a file
 * 
 * @param dirname
 *        writes to file privkeyname in this 
 *        directory. dirname assumed to end in /
 */

private static void genkey(String dirname) 
{
	try 
	{
		/* Generate key. */
		log.info("Generating new key in {}{}", dirname, privkeyname);
		SecretKey key = KeyGenerator.getInstance("Blowfish").generateKey();

		/* Write private key to file. */
		writeKey(key, dirname + privkeyname);
	} catch (Exception e) {
		log.debug("Error generating key", e);
	}

}
 
Example #5
Source File: DynamoDBSignerTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {

    //RSA key generation
    KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
    rsaGen.initialize(2048, Utils.getRng());
    KeyPair sigPair = rsaGen.generateKeyPair();
    pubKeyRsa = sigPair.getPublic();
    privKeyRsa = sigPair.getPrivate();

    KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
    macGen.init(256, Utils.getRng());
    macKey = macGen.generateKey();

    Security.addProvider(new BouncyCastleProvider());
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1");
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
    g.initialize(ecSpec, Utils.getRng());
    KeyPair keypair = g.generateKeyPair();
    pubKeyEcdsa = keypair.getPublic();
    privKeyEcdsa = keypair.getPrivate();

}
 
Example #6
Source File: CipherOutputStreamTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private static SecretKey getAndroidKeyStoreSecretKey() throws Exception {
    KeyGenerator keygen = KeyGenerator.getInstance("AES", "AndroidKeyStore");
    Class<?> keyParamsBuilderClass = keygen.getClass().getClassLoader().loadClass(
            "android.security.keystore.KeyGenParameterSpec$Builder");
    Object keyParamsBuilder = keyParamsBuilderClass.getConstructor(String.class, Integer.TYPE)
            // 3 is PURPOSE_ENCRYPT | PURPOSE_DECRYPT
            .newInstance("testDecryptCorruptGCM", 3);
    keyParamsBuilderClass.getMethod("setBlockModes", new Class[]{String[].class})
            .invoke(keyParamsBuilder, new Object[]{new String[]{"GCM"}});
    keyParamsBuilderClass.getMethod("setEncryptionPaddings", new Class[]{String[].class})
            .invoke(keyParamsBuilder, new Object[]{new String[]{"NoPadding"}});
    AlgorithmParameterSpec spec = (AlgorithmParameterSpec)
            keyParamsBuilderClass.getMethod("build", new Class[]{}).invoke(keyParamsBuilder);
    keygen.init(spec);
    return keygen.generateKey();
}
 
Example #7
Source File: AESUtil.java    From jee-universal-bms with Apache License 2.0 6 votes vote down vote up
public static String StrDecrypt(String content, String secret,String charset){
	try {
		byte[] bytes = Encodes.decodeHex(content);
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		//kgen.init(128, new SecureRandom(authorization.getBytes(charset)));
		SecureRandom secureRandom=
			      SecureRandom.getInstance("SHA1PRNG");
			      secureRandom.setSeed(secret.getBytes(charset));
			      kgen.init(128,secureRandom);
		SecretKey secretKey = kgen.generateKey();
		byte[] enCodeFormat = secretKey.getEncoded();
		SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
		Cipher cipher = Cipher.getInstance("AES");// 创建密码器
		cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
		byte[] result = cipher.doFinal(bytes);// 加密
		return bytes == null ? null : new String(result, charset);
	} catch (Exception e) {
	}
	return null;
}
 
Example #8
Source File: AESUtil.java    From taoshop with Apache License 2.0 6 votes vote down vote up
/**
 * 解密
 * @param encryptBytes
 * @param decryptKey
 * @return
 * @throws Exception
 */
public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    //防止linux下 随机生成key
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
    secureRandom.setSeed(decryptKey.getBytes());
    kgen.init(128, secureRandom);
    SecretKey secretKey = kgen.generateKey();
    byte[] enCodeFormat = secretKey.getEncoded();
    SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
    Cipher cipher = Cipher.getInstance("AES");// 创建密码器
    cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
    byte[] result = cipher.doFinal(encryptBytes);

    return new String(result);
}
 
Example #9
Source File: AesUtil.java    From springboot-shiro with MIT License 6 votes vote down vote up
/**
 * 生成加密秘钥
 *
 * @return
 */
private static SecretKeySpec getSecretKey(final String password) throws NoSuchAlgorithmException {
    //返回生成指定算法密钥生成器的 KeyGenerator 对象
    KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
    // javax.crypto.BadPaddingException: Given final block not properly padded解决方案
    // https://www.cnblogs.com/zempty/p/4318902.html - 用此法解决的
    // https://www.cnblogs.com/digdeep/p/5580244.html - 留作参考吧
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(password.getBytes());
    //AES 要求密钥长度为 128
    kg.init(128, random);

    //生成一个密钥
    SecretKey secretKey = kg.generateKey();
    // 转换为AES专用密钥
    return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
}
 
Example #10
Source File: EncryptionUtil.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public byte[] encrypt(byte[] data, PublicKey publicKey, SecretKey key) throws Exception
{
  // Get the KeyGenerator
   KeyGenerator kgen = KeyGenerator.getInstance(this.encryptionAlgorithm);
   kgen.init(keySize);
 
   byte[] publicKeyEncoded = publicKey.getEncoded();

   SecretKeySpec skeySpec = new SecretKeySpec(key.getEncoded(), encryptionAlgorithm);


   // Instantiate the cipher 
   Cipher cipher = Cipher.getInstance(encryptionAlgorithm);

   cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

   byte[] encrypted =
     cipher.doFinal( data);
   return encrypted;
}
 
Example #11
Source File: ToolDESede.java    From protools with Apache License 2.0 6 votes vote down vote up
/**
 * 生成密钥 <br>
 *
 * @return byte[] 二进制密钥
 *
 * @throws Exception
 */
public static byte[] initKey() throws NoSuchAlgorithmException {

    // 实例化
    KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);

    /*
     * DESede 要求密钥长度为 112位或168位
     */
    kg.init(168);

    // 生成秘密密钥
    SecretKey secretKey = kg.generateKey();

    // 获得密钥的二进制编码形式
    return secretKey.getEncoded();
}
 
Example #12
Source File: WrongAAD.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public WrongAAD() throws Exception {
    // init a secret key
    KeyGenerator kg = KeyGenerator.getInstance("AES", PROVIDER);
    kg.init(KEY_SIZE);
    key = kg.generateKey();

    // generate a plain text
    plainText = Helper.generateBytes(TEXT_SIZE);

    // init AADs
    byte[] AAD = Helper.generateBytes(AAD_SIZE);

    // init a cipher
    encryptCipher = createCipher(Cipher.ENCRYPT_MODE, null);
    encryptCipher.updateAAD(AAD);
}
 
Example #13
Source File: ToolHmacRipeMD.java    From protools with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化HmacRipeMD128密钥
 *
 * @return byte[] 密钥
 *
 * @throws NoSuchAlgorithmException
 */
public static byte[] initHmacRipeMD128Key() throws NoSuchAlgorithmException {

    // 加入BouncyCastleProvider支持
    Security.addProvider(new BouncyCastleProvider());

    // 初始化KeyGenerator
    KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacRipeMD128");

    // 产生秘密密钥
    SecretKey secretKey = keyGenerator.generateKey();

    // 获得密钥
    return secretKey.getEncoded();
}
 
Example #14
Source File: EncryptingOutputStream.java    From alfresco-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Constructs an EncryptingOutputStream.
 * 
 * @param wrapped
 *            outputstream to store the encrypted data
 * @param receiverKey
 *            the receiver's public key for encrypting the symmetric key
 * @param algorithm
 *            symmetric encryption algorithm (e.g. "AES")
 * @param rand
 *            a secure source of randomness
 * @param strength
 *            the key size in bits (e.g. 128)
 * @param mode
 *            encryption mode (e.g. "CBC")
 * @param padding
 *            padding scheme (e.g. "PKCS5PADDING")
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws NoSuchAlgorithmException
 *             the no such algorithm exception
 * @throws NoSuchPaddingException
 *             the no such padding exception
 * @throws InvalidKeyException
 *             the invalid key exception
 * @throws BadPaddingException
 *             the bad padding exception
 * @throws IllegalBlockSizeException
 *             the illegal block size exception
 */
public EncryptingOutputStream(final OutputStream wrapped, final PublicKey receiverKey, final String algorithm,
        final SecureRandom rand, final int strength, final String mode, final String padding) throws IOException,
        NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
        BadPaddingException
{
    // Initialise
    this.wrapped = wrapped;

    // Generate a random symmetric key
    final KeyGenerator keyGen = KeyGenerator.getInstance(algorithm);
    keyGen.init(strength, rand);
    final Key symKey = keyGen.generateKey();

    // Instantiate Symmetric cipher for encryption.
    this.outputCipher = Cipher.getInstance(algorithm + "/" + mode + "/" + padding);
    this.outputCipher.init(Cipher.ENCRYPT_MODE, symKey, rand);

    // Set up HMAC
    this.mac = Mac.getInstance("HMACSHA1");
    final byte[] macKeyBytes = new byte[20];
    rand.nextBytes(macKeyBytes);
    final Key macKey = new SecretKeySpec(macKeyBytes, "HMACSHA1");
    this.mac.init(macKey);

    // Set up RSA to encrypt symmetric key
    final Cipher rsa = Cipher.getInstance("RSA/ECB/OAEPWITHSHA1ANDMGF1PADDING");
    rsa.init(Cipher.ENCRYPT_MODE, receiverKey, rand);

    // Write the header

    // Write out an RSA-encrypted block for the key of the cipher.
    writeBlock(rsa.doFinal(symKey.getEncoded()));

    // Write out RSA-encrypted Initialisation Vector block
    writeBlock(rsa.doFinal(this.outputCipher.getIV()));

    // Write out key for HMAC.
    writeBlock(this.outputCipher.doFinal(macKey.getEncoded()));
}
 
Example #15
Source File: CryptoUtils.java    From Aegis with GNU General Public License v3.0 5 votes vote down vote up
public static SecretKey generateKey() {
    try {
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        generator.init(CRYPTO_AEAD_KEY_SIZE * 8);
        return generator.generateKey();
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    }
}
 
Example #16
Source File: JdkCryptorSupport.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * Generate symmetric algorithm key.
 * 
 * @param keybits
 * @return
 */
public CodecSource generateKey(int keybits) {
	try {
		SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
		KeyGenerator keyGenerator = KeyGenerator.getInstance(config.getAlgName());
		keyGenerator.init(keybits, random);
		SecretKey secretKey = keyGenerator.generateKey();
		return new CodecSource(secretKey.getEncoded());
	} catch (GeneralSecurityException e) {
		throw new IllegalStateException(e);
	}
}
 
Example #17
Source File: Association.java    From openid4java with Apache License 2.0 5 votes vote down vote up
public static boolean isHmacSha256Supported()
{
    try
    {
        KeyGenerator.getInstance(HMAC_SHA256_ALGORITHM);

        return true;
    }
    catch (NoSuchAlgorithmException e)
    {
        return false;
    }
}
 
Example #18
Source File: RNSensitiveInfoModule.java    From react-native-sensitive-info with MIT License 5 votes vote down vote up
private void prepareKey() throws Exception {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
        return;
    }
    KeyGenerator keyGenerator = KeyGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE_PROVIDER);

    KeyGenParameterSpec.Builder builder = null;
    builder = new KeyGenParameterSpec.Builder(
            KEY_ALIAS_AES,
            KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT);

    builder.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
            .setKeySize(256)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
            // forces user authentication with fingerprint
            .setUserAuthenticationRequired(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        try {
            builder.setInvalidatedByBiometricEnrollment(invalidateEnrollment);
        } catch (Exception e) {
            Log.d("RNSensitiveInfo", "Error setting setInvalidatedByBiometricEnrollment: " + e.getMessage());
        }
    }

    keyGenerator.init(builder.build());
    keyGenerator.generateKey();
}
 
Example #19
Source File: AesCipherProvider.java    From RxFingerprint with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
private static SecretKey createKey(String keyName, boolean invalidatedByBiometricEnrollment) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE);
        keyGenerator.init(getKeyGenParameterSpecBuilder(keyName, KeyProperties.BLOCK_MODE_CBC, KeyProperties.ENCRYPTION_PADDING_PKCS7, invalidatedByBiometricEnrollment)
                .setKeySize(AES_KEY_SIZE)
                .build());
        return keyGenerator.generateKey();
}
 
Example #20
Source File: TestCipherKeyWrapperTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void wrapperAesDESedeKeyTest(String algo, String wrapAlgo,
        int keySize) throws InvalidKeyException, NoSuchAlgorithmException,
        NoSuchPaddingException, IllegalBlockSizeException,
        InvalidAlgorithmParameterException {
    // Initialization
    KeyGenerator kg = KeyGenerator.getInstance(algo);
    if (keySize != -1) {
        kg.init(keySize);
    }
    SecretKey key = kg.generateKey();
    wrapTest(algo, wrapAlgo, key, key, Cipher.SECRET_KEY, false);
}
 
Example #21
Source File: AESTest.java    From java_security with MIT License 5 votes vote down vote up
public static void jdkAES()
{
	try 
	{
		// 生成KEY
		KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");			
		keyGenerator.init(128);
		// 产生密钥
		SecretKey secretKey = keyGenerator.generateKey();
		// 获取密钥
		byte[] keyBytes = secretKey.getEncoded();
		
		
		// KEY转换
		Key key = new SecretKeySpec(keyBytes, "AES");
		
		
		// 加密
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] result = cipher.doFinal(src.getBytes());
		System.out.println("jdk aes encrypt:" + Hex.encodeHexString(result));
		
		// 解密
		cipher.init(Cipher.DECRYPT_MODE, key);
		result = cipher.doFinal(result);
		System.out.println("jdk aes decrypt:" + new String(result));
		
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #22
Source File: TestCipherKeyWrapperTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void wrapperAesDESedeKeyTest(String algo, String wrapAlgo,
        int keySize) throws InvalidKeyException, NoSuchAlgorithmException,
        NoSuchPaddingException, IllegalBlockSizeException,
        InvalidAlgorithmParameterException {
    // Initialization
    KeyGenerator kg = KeyGenerator.getInstance(algo);
    if (keySize != -1) {
        kg.init(keySize);
    }
    SecretKey key = kg.generateKey();
    wrapTest(algo, wrapAlgo, key, key, Cipher.SECRET_KEY, false);
}
 
Example #23
Source File: TestPremaster.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void test(KeyGenerator kg,
        int clientVersion, int serverVersion) throws Exception {

    System.out.printf(
            "Testing RSA pre-master secret key generation between " +
            "client (0x%04X) and server(0x%04X)%n",
            clientVersion, serverVersion);
    kg.init(new TlsRsaPremasterSecretParameterSpec(
                                clientVersion, serverVersion));

    SecretKey key = kg.generateKey();
    byte[] encoded = key.getEncoded();
    if (encoded != null) {  // raw key material may be not extractable
        if (encoded.length != 48) {
            throw new Exception("length: " + encoded.length);
        }
        int v = versionOf(encoded[0], encoded[1]);
        if (clientVersion != v) {
            if (serverVersion != v || clientVersion >= 0x0302) {
                throw new Exception(String.format(
                    "version mismatch: (0x%04X) rather than (0x%04X) " +
                    "is used in pre-master secret", v, clientVersion));
            }
            System.out.printf("Use compatible version (0x%04X)%n", v);
        }
        System.out.println("Passed, version matches!");
   } else {
        System.out.println("Raw key material is not extractable");
   }
}
 
Example #24
Source File: PasswordCrypt.java    From ermasterr with Apache License 2.0 5 votes vote down vote up
private static Key generateKey() throws Exception {
    final KeyGenerator generator = KeyGenerator.getInstance(KEY_ALGORITHM);

    final SecureRandom random = new SecureRandom();
    generator.init(128, random);
    final Key key = generator.generateKey();

    return key;
}
 
Example #25
Source File: P12SecretKey.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void run(String keystoreType) throws Exception {
    char[] pw = "password".toCharArray();
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(null, pw);

    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(128);
    SecretKey key = kg.generateKey();

    KeyStore.SecretKeyEntry ske = new KeyStore.SecretKeyEntry(key);
    KeyStore.ProtectionParameter kspp = new KeyStore.PasswordProtection(pw);
    ks.setEntry(ALIAS, ske, kspp);

    File ksFile = File.createTempFile("test", ".test");
    try (FileOutputStream fos = new FileOutputStream(ksFile)) {
        ks.store(fos, pw);
        fos.flush();
    }

    // now see if we can get it back
    try (FileInputStream fis = new FileInputStream(ksFile)) {
        KeyStore ks2 = KeyStore.getInstance(keystoreType);
        ks2.load(fis, pw);
        KeyStore.Entry entry = ks2.getEntry(ALIAS, kspp);
        SecretKey keyIn = ((KeyStore.SecretKeyEntry)entry).getSecretKey();
        if (Arrays.equals(key.getEncoded(), keyIn.getEncoded())) {
            System.err.println("OK: worked just fine with " + keystoreType +
                               " keystore");
        } else {
            System.err.println("ERROR: keys are NOT equal after storing in "
                               + keystoreType + " keystore");
        }
    }
}
 
Example #26
Source File: TestServer.java    From ob1k with Apache License 2.0 5 votes vote down vote up
private static byte[] createKey() {
  try {
    final KeyGenerator generator = KeyGenerator.getInstance("AES");
    final SecretKey key = generator.generateKey();
    return key.getEncoded();
  } catch (final NoSuchAlgorithmException e) {
    throw new RuntimeException("Error creating key", e);
  }
}
 
Example #27
Source File: SecretKeyGenerator.java    From Much-Assembly-Required with GNU General Public License v3.0 5 votes vote down vote up
public SecretKeyGenerator() {
    try {
        keyGen = KeyGenerator.getInstance(KEY_GENERATION_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Error creating Key generator", e);
    }
    keyGen.init(new SecureRandom(SecureRandom.getSeed(32)));
}
 
Example #28
Source File: EncryptUtil.java    From hdw-dubbo with Apache License 2.0 5 votes vote down vote up
/**
 * AES解密
 *
 * @param cipherText 密文
 * @param privateKey 密钥
 * @return
 * @throws Exception
 */
public static String decryptAES(String cipherText, String privateKey) {
    try {
        if (cipherText.length() < 1) {
            return null;
        }
        byte[] byteRresult = new byte[cipherText.length() / 2];
        for (int i = 0; i < cipherText.length() / 2; i++) {
            int high = Integer.parseInt(cipherText.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(cipherText.substring(i * 2 + 1, i * 2 + 2), 16);
            byteRresult[i] = (byte) (high * 16 + low);
        }
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(privateKey.getBytes());
        kgen.init(128, random);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] result = cipher.doFinal(byteRresult);
        return new String(result);
    } catch (Exception e) {
        return null;
    }
}
 
Example #29
Source File: EncryptionTests.java    From hygieia-core with Apache License 2.0 5 votes vote down vote up
private static SecretKey getKey() {
		SecretKey key = null;
		try {
			key = KeyGenerator.getInstance(ALGO).generateKey();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
//		String stringKey = Base64.encodeBase64String(key.getEncoded());
		return key;
	}
 
Example #30
Source File: EncryptAES.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
public EncryptAES() throws NoSuchAlgorithmException, NoSuchPaddingException{
	//ʵ����֧��DES�㷨����Կ������(�㷨���������谴�涨�������׳��쳣)
	keygen = KeyGenerator.getInstance("AES");
	//������Կ
	deskey = keygen.generateKey();
	//����Cipher����,ָ����֧�ֵ�DES�㷨
	c = Cipher.getInstance("AES");
}