Java Code Examples for javax.crypto.Cipher#init()
The following examples show how to use
javax.crypto.Cipher#init() .
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: CipherStreamClose.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
public static byte[] streamEncrypt(String message, SecretKey key, MessageDigest digest) throws Exception { byte[] data; Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); encCipher.init(Cipher.ENCRYPT_MODE, key); try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); DigestOutputStream dos = new DigestOutputStream(bos, digest); CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) { try (ObjectOutputStream oos = new ObjectOutputStream(cos)) { oos.writeObject(message); } data = bos.toByteArray(); } if (debug) { System.out.println(DatatypeConverter.printHexBinary(data)); } return data; }
Example 2
Source File: Des.java From dk-foundation with GNU Lesser General Public License v2.1 | 6 votes |
/** * 加密 * @param data * @param sKey * @return */ public static byte[] encrypt(byte[] data, String sKey) { try { byte[] key = sKey.getBytes(); // 初始化向量 IvParameterSpec iv = new IvParameterSpec(key); DESKeySpec desKey = new DESKeySpec(key); // 创建一个密匙工厂,然后用它把DESKeySpec转换成securekey SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); // 用密匙初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, securekey, iv); // 现在,获取数据并加密 // 正式执行加密操作 return cipher.doFinal(data); } catch (Throwable e) { e.printStackTrace(); } return null; }
Example 3
Source File: SecurePreferences.java From aptoide-client with GNU General Public License v2.0 | 6 votes |
private static String decrypt(String ciphertext) { if (ciphertext == null || ciphertext.length() == 0) { return ciphertext; } try { final Cipher cipher = Cipher.getInstance(AES_KEY_ALG, PROVIDER); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec( SecurePreferences.sKey, AES_KEY_ALG)); return new String(cipher.doFinal(SecurePreferences .decode(ciphertext)), "UTF-8"); } catch (Exception e) { if (sLoggingEnabled) { Log.w(TAG, "decrypt", e); } return null; } }
Example 4
Source File: AESUtil.java From singleton with Eclipse Public License 2.0 | 6 votes |
/** * The encryption method by AES * * @param data Data to be encrypted * @param key AES key (must be 16 bytes) * @return The encrypted string */ public static String encrypt(String data, String key) { if (key.length() < 16) { logger.error("Invalid AES key length (must be 16 bytes)"); return null; } else if (key.length() > 16) { key = key.substring(0, 16); } try { Cipher cipher = Cipher.getInstance(ConstantsKeys.AES_ALGORITHM); byte[] byteContent = data.getBytes(ConstantsUnicode.UTF8); cipher.init(Cipher.ENCRYPT_MODE, genKey(key)); byte[] result = cipher.doFinal(byteContent); return parseByte2HexStr(result); } catch (Exception e) { logger.error(e.getMessage(), e); } return null; }
Example 5
Source File: SymmetricCryptorSupport.java From super-cloudops with Apache License 2.0 | 6 votes |
/** * Decryption symmetric cipher source. * * @param key * @param iv * @param cipherSource * @return */ protected CodecSource doDecrypt(byte[] key, IvParameterSpec iv, CodecSource cipherSource) { notNullOf(key, "key"); notNullOf(cipherSource, "cipherSource"); try { SecretKey _key = createSecretKey(key); // Create a cipher, PKCS5padding is more efficient than // PKCS7padding. PKCS7padding can support IOS encryption and // decryption. Cipher cipher = Cipher.getInstance(config.getAlgTransformationName()); // This method can be added in three ways according to the // requirements of encryption algorithm. (1) No third parameter; (2) // the third parameter is SecureRandom; (not available for // AES) (3) uses IVParameterspec. if (config.isRequireIv()) { notNull(iv, "Init algorithm %s cipher Iv is requires", config.getAlgTransformationName()); cipher.init(Cipher.DECRYPT_MODE, _key, iv); } else { cipher.init(Cipher.DECRYPT_MODE, _key); } return new CodecSource(cipher.doFinal(cipherSource.getBytes())); } catch (Exception e) { throw new IllegalStateException(e); } }
Example 6
Source File: DESUtil.java From Encrypt with Apache License 2.0 | 6 votes |
/** * DES���ܷ��� * * @param message * @param key * @return * @throws Exception */ public static String decrypt(String message, String key) throws Exception { byte[] bytesrc = convertHexString(message); byte[] theKey = null; String jqstr = getstrByte(key).substring(0, 8).toUpperCase(); theKey = jqstr.getBytes(ENCODED_ASCII); Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE_CBC); DESKeySpec desKeySpec = new DESKeySpec(theKey); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); IvParameterSpec iv = new IvParameterSpec(theKey); cipher.init(Cipher.DECRYPT_MODE, secretKey, iv); byte[] retByte = cipher.doFinal(bytesrc); return new String(retByte, ENCODED_GB2312); }
Example 7
Source File: PKCS12KeyStoreSpi.java From RipplePower with Apache License 2.0 | 5 votes |
private Cipher createCipher(int mode, char[] password, AlgorithmIdentifier algId) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchProviderException { PBES2Parameters alg = PBES2Parameters.getInstance(algId.getParameters()); PBKDF2Params func = PBKDF2Params.getInstance(alg.getKeyDerivationFunc().getParameters()); AlgorithmIdentifier encScheme = AlgorithmIdentifier.getInstance(alg.getEncryptionScheme()); SecretKeyFactory keyFact = helper.createSecretKeyFactory(alg.getKeyDerivationFunc().getAlgorithm().getId()); SecretKey key; if (func.isDefaultPrf()) { key = keyFact.generateSecret(new PBEKeySpec(password, func.getSalt(), func.getIterationCount().intValue(), keySizeProvider.getKeySize(encScheme))); } else { key = keyFact.generateSecret(new PBKDF2KeySpec(password, func.getSalt(), func.getIterationCount().intValue(), keySizeProvider.getKeySize(encScheme), func.getPrf())); } Cipher cipher = Cipher.getInstance(alg.getEncryptionScheme().getAlgorithm().getId()); AlgorithmIdentifier encryptionAlg = AlgorithmIdentifier.getInstance(alg.getEncryptionScheme()); ASN1Encodable encParams = alg.getEncryptionScheme().getParameters(); if (encParams instanceof ASN1OctetString) { cipher.init(mode, key, new IvParameterSpec(ASN1OctetString.getInstance(encParams).getOctets())); } else { // TODO: at the moment it's just GOST, but... GOST28147Parameters gParams = GOST28147Parameters.getInstance(encParams); cipher.init(mode, key, new GOST28147ParameterSpec(gParams.getEncryptionParamSet(), gParams.getIV())); } return cipher; }
Example 8
Source File: AesGcmEncryptionProvider.java From keycloak with Apache License 2.0 | 5 votes |
private byte[] decryptBytes(byte[] encryptedBytes, byte[] ivBytes, Key aesKey, byte[] aad) throws GeneralSecurityException { Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC"); GCMParameterSpec gcmParams = new GCMParameterSpec(AUTH_TAG_SIZE_BYTE * 8, ivBytes); cipher.init(Cipher.DECRYPT_MODE, aesKey, gcmParams); cipher.updateAAD(aad); return cipher.doFinal(encryptedBytes); }
Example 9
Source File: ProvisioningCipher.java From mollyim-android with GNU General Public License v3.0 | 5 votes |
private byte[] getCiphertext(byte[] key, byte[] message) { try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES")); return Util.join(cipher.getIV(), cipher.doFinal(message)); } catch (NoSuchAlgorithmException | NoSuchPaddingException | java.security.InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { throw new AssertionError(e); } }
Example 10
Source File: Crypto.java From evercam-android with GNU Affero General Public License v3.0 | 5 votes |
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(clear); return encrypted; }
Example 11
Source File: CombinedDecryptor.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 5 votes |
private void init(Key asymKey, byte[] hiddenSecret) throws GeneralSecurityException { Cipher asymCipher = Cipher.getInstance(asymKey.getAlgorithm()); asymCipher.init(Cipher.DECRYPT_MODE, asymKey); SecretKeySpec kspec = new SecretKeySpec(asymCipher.doFinal(hiddenSecret), symAlg); symCipher = Cipher.getInstance(symAlg); symCipher.init(Cipher.DECRYPT_MODE, kspec); }
Example 12
Source File: RSAEncryptDecrypt.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SunMSCAPI"); KeyPair keyPair = generator.generateKeyPair(); Key publicKey = keyPair.getPublic(); Key privateKey = keyPair.getPrivate(); Cipher cipher = null; try { cipher = Cipher.getInstance("RSA", "SunMSCAPI"); } catch (GeneralSecurityException e) { System.out.println("Cipher not supported by provider, skipping..."); return; } cipher.init(Cipher.ENCRYPT_MODE, publicKey); displayBytes("Plaintext data:", PLAINTEXT); byte[] data = cipher.doFinal(PLAINTEXT); displayBytes("Encrypted data:", data); cipher.init(Cipher.DECRYPT_MODE, privateKey); data = cipher.doFinal(data); displayBytes("Decrypted data:", data); }
Example 13
Source File: AesCrypto.java From android-showcase-template with Apache License 2.0 | 5 votes |
/** * Encrypt the given text. * @param keyAlias The alias of the key in the keystore that will be used for the encryption. * @param plainText the text to encrypt * @return the encrypted data. The first 12 bytes will be the IV (initial vector) used for the encryption. * @throws GeneralSecurityException * @throws IOException */ public byte[] encrypt(String keyAlias, byte[] plainText) throws GeneralSecurityException, IOException { SecretKey secretKey = loadOrGenerateSecretKey(keyAlias, true); Cipher cipher = Cipher.getInstance(secureKeyStore.getSupportedAESMode()); cipher.init(Cipher.ENCRYPT_MODE, secretKey); //get the iv that is being used byte[] iv = cipher.getIV(); byte[] encrypted = cipher.doFinal(plainText); GCMEncrypted encryptedData = new GCMEncrypted(iv, encrypted); return encryptedData.toByteArray(); }
Example 14
Source File: ReadWriteSkip.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private Cipher createCipher(int mode) throws GeneralSecurityException { Cipher cipher = Cipher.getInstance(TRANSFORM, PROVIDER); if (mode == Cipher.ENCRYPT_MODE) { cipher.init(Cipher.ENCRYPT_MODE, key); } else { if (encryptCipher != null) { cipher.init(Cipher.DECRYPT_MODE, key, encryptCipher.getParameters()); } else { throw new RuntimeException("Can't create a cipher"); } } cipher.updateAAD(AAD); return cipher; }
Example 15
Source File: GPCrypto.java From openjavacard-tools with GNU Lesser General Public License v3.0 | 5 votes |
private static byte[] mac_aes(Key key, byte[] text, int offset, int length, byte[] iv) { final int macLength = 8; final int blockLength = 16; try { Cipher cipher = Cipher.getInstance(AES_CBC_NOPAD); // pad if required boolean padded = (text.length % blockLength) != 0; byte[] input = Arrays.copyOfRange(text, offset, offset + length); if (padded) { input = pad80(input, blockLength); } // derive padding secrets byte[] L = new byte[blockLength]; cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv)); cipher.update(ZEROES_16, 0, L.length, L, 0); byte[] Lu1 = mac_aes_doubleLu(L); byte[] Lu2 = mac_aes_doubleLu(Lu1); // shadow last block int lastBlock = input.length - blockLength; byte[] Lu = Lu1; if (padded) { Lu = Lu2; } for (int i = 0; i < blockLength; i++) { input[lastBlock + i] ^= Lu[lastBlock + i]; } // perform CBC operation cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv)); byte[] raw = cipher.doFinal(input, 0, input.length); // truncate result and return return Arrays.copyOfRange(raw, 0, macLength); } catch (Exception e) { throw new RuntimeException("MAC computation failed", e); } }
Example 16
Source File: EncryptionUtil.java From lams with GNU General Public License v2.0 | 5 votes |
public byte[] encrypt(byte[] data, SecretKey key) throws Exception { 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 17
Source File: RSAUtils.java From NetworkDisk_Storage with GNU General Public License v2.0 | 5 votes |
/** * <p> * 公钥加密 * </p> * * @param data * 源数据 * @param publicKey * 公钥(BASE64编码) * @return * @throws Exception */ public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception { byte[] keyBytes = Base64Utils.decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); // 对数据加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; }
Example 18
Source File: AESUtils.java From Cangol-appcore with Apache License 2.0 | 4 votes |
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { final SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); final Cipher cipher = Cipher.getInstance("AES"); //AES/CBC/PKCS5Padding cipher.init(Cipher.DECRYPT_MODE, skeySpec); return cipher.doFinal(encrypted); }
Example 19
Source File: TestSymmCiphersNoPad.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
@Override public void main(Provider p) throws Exception { boolean status = true; Random random = new Random(); try { for (int i = 0; i < TEST_LIST.length; i++) { CI currTest = TEST_LIST[i]; System.out.println("===" + currTest.transformation + "==="); try { KeyGenerator kg = KeyGenerator.getInstance(currTest.keyAlgo, p); SecretKey key = kg.generateKey(); Cipher c1 = Cipher.getInstance(currTest.transformation, p); Cipher c2 = Cipher.getInstance(currTest.transformation, "SunJCE"); byte[] plainTxt = new byte[currTest.dataSize]; random.nextBytes(plainTxt); System.out.println("Testing inLen = " + plainTxt.length); c2.init(Cipher.ENCRYPT_MODE, key); AlgorithmParameters params = c2.getParameters(); byte[] answer = c2.doFinal(plainTxt); test(c1, Cipher.ENCRYPT_MODE, key, params, plainTxt, answer); System.out.println("Encryption tests: DONE"); c2.init(Cipher.DECRYPT_MODE, key, params); byte[] answer2 = c2.doFinal(answer); test(c1, Cipher.DECRYPT_MODE, key, params, answer, answer2); System.out.println("Decryption tests: DONE"); } catch (NoSuchAlgorithmException nsae) { System.out.println("Skipping unsupported algorithm: " + nsae); } } } catch (Exception ex) { // print out debug info when exception is encountered if (debugBuf != null) { System.out.println(debugBuf.toString()); } throw ex; } }
Example 20
Source File: GPCrypto.java From GlobalPlatformPro with GNU Lesser General Public License v3.0 | 4 votes |
public static byte[] dek_encrypt_aes(byte[] key, byte[] data) throws GeneralSecurityException { Cipher cipher = Cipher.getInstance(AES_CBC_CIPHER); cipher.init(Cipher.ENCRYPT_MODE, aeskey(key), iv_null_16); return cipher.doFinal(data); }