public String decrypt(final String alias, final byte[] encryptedData, Context appContext) throws UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IOException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { final Cipher cipher = Cipher.getInstance(TRANSFORMATION); String IV = PreferenceHelper.getPrefernceHelperInstace().getString(appContext, "IV", ""); if (null != IV && !IV.isEmpty()) { byte[] encryptionIv = Base64.decode(IV, Base64.DEFAULT); Log.e("Decrypter", "IV : " + IV + " IV size " + encryptionIv.length); final GCMParameterSpec spec = new GCMParameterSpec(128, encryptionIv); cipher.init(Cipher.DECRYPT_MODE, getSecretKey(alias), spec); return new String(cipher.doFinal(encryptedData), "UTF-8"); } else { return "{}"; } }
/** * Compute MGF1 using mgfMD as the message digest. * Note that we combine MGF1 with the XOR operation to reduce data * copying. * * We generate maskLen bytes of MGF1 from the seed and XOR it into * out[] starting at outOfs; */ private void mgf1(byte[] seed, int seedOfs, int seedLen, byte[] out, int outOfs, int maskLen) throws BadPaddingException { byte[] C = new byte[4]; // 32 bit counter byte[] digest = new byte[mgfMd.getDigestLength()]; while (maskLen > 0) { mgfMd.update(seed, seedOfs, seedLen); mgfMd.update(C); try { mgfMd.digest(digest, 0, digest.length); } catch (DigestException e) { // should never happen throw new BadPaddingException(e.toString()); } for (int i = 0; (i < digest.length) && (maskLen > 0); maskLen--) { out[outOfs++] ^= digest[i++]; } if (maskLen > 0) { // increment counter for (int i = C.length - 1; (++C[i] == 0) && (i > 0); i--) { // empty } } } }
@Override protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { byte tmpOut[]; if (debug.DEBUG) log("final (in offset: " + inputOffset + ", len: " + inputLen + ", out offset: " + outputOffset + ")"); tmpOut = wolfCryptFinal(input, inputOffset, inputLen); System.arraycopy(tmpOut, 0, output, outputOffset, tmpOut.length); return tmpOut.length; }
public Key getKey(PrivateKey privatekey) throws MeviusCipherException { try { Cipher c = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "SunJCE"); c.init(Cipher.DECRYPT_MODE, privatekey); /* * DESedeKeySpec desKeySpec = new DESedeKeySpec((byte[]) (convertByte(key, c))); * SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); return * keyFactory.generateSecret(desKeySpec); */ return (Key) convertByte(key, c); } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | ClassNotFoundException | IOException | IllegalBlockSizeException | BadPaddingException e) { e.printStackTrace(); throw new MeviusCipherException(e.getMessage()); } }
public static String decrypt(String str) { if (str == null) return null; Cipher cipher; try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ips.getBytes("UTF-8"))); byte[] byteStr = Base64.decodeBase64(str.getBytes()); return new String(cipher.doFinal(byteStr), "UTF-8"); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
/** * Encrypt or decrypt byte[] data using the specified key */ private static byte[] cipherOperation(int opMode, Key key, byte[] data) { try { return createTheCipherInstance(opMode, key.getAlgorithm(), key).doFinal(data); } catch (IllegalBlockSizeException illegalblocksizeexception) { illegalblocksizeexception.printStackTrace(); } catch (BadPaddingException badpaddingexception) { badpaddingexception.printStackTrace(); } LOGGER.error("Cipher data failed!"); return null; }
public static void main(final String[] argv) throws IOException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, ClassNotFoundException, GeneralSecurityException { if(argv.length >= 2) { ip = argv[0]; port = Integer.parseInt(argv[1]); } else { Logger.getLogger(Main.class.getName()).log(Level.INFO, "Default ip and port were applied."); ip = Parameters.RELAY_IP; port = Parameters.RELAY_PORT_WALLET_LISTENER; } // Init connection with relay try { RelayConnection.getInstance(); } catch(IOException ex) { Logger.getLogger(Main.class.getName()).severe(ex.getMessage()); return; } new ClientApplication(); }
public static void main(String[] args) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { byte[] plainText = new byte[801]; // Initialization RandomFactory.getRandom().nextBytes(plainText); Cipher ci = new NullCipher(); // Encryption byte[] cipherText = new byte[ci.getOutputSize(plainText.length)]; int offset = ci.update(plainText, 0, plainText.length, cipherText, 0); ci.doFinal(cipherText, offset); // Decryption byte[] recoveredText = new byte[ci.getOutputSize(cipherText.length)]; int len = ci.doFinal(cipherText, 0, cipherText.length, recoveredText); // Comparison if (len != plainText.length || !TestUtilities.equalsBlock(plainText, cipherText, len) || !TestUtilities.equalsBlock(plainText, recoveredText, len)) { throw new RuntimeException( "Test failed because plainText not equal to cipherText and revoveredText"); } }
protected byte[] engineDoFinal( byte[] input, int inputOffset, int inputLen) throws BadPaddingException, IllegalBlockSizeException { if (inputLen != 0) { byte[] out = engineUpdate(input, inputOffset, inputLen); cipher.reset(); return out; } cipher.reset(); return new byte[0]; }
public byte[] encrypt(int version, byte[] data) { CryptVersion cryptVersion = cryptVersion(version); try { int cryptedLength = cryptVersion.encryptedLength.apply(data.length); byte[] result = new byte[cryptedLength + cryptVersion.saltLength + 1]; result[0] = toSignedByte(version); byte[] random = urandomBytes(cryptVersion.saltLength); IvParameterSpec iv_spec = new IvParameterSpec(random); System.arraycopy(random, 0, result, 1, cryptVersion.saltLength); Cipher cipher = cipher(cryptVersion.cipher); cipher.init(Cipher.ENCRYPT_MODE, cryptVersion.key, iv_spec); int len = cipher.doFinal(data, 0, data.length, result, cryptVersion.saltLength + 1); if (len < cryptedLength) LOG.info("len was " + len + " instead of " + cryptedLength); return result; } catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) { throw new RuntimeException("JCE exception caught while encrypting with version " + version, e); } }
protected byte[] engineWrap( Key key) throws IllegalBlockSizeException, InvalidKeyException { byte[] encoded = key.getEncoded(); if (encoded == null) { throw new InvalidKeyException("Cannot wrap key, null encoding."); } try { if (wrapEngine == null) { return engineDoFinal(encoded, 0, encoded.length); } else { return wrapEngine.wrap(encoded, 0, encoded.length); } } catch (BadPaddingException e) { throw new IllegalBlockSizeException(e.getMessage()); } }
/** * Wrap a key. * * @param key the key to be wrapped. * * @return the wrapped key. * * @exception IllegalBlockSizeException if this cipher is a block * cipher, no padding has been requested, and the length of the * encoding of the key to be wrapped is not a * multiple of the block size. * * @exception InvalidKeyException if it is impossible or unsafe to * wrap the key with this cipher (e.g., a hardware protected key is * being passed to a software only cipher). */ protected final byte[] engineWrap(Key key) throws IllegalBlockSizeException, InvalidKeyException { byte[] result = null; try { byte[] encodedKey = key.getEncoded(); if ((encodedKey == null) || (encodedKey.length == 0)) { throw new InvalidKeyException("Cannot get an encoding of " + "the key to be wrapped"); } result = engineDoFinal(encodedKey, 0, encodedKey.length); } catch (BadPaddingException e) { // Should never happen } return result; }
protected byte[] engineDoFinal( byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { if (inputLen != 0) { buffer.write(input, inputOffset, inputLen); } try { byte[] buf = buffer.toByteArray(); buffer.reset(); return cipher.processBlock(buf, 0, buf.length); } catch (InvalidCipherTextException e) { throw new BadPaddingException(e.getMessage()); } }
protected byte[] engineDoFinal( byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { cipher.processBytes(input, inputOffset, inputLen); try { return cipher.doFinal(); } catch (InvalidCipherTextException e) { throw new BadPaddingException(e.getMessage()); } }
public byte[] decrypt(byte[] data) { int version = fromSignedByte(data[0]); CryptVersion cryptVersion = cryptVersion(version); try { byte[] random = new byte[cryptVersion.saltLength]; System.arraycopy(data, 1, random, 0, cryptVersion.saltLength); IvParameterSpec iv_spec = new IvParameterSpec(random); Cipher cipher = cipher(cryptVersions[version].cipher); cipher.init(Cipher.DECRYPT_MODE, cryptVersions[version].key, iv_spec); return cipher.doFinal(data, cryptVersion.saltLength + 1, data.length - cryptVersion.saltLength - 1); } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) { throw new RuntimeException("JCE exception caught while decrypting with version " + version, e); } }
/** * Wrap a key. * * @param key the key to be wrapped. * * @return the wrapped key. * * @exception IllegalBlockSizeException if this cipher is a block * cipher, no padding has been requested, and the length of the * encoding of the key to be wrapped is not a * multiple of the block size. * * @exception InvalidKeyException if it is impossible or unsafe to * wrap the key with this cipher (e.g., a hardware protected key is * being passed to a software only cipher). */ byte[] wrap(Key key) throws IllegalBlockSizeException, InvalidKeyException { byte[] result = null; try { byte[] encodedKey = key.getEncoded(); if ((encodedKey == null) || (encodedKey.length == 0)) { throw new InvalidKeyException("Cannot get an encoding of " + "the key to be wrapped"); } result = doFinal(encodedKey, 0, encodedKey.length); } catch (BadPaddingException e) { // Should never happen } return result; }
public String decrypt(String str) { Cipher cipher; try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ips.getBytes("UTF-8"))); byte[] byteStr = Base64.decodeBase64(str.getBytes()); String Str = new String(cipher.doFinal(byteStr), "UTF-8"); return Str; } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) { } return null; }
public String encrypt(String plainText, String key) { String encodedString = ""; try { byte[] plainTextbytes = plainText.getBytes(characterEncoding); byte[] keyBytes = getKeyBytes(KEY_PREFIX + "" + key); encodedString = Base64.getEncoder().encodeToString(encrypt(plainTextbytes, keyBytes, keyBytes)); } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return encodedString; }
public String encryptStr(String str) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException { byte[] encryptArray = encrypt(str); StringBuffer strBuf = new StringBuffer(); for(byte e : encryptArray) { strBuf.append(intToChar((e >> 4) & 0x0f)); strBuf.append(intToChar(e & 0x0f)); } return strBuf.toString(); }
public static byte[] streamEncrypt(EncFSVolume volume, byte[] ivSeed, byte[] data) throws EncFSUnsupportedException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { return streamEncrypt(volume.getStreamCipher(), volume.getMAC(), volume.getKey(), volume.getIV(), ivSeed, data); }
public static byte[] decrypt(SecretKey secretKey, IvParameterSpec iv, byte[] cipherText) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { Cipher cipher = Cipher.getInstance(CRYPT_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKey, iv); return cipher.doFinal(cipherText); }
private static byte[] cipher(byte[] data, int mode, Context ctx) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { KeyManager km = new KeyManager(); SecretKeySpec sks = new SecretKeySpec(km.getId(ctx), engine); IvParameterSpec iv = new IvParameterSpec(km.getIv(ctx)); Cipher c = Cipher.getInstance(crypto); c.init(mode, sks, iv); return c.doFinal(data); }
/** * Parse the msg into a BigInteger and check against the modulus n. */ private static BigInteger parseMsg(byte[] msg, BigInteger n) throws BadPaddingException { BigInteger m = new BigInteger(1, msg); if (m.compareTo(n) >= 0) { throw new BadPaddingException("Message is larger than modulus"); } return m; }
static String decrypt(String data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { Key key = generateKey(); Cipher cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.DECRYPT_MODE, key); byte[] decodedData = decode(data, 16); return new String(cipher.doFinal(decodedData)); }
/** * Creates a KeyPair from a WalletInformation. * * The private key is decrypted thanks to the password. * @param userPassword the user-selected password used to decrypt the private key * @param walletInformation the WalletInformation containing the encrypted private key * @return a KeyPair with the keys contained in walletInformation * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws IllegalBlockSizeException */ public static KeyPair keyPairFromWalletInformation(final char[] userPassword, WalletInformation walletInformation) throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException { // Retrieve wallet information stored final byte[] salt = walletInformation.getSalt(); final byte[] iv = walletInformation.getIv(); final byte[] encryptedPrivateKey = walletInformation.getEncryptedPrivateKey(); final byte[] publicKeyBytes = walletInformation.getPublicKey(); final SecretKey decryptionKey = Cryptography.computeSecretKey(userPassword, salt); // Decrypt the private key with the decryption key generated from the user password // Initialize a cipher to the decryption mode with the decryptionKey cipher.init(Cipher.DECRYPT_MODE, decryptionKey, new IvParameterSpec(iv)); // Decrypt the private key KeyPair keyPair; try { final byte[] privateKeyBytes = cipher.doFinal(encryptedPrivateKey); // Create a PairKey with the encoded public and private keys keyPair = Cryptography.createKeyPairFromEncodedKeys(publicKeyBytes, privateKeyBytes); // Verify the private key generated by the password entered by the user if (! Cryptography.verifyPrivateKey(keyPair)) return null; } catch (BadPaddingException e) { return null; } return keyPair; }
public static String encryptAES256PKCS7Padding(String key, String src) throws NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException { Cipher cipher = Cipher.getInstance(ALGORITHM_ENCODING); cipher.init(Cipher.ENCRYPT_MODE, generateKeyAES256(key), new IvParameterSpec(new byte[cipher.getBlockSize()])); return Base64.encodeBytes(cipher.doFinal(src.getBytes())); }
public static String decryptAES256PKCS7Padding(String key, String src) throws NoSuchPaddingException, NoSuchAlgorithmException, IOException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { Cipher cipher = Cipher.getInstance(ALGORITHM_ENCODING); cipher.init(Cipher.DECRYPT_MODE, generateKeyAES256(key), new IvParameterSpec(new byte[cipher.getBlockSize()])); return new String(cipher.doFinal(Base64.decode(src))); }
public static String encryptAES128PKCS5Padding(String key, String src) throws NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException { Cipher cipher = Cipher.getInstance(ALGORITHM_ENCODING); cipher.init(Cipher.ENCRYPT_MODE, generateKeyAES128(key), new IvParameterSpec(new byte[cipher.getBlockSize()])); return Base64.encodeBytes(cipher.doFinal(src.getBytes())); }
/** * 解密方法 * * @param rawKeyData * @param encryptedData * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws InvalidKeySpecException */ public static String decrypt(byte rawKeyData[], byte[] encryptedData) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); // 从原始密匙数据创建一个DESKeySpec对象 DESKeySpec dks = new DESKeySpec(rawKeyData); // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks); // Cipher对象实际完成解密操作 Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, key, sr); // 正式执行解密操作 byte decryptedData[] = cipher.doFinal(encryptedData); System.out.println("解密后===>" + new String(decryptedData)); return new String(decryptedData); }
public int engineDoFinal( byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws IllegalBlockSizeException, BadPaddingException { if (inputLen != 0) { buffer.write(input, inputOffset, inputLen); } try { byte[] buf = buffer.toByteArray(); buffer.reset(); buf = cipher.processBlock(buf, 0, buf.length); System.arraycopy(buf, 0, output, outputOffset, buf.length); return buf.length; } catch (InvalidCipherTextException e) { throw new BadPaddingException(e.getMessage()); } }
public static String decryptAES128PKCS7Padding(String key, String src) throws NoSuchPaddingException, NoSuchAlgorithmException, IOException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { Cipher cipher = Cipher.getInstance(ALGORITHM_ENCODING); cipher.init(Cipher.DECRYPT_MODE, generateKeyAES128(key), new IvParameterSpec(new byte[cipher.getBlockSize()])); return new String(cipher.doFinal(Base64.decode(src))); }
@Test public void encryptionIsCorrect() throws NoSuchPaddingException, UnsupportedEncodingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException { String value = "dummy test"; String encoded = new SecureString(KEY, value).encoded(); assertNotEquals(value, encoded); }
@Test public void decryptionIsCorrect() throws NoSuchPaddingException, IOException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException { String value = "dummy test"; String decoded = new SecureString(KEY, value).decoded(); assertEquals(value, decoded); }
@Test public void equalsIsCorrect() throws NoSuchPaddingException, IOException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException { SecureString secureString1 = new SecureString(KEY, "dummy test"); SecureString secureString2 = new SecureString(KEY, "dummy test"); assertTrue(secureString1.isEqualTo(secureString2)); }
public static String cipherPassword(String password, String hash, RSAPublicKey rsaPublicKey) throws InvalidKeyException { try { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey); return new String( Base64.getEncoder().encode( cipher.doFinal((hash + password).getBytes()) ) ); } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) { throw new Error(e); } }
public String encrypt(final String plainText, final String password) { if (this.cipher == null) { initWithPassword(password); } try { cipher.init(Cipher.ENCRYPT_MODE, key, spec); byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8")); return new String(Base64.encode(encrypted), "UTF-8"); } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) { throw new RuntimeException(e); } }