Java Code Examples for javax.crypto.Cipher#doFinal()
The following examples show how to use
javax.crypto.Cipher#doFinal() .
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: RSAEncryptDecrypt.java From AndroidEncryptionExample with MIT License | 6 votes |
/** * main RSA decrypt method * * @param enc encrypted text you want to dcrypt * @param privateKey private key to use for decryption * @return plain text */ public static byte[] decryptRSA(byte[] enc, PrivateKey privateKey) { byte[] plain = null; try { Cipher cipher = Cipher.getInstance(RSA); cipher.init(Cipher.DECRYPT_MODE, privateKey); plain = cipher.doFinal(enc); } //no need to catch 4 different exceptions catch (Exception e) { Log.e(RSAEncryptDecrypt.class.getName(), e.getMessage(), e); throw new RuntimeException(e); } return plain; }
Example 2
Source File: CFDv3Debugger.java From factura-electronica with Apache License 2.0 | 6 votes |
private void dumpDigests() throws Exception { System.err.println(cfd.getCadenaOriginal()); String certStr = cfd.document.getCertificado(); Base64 b64 = new Base64(); byte[] cbs = b64.decode(certStr); X509Certificate cert = (X509Certificate) KeyLoaderFactory.createInstance( KeyLoaderEnumeration.PUBLIC_KEY_LOADER, new ByteArrayInputStream(cbs)).getKey(); cert.checkValidity(); String sigStr = cfd.document.getSello(); byte[] signature = b64.decode(sigStr); CFDv3.dump("Digestion firmada", signature, System.err); Cipher dec = Cipher.getInstance("RSA"); dec.init(Cipher.DECRYPT_MODE, cert); byte[] result = dec.doFinal(signature); CFDv3.dump("Digestion decriptada", result, System.err); ASN1InputStream aIn = new ASN1InputStream(result); ASN1Sequence seq = (ASN1Sequence) aIn.readObject(); ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1); CFDv3.dump("Sello", sigHash.getOctets(), System.err); }
Example 3
Source File: DesUtil.java From javabase with Apache License 2.0 | 6 votes |
/** * 带向量的解密 * @param str * @param secretKey * @param iv * @return * @throws Exception */ public static String decrypt(String str, String secretKey, byte[] iv) throws Exception { if (str == null || "".equals(str)) { return str; } String str1 = URLDecoder.decode(str, "UTF-8"); byte str2[] = Base64.decodeBase64(str1.getBytes()); IvParameterSpec zeroIv = new IvParameterSpec(iv); SecretKeySpec key = new SecretKeySpec(secretKey.getBytes("UTF-8"), "DES"); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key, zeroIv); byte[] str3 = cipher.doFinal(str2); String res = str; if (str3 != null) { res = new String(str3, "UTF-8"); } return res; }
Example 4
Source File: VaultManagerImpl.java From cia with Apache License 2.0 | 6 votes |
@Override public String decryptValue(final String password, final String userId, final String value) { if (password != null && userId != null && value!=null) { try { final Key buildKey = buildKey(userId, password); final ByteBuffer byteBuffer = ByteBuffer.wrap(Hex.decode(value.getBytes(StandardCharsets.UTF_8))); final int ivLength = byteBuffer.getInt(); final byte[] iv = new byte[ivLength]; byteBuffer.get(iv); final byte[] cipherText = new byte[byteBuffer.remaining()]; byteBuffer.get(cipherText); final Cipher cipher = Cipher.getInstance(AES_GCM_NO_PADDING); cipher.init(Cipher.DECRYPT_MODE, buildKey, new GCMParameterSpec(TAG_BIT_LENGTH, iv)); return new String(cipher.doFinal(cipherText),StandardCharsets.UTF_8); } catch (final GeneralSecurityException e) { LOGGER.error(DECRYPT_VALUE,e); return null; } } else { return null; } }
Example 5
Source File: AESUtils.java From liteflow with Apache License 2.0 | 6 votes |
/** * CBC分组密码模式 PKCS7Padding填充模式 使用加密混淆向量iv * @param content 加密内容 * @param key 加密密钥 * @param iv 加密混淆向量iv * @return */ public String decryptWithDiyIV(String content, String key, String iv) { byte[] keyByte = Base64.decodeBase64(key); byte[] ivByte = Base64.decodeBase64(iv); SecretKeySpec secretKeySpec = new SecretKeySpec(keyByte, "AES"); try { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC"); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(ivByte)); byte[] contentByte = Base64.decodeBase64(content.getBytes(Constants.DEFAULT_CHARSET)); byte[] decrypted = cipher.doFinal(contentByte); return new String(decrypted); } catch (Exception e) { logger.error("解密过程中出错!content:{},key:{},iv:{}", content, key, iv, e); } return ""; }
Example 6
Source File: TestDelegatedKey.java From aws-dynamodb-encryption-java with Apache License 2.0 | 6 votes |
@Override public byte[] encrypt(byte[] plainText, byte[] additionalAssociatedData, String algorithm) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException { Cipher cipher = Cipher.getInstance(extractAlgorithm(algorithm)); cipher.init(Cipher.ENCRYPT_MODE, realKey); byte[] iv = cipher.getIV(); byte[] result = new byte[cipher.getOutputSize(plainText.length) + iv.length + 1]; result[0] = (byte) iv.length; System.arraycopy(iv, 0, result, 1, iv.length); try { cipher.doFinal(plainText, 0, plainText.length, result, iv.length + 1); } catch (ShortBufferException e) { throw new RuntimeException(e); } return result; }
Example 7
Source File: RsaUtil.java From base-admin with MIT License | 6 votes |
/** * 分段进行加密、解密操作 */ private static byte[] encryptAndDecryptOfSubsection(byte[] data, Cipher cipher, int encryptBlock) throws Exception { int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > encryptBlock) { cache = cipher.doFinal(data, offSet, encryptBlock); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * encryptBlock; } out.close(); return out.toByteArray(); }
Example 8
Source File: AESEncrypt.java From ans-android-sdk with GNU General Public License v3.0 | 5 votes |
/** * 加密 */ public static String ECBEncrypt(String content, String password) { try { SecretKeySpec secretKeySpec = new SecretKeySpec(password.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] result = cipher.doFinal(content.getBytes()); return toHex(result); } catch (Throwable e) { } return null; }
Example 9
Source File: PasswordCrypt.java From ermasterr with Apache License 2.0 | 5 votes |
public static String encrypt(final String password) throws Exception { final Key key = getKey(); final Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key); final byte[] input = password.getBytes(); final byte[] encrypted = cipher.doFinal(input); return new String(Base64.encodeBase64(encrypted)); }
Example 10
Source File: SSOSymmetrical.java From kisso with Apache License 2.0 | 5 votes |
/** * 加密 * * @param algorithm * @param data * @param key * @return */ public byte[] encrypt(Algorithm algorithm, byte[] data, String key) { try { Cipher cipher = Cipher.getInstance(algorithm.toString()); cipher.init(Cipher.ENCRYPT_MODE, this.toKey(algorithm, key)); return cipher.doFinal(data); } catch (Exception e) { log.error("Encrypt setKey is exception."); throw new KissoException(e); } }
Example 11
Source File: CryptUtil.java From nano-framework with Apache License 2.0 | 5 votes |
/** * 使用密钥对密文进行解密,并返回明文. * * @param data 密文 * @param passwd 密钥 * @return 明文 */ public static String decrypt(final String data, final String passwd) { final String password; if (passwd == null || passwd.trim().length() == 0) { password = DEFAULT_PASSWORD; } else { password = passwd; } final StringBuilder cryptBuilder = new StringBuilder(data.substring(0, data.length() - 1)); final int len = Integer.parseInt(data.substring(data.length() - 1)); if (len > 0) { for (int idx = 0; idx < len; idx++) { cryptBuilder.append('='); } } final String cryptData = cryptBuilder.toString(); try { final byte[] content = parseHexStr2Byte(new String(Base64.getDecoder().decode(cryptData.getBytes()))); final KeyGenerator kgen = KeyGenerator.getInstance(CRYPT_MODE); final SecureRandom random = SecureRandom.getInstance(SHA_MODE); random.setSeed(password.getBytes(UTF8)); kgen.init(CRYPT_KEY_SIZE, random); final SecretKey secretKey = kgen.generateKey(); final byte[] enCodeFormat = secretKey.getEncoded(); final SecretKeySpec key = new SecretKeySpec(enCodeFormat, CRYPT_MODE); final Cipher cipher = Cipher.getInstance(CRYPT_MODE);//创建密码器 cipher.init(Cipher.DECRYPT_MODE, key);//初始化 final byte[] result = cipher.doFinal(content);//解密 return new String(result); } catch (final Exception e) { throw new DecryptException(e.getMessage(), e); } }
Example 12
Source File: TextPKCS5PaddingTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { Provider provider = Security.getProvider("SunJCE"); if (provider == null) { throw new RuntimeException("SunJCE provider not exist"); } // generate no-padding cipher with secret key Cipher c = Cipher.getInstance("DES/CBC/NoPadding", provider); KeyGenerator kgen = KeyGenerator.getInstance("DES", provider); SecretKey skey = kgen.generateKey(); // this is the improperly padded plaintext c.init(Cipher.ENCRYPT_MODE, skey); // encrypt plaintext byte[] cipher = c.doFinal(PLAIN_TEXT); AlgorithmParameters params = c.getParameters(); // generate cipher that enforces PKCS5 padding c = Cipher.getInstance("DES/CBC/PKCS5Padding", provider); c.init(Cipher.DECRYPT_MODE, skey, params); try { c.doFinal(cipher); throw new RuntimeException( "ERROR: Expected BadPaddingException not thrown"); } catch (BadPaddingException expected) { out.println("Expected BadPaddingException thrown"); } }
Example 13
Source File: CipherStreamClose.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
public static Object blockDecrypt(byte[] data, SecretKey key) throws Exception { Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding"); c.init(Cipher.DECRYPT_MODE, key); data = c.doFinal(data); try (ByteArrayInputStream bis = new ByteArrayInputStream(data)) { try (ObjectInputStream ois = new ObjectInputStream(bis)) { return ois.readObject(); } } }
Example 14
Source File: GCMReceiver.java From tapchat-android with Apache License 2.0 | 5 votes |
private byte[] decrypt(byte[] cipherText, byte[] key, byte[] iv) throws Exception { SecretKey keySpec = new SecretKeySpec(key, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(iv); Cipher aes = Cipher.getInstance("AES/CBC/PKCS5Padding"); aes.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); return aes.doFinal(cipherText); }
Example 15
Source File: AlipaySignature.java From pay with Apache License 2.0 | 5 votes |
/** * 私钥解密 * * @param content 待解密内容 * @param privateKey 私钥 * @param charset 字符集,如UTF-8, GBK, GB2312 * @return 明文内容 * @throws AlipayApiException 支付异常 */ public static String rsaDecrypt(String content, String privateKey, String charset) throws AlipayApiException { try { PrivateKey priKey = getPrivateKeyFromPKCS8(AlipayConstants.SIGN_TYPE_RSA, new ByteArrayInputStream(privateKey.getBytes())); Cipher cipher = Cipher.getInstance(AlipayConstants.SIGN_TYPE_RSA); cipher.init(Cipher.DECRYPT_MODE, priKey); byte[] encryptedData = StringUtils.isEmpty(charset) ? Base64.decodeBase64(content.getBytes()) : Base64.decodeBase64(content.getBytes(charset)); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return StringUtils.isEmpty(charset) ? new String(decryptedData) : new String(decryptedData, charset); } catch (Exception e) { throw new AlipayApiException("EncodeContent = " + content + ",charset = " + charset, e); } }
Example 16
Source File: SecureString.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
private void encrypt(byte[] cleartext) throws GeneralSecurityException { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(getMetaPassword())); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(1, key, new PBEParameterSpec(this.salt, 20)); this.cipherBytes = pbeCipher.doFinal(cleartext); }
Example 17
Source File: RSACoder.java From bird-java with MIT License | 5 votes |
/** * 公钥加密 * * @param data 待加密数据 * @param key 公钥 * @return byte[] 加密数据 * @throws Exception */ public static byte[] encryptByPublicKey(byte[] data, byte[] key) throws Exception { // 取得公钥 X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PublicKey publicKey = keyFactory.generatePublic(x509KeySpec); // 对数据加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(data); }
Example 18
Source File: MySQLDbService.java From ecs-sync with Apache License 2.0 | 5 votes |
private static String decryptPassword(String encPassword) { try { Cipher decryptCipher = Cipher.getInstance("AES"); decryptCipher.init(Cipher.DECRYPT_MODE, cipherKey); return new String(decryptCipher.doFinal(DatatypeConverter.parseBase64Binary(encPassword))); } catch (GeneralSecurityException e) { throw new RuntimeException("unable to decrypt password: " + e.toString(), e); } }
Example 19
Source File: Crypto.java From jsqsh with Apache License 2.0 | 4 votes |
/** * Decrypt a value using a provided key. * * @param key The key to use for encryption. The encryption * algorithm used is Blowfish so the key should conform * to what Blowfish expects. * @param value The value to be decrypted. * @return The decrypted value. */ public static byte[] decrypt(byte []key, byte []value) { if (key == null) { key = DEFAULT_KEY; } try { SecretKeySpec skeySpec = new SecretKeySpec(key, "Blowfish"); Cipher cipher = Cipher.getInstance("Blowfish"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); return cipher.doFinal(value); } catch (Exception e) { return value; } }
Example 20
Source File: AESTest2.java From axelor-open-suite with GNU Affero General Public License v3.0 | 4 votes |
@Test public void test() throws Exception { String message = "Hello World"; byte[] CRYPTO_KEY_EXT = { (byte) 0xEF, (byte) 0xA4, (byte) 0xA8, (byte) 0x04, (byte) 0xB6, (byte) 0x14, (byte) 0x3E, (byte) 0xF7, (byte) 0xCE, (byte) 0xD2, (byte) 0xA2, (byte) 0x78, (byte) 0x10, (byte) 0xB2, (byte) 0x2B, (byte) 0x43 }; byte[] CRYPTO_IV_EXT = { (byte) 0xCC, (byte) 0xBA, (byte) 0xAC, (byte) 0x54, (byte) 0xA2, (byte) 0x35, (byte) 0x56, (byte) 0x9E, (byte) 0xEA, (byte) 0x36, (byte) 0xAB, (byte) 0x31, (byte) 0xBC, (byte) 0xB4, (byte) 0x34, (byte) 0x31 }; byte[] sessionKey = CRYPTO_KEY_EXT; // Where you get this from is beyond // the scope of this post byte[] iv = CRYPTO_IV_EXT; // Ditto byte[] plaintext = message.getBytes("UTF8"); // Whatever you want to // encrypt/decrypt Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // You can use ENCRYPT_MODE or DECRYPT_MODE cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(sessionKey, "AES"), new IvParameterSpec(iv)); byte[] ciphertext = cipher.doFinal(plaintext); Cipher cipher2 = Cipher.getInstance("AES/CBC/PKCS5Padding"); // You can use DECRYPT_MODE or DECRYPT_MODE cipher2.init( Cipher.DECRYPT_MODE, new SecretKeySpec(sessionKey, "AES"), new IvParameterSpec(iv)); byte[] roundTriptext = cipher2.doFinal(ciphertext); String roundTrip = new String(roundTriptext, "UTF8"); Assert.assertEquals(message, roundTrip); }