Java Examples for javax.crypto.spec.IvParameterSpec
The following java examples will help you to understand the usage of javax.crypto.spec.IvParameterSpec. These source code samples are taken from different open source projects.
Example 1
| Project: find-sec-bugs-master File: ConstantIv.java View source code |
public static void encryptIvNotInitialize1(String message) throws Exception {
//Oups. Static
byte[] iv = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
//IV
IvParameterSpec ivSpec = new IvParameterSpec(iv);
//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 2
| Project: CupCarbon-master File: Blowfish.java View source code |
public String encrypt() throws Exception {
byte[] byteKey = key.getBytes();
String IV = "12345678";
// Create new Blowfish cipher
SecretKeySpec keySpec = new SecretKeySpec(byteKey, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, new javax.crypto.spec.IvParameterSpec(IV.getBytes()));
byte[] encoding = cipher.doFinal(message.getBytes());
return bytesToHex(encoding);
}Example 3
| Project: conceal-master File: BetterCipherInputStreamTest.java View source code |
@Before
public void setUp() throws Exception {
mData = new byte[1024 * 1024];
mCipheredData = new byte[mData.length];
byte[] iv = new byte[16];
byte[] key = new byte[16];
mKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance(CIPHER_ALG);
mIV = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, mKey, mIV);
mCipheredData = cipher.update(mData, 0, mData.length);
cipher.doFinal();
}Example 4
| Project: D3Xmpp-master File: DES.java View source code |
public static String encryptDES(String encryptString, String encryptKey) throws Exception {
IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
return android.util.Base64.encodeToString(encryptedData, android.util.Base64.NO_WRAP);
}Example 5
| Project: haox-master File: DesProvider.java View source code |
@Override
protected void doEncrypt(byte[] input, byte[] key, byte[] cipherState, boolean encrypt) throws KrbException {
Cipher cipher = null;
try {
cipher = Cipher.getInstance("DES/CBC/NoPadding");
} catch (GeneralSecurityException e) {
throw new KrbException("Failed to init cipher", e);
}
IvParameterSpec params = new IvParameterSpec(cipherState);
SecretKeySpec skSpec = new SecretKeySpec(key, "DES");
try {
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey sk = (SecretKey) skSpec;
cipher.init(encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, sk, params);
byte[] output = cipher.doFinal(input);
System.arraycopy(output, 0, input, 0, output.length);
} catch (GeneralSecurityException e) {
KrbException ke = new KrbException(e.getMessage());
ke.initCause(e);
throw ke;
}
}Example 6
| Project: andbase2x-master File: AbAes.java View source code |
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
//Cipher cipher = Cipher.getInstance("AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}Example 7
| Project: any-video-master File: AesUtils.java View source code |
/**
* 使用AES 算法 åŠ å¯†ï¼Œé»˜è®¤æ¨¡å¼? AES/CBC/PKCS5Padding
*/
public static String encrypt(String str, String iv, String pass) {
try {
Cipher cipher = Cipher.getInstance(TYPE);
SecretKey secretKey = new SecretKeySpec(pass.getBytes(), KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv.getBytes()));
byte[] encrypt = cipher.doFinal(str.getBytes());
return Base64.getEncoder().encodeToString(encrypt);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
return null;
}Example 8
| Project: atlas-lb-master File: PGPPBEEncryptedData.java View source code |
/**
* Return the decrypted input stream, using the passed in passPhrase.
*
* @param passPhrase
* @param provider
* @return InputStream
* @throws PGPException
*/
public InputStream getDataStream(char[] passPhrase, Provider provider) throws PGPException {
try {
int keyAlgorithm = keyData.getEncAlgorithm();
SecretKey key = PGPUtil.makeKeyFromPassPhrase(keyAlgorithm, keyData.getS2K(), passPhrase, provider);
byte[] secKeyData = keyData.getSecKeyData();
if (secKeyData != null && secKeyData.length > 0) {
Cipher keyCipher = Cipher.getInstance(PGPUtil.getSymmetricCipherName(keyAlgorithm) + "/CFB/NoPadding", provider);
keyCipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[keyCipher.getBlockSize()]));
byte[] keyBytes = keyCipher.doFinal(secKeyData);
keyAlgorithm = keyBytes[0];
key = new SecretKeySpec(keyBytes, 1, keyBytes.length - 1, PGPUtil.getSymmetricCipherName(keyAlgorithm));
}
Cipher c = createStreamCipher(keyAlgorithm, provider);
byte[] iv = new byte[c.getBlockSize()];
c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
encStream = new BCPGInputStream(new CipherInputStream(encData.getInputStream(), c));
if (encData instanceof SymmetricEncIntegrityPacket) {
truncStream = new TruncatedStream(encStream);
String digestName = PGPUtil.getDigestName(HashAlgorithmTags.SHA1);
MessageDigest digest = MessageDigest.getInstance(digestName, provider);
encStream = new DigestInputStream(truncStream, digest);
}
for (int i = 0; i != iv.length; i++) {
int ch = encStream.read();
if (ch < 0) {
throw new EOFException("unexpected end of stream.");
}
iv[i] = (byte) ch;
}
int v1 = encStream.read();
int v2 = encStream.read();
if (v1 < 0 || v2 < 0) {
throw new EOFException("unexpected end of stream.");
}
// Note: the oracle attack on "quick check" bytes is not deemed
// a security risk for PBE (see PGPPublicKeyEncryptedData)
boolean repeatCheckPassed = iv[iv.length - 2] == (byte) v1 && iv[iv.length - 1] == (byte) v2;
// Note: some versions of PGP appear to produce 0 for the extra
// bytes rather than repeating the two previous bytes
boolean zeroesCheckPassed = v1 == 0 && v2 == 0;
if (!repeatCheckPassed && !zeroesCheckPassed) {
throw new PGPDataValidationException("data check failed.");
}
return encStream;
} catch (PGPException e) {
throw e;
} catch (Exception e) {
throw new PGPException("Exception creating cipher", e);
}
}Example 9
| Project: audit-master File: MainActivity.java View source code |
private //固定密钥
String cipher() {
try {
SecretKeySpec securekey = new // 使用
SecretKeySpec(// 使用
"0123456789abcdef".getBytes(), // 使用
"AES");
// 创建密ç ?器
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding ");
SecureRandom random = new SecureRandom();
byte[] iv = new byte[16];
random.nextBytes(iv);
cipher.init(Cipher.ENCRYPT_MODE, securekey, new IvParameterSpec(iv));
byte[] byteContent = plaintext.getText().toString().getBytes("utf-8");
byte[] result = cipher.doFinal(byteContent);
return parseByte2HexStr(result);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}Example 10
| Project: bc-java-master File: JceAEADCipherImpl.java View source code |
private static Constructor<AlgorithmParameterSpec> initSpecConstructor() {
try {
Class<AlgorithmParameterSpec> clazz = (Class<AlgorithmParameterSpec>) Class.forName("javax.crypto.spec.GCMParameterSpec", true, IvParameterSpec.class.getClassLoader());
return clazz.getConstructor(int.class, byte[].class);
} catch (Exception ignore) {
return null;
}
}Example 11
| Project: cloudstore-master File: SignedAuthTokenDecrypter.java View source code |
public byte[] decrypt(final EncryptedSignedAuthToken encryptedSignedAuthToken) {
AssertUtil.assertNotNull(encryptedSignedAuthToken, "encryptedSignedAuthToken");
AssertUtil.assertNotNull(encryptedSignedAuthToken.getEncryptedSignedAuthTokenData(), "encryptedSignedAuthToken.encryptedSignedAuthTokenData");
AssertUtil.assertNotNull(encryptedSignedAuthToken.getEncryptedSymmetricKey(), "encryptedSignedAuthToken.encryptedSymmetricKey");
try {
final Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA1ANDMGF1PADDING");
asymCipher.init(Cipher.DECRYPT_MODE, privateKey);
final byte[] symKey = asymCipher.doFinal(encryptedSignedAuthToken.getEncryptedSymmetricKey());
final Cipher symCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
symCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(symKey, "AES"), new IvParameterSpec(encryptedSignedAuthToken.getEncryptedSignedAuthTokenDataIV()));
final byte[] signedAuthTokenData = symCipher.doFinal(encryptedSignedAuthToken.getEncryptedSignedAuthTokenData());
return signedAuthTokenData;
} catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new RuntimeException(e);
}
}Example 12
| Project: CNode-Material-Design-master File: Crypto.java View source code |
public byte[] encrypt(@NonNull SecretKey secret, @NonNull IvParameterSpec iv, @NonNull byte[] data) throws CryptoException {
try {
Cipher cipher = Cipher.getInstance(algorithm + "/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret, iv);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmExceptionInvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | e) {
throw new CryptoException("Encrypt error.", e);
}
}Example 13
| Project: codeine-master File: EncryptionUtils.java View source code |
private static byte[] encrypt(String key, String value) {
byte[] raw = key.getBytes(Charsets.US_ASCII);
if (raw.length != 16) {
throw ExceptionUtils.asUnchecked(new IllegalArgumentException("Invalid key size."));
}
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
return cipher.doFinal(value.getBytes(Charsets.US_ASCII));
} catch (Exception e) {
throw ExceptionUtils.asUnchecked(e);
}
}Example 14
| Project: craken-master File: TestEncrypt.java View source code |
public void testCiper() throws Exception {
byte[] keyBytes = "40674244".getBytes();
byte[] ivBytes = "@1B2c3D4".getBytes();
// wrap key data in Key/IV specs to pass to cipher
SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
// create the cipher with the algorithm you choose see javadoc for Cipher class for more info, e.g.
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
byte[] input = "administrator".getBytes("UTF-8");
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] encrypted = new byte[cipher.getOutputSize(input.length)];
int enc_len = cipher.update(input, 0, input.length, encrypted, 0);
enc_len += cipher.doFinal(encrypted, enc_len);
Debug.line(encrypted, enc_len);
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] decrypted = new byte[cipher.getOutputSize(enc_len)];
int dec_len = cipher.update(encrypted, 0, enc_len, decrypted, 0);
dec_len += cipher.doFinal(decrypted, dec_len);
Debug.line(decrypted, dec_len, new String(decrypted, "UTF-8").trim());
}Example 15
| Project: CrocodileNote-master File: FolderItem.java View source code |
static String loadInfo(String folder, String salt) {
try {
Cipher c = Cipher.getInstance(Base.cbc);
IvParameterSpec ivSpec = new IvParameterSpec(genIV(salt));
c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base.kcipher.doFinal(Base.tmp_esk), Base.aes), ivSpec);
CipherInputStream cis = new CipherInputStream(new FileInputStream(new File(folder, ".info")), c);
return Utils.readFile(cis);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}Example 16
| Project: irma_future_id-master File: BaseMac.java View source code |
protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException {
CipherParameters param;
if (key == null) {
throw new InvalidKeyException("key is null");
}
if (key instanceof BCPBEKey) {
BCPBEKey k = (BCPBEKey) key;
if (k.getParam() != null) {
param = k.getParam();
} else if (params instanceof PBEParameterSpec) {
param = PBE.Util.makePBEMacParameters(k, params);
} else {
throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
}
} else if (params instanceof IvParameterSpec) {
param = new ParametersWithIV(new KeyParameter(key.getEncoded()), ((IvParameterSpec) params).getIV());
} else if (params instanceof SkeinParameters) {
param = new SkeinParameters.Builder((SkeinParameters) params).setKey(key.getEncoded()).build();
} else if (params == null) {
param = new KeyParameter(key.getEncoded());
} else {
throw new InvalidAlgorithmParameterException("unknown parameter type.");
}
macEngine.init(param);
}Example 17
| Project: Java-Examples-master File: AESTest.java View source code |
@Test
public void testAESwithIV() throws Exception {
final String input = "Hello, World!";
final Key key = KeyUtils.generateAESKey();
Assert.assertNotNull(key);
final IvParameterSpec ivParameterSpec = IvUtils.generateDefaultVector();
Assert.assertNotNull(ivParameterSpec);
final ICipher iCipher = SymetricCipherProvider.createCipherInstance(CipherAlgorithm.AES, CipherMode.CBC, CipherPadding.PKCS5Padding, key, ivParameterSpec);
Assert.assertNotNull(iCipher);
final byte[] encrpyted = iCipher.encrypt(input.getBytes("UTF-8"));
Assert.assertNotNull(encrpyted);
final byte[] decrypted = iCipher.decrypt(encrpyted);
Assert.assertNotNull(decrypted);
final String inputVer2 = new String(decrypted, "UTF-8");
Assert.assertEquals(input, inputVer2);
}Example 18
| Project: jcrypt-master File: Build.java View source code |
public static void build(File input, File output, String mainclass, byte[] key, boolean encall) throws Exception {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(output));
if (!encall) {
ZipFile inp = new ZipFile(input);
Enumeration<? extends ZipEntry> entries = inp.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (!entry.getName().toLowerCase().contains("meta-inf") && !entry.getName().toLowerCase().endsWith(".class")) {
out.putNextEntry(entry);
Utils.copy(inp.getInputStream(entry), out);
out.closeEntry();
}
}
inp.close();
}
ZipFile zip = new ZipFile("Bin.jar");
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
InputStream in = zip.getInputStream(entry);
out.putNextEntry(entry);
Utils.copy(in, out);
out.closeEntry();
in.close();
}
zip.close();
byte[] iv = new byte[16];
new Random().nextBytes(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/NOPADDING");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
FileInputStream is = new FileInputStream(input);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CipherOutputStream cos = new CipherOutputStream(baos, cipher);
Utils.copy(is, cos);
is.close();
cos.close();
byte[] bMainClass = mainclass.getBytes("UTF-8");
byte[] config = new byte[key.length + iv.length + 1 + bMainClass.length];
System.arraycopy(key, 0, config, 0, key.length);
System.arraycopy(iv, 0, config, 16, iv.length);
config[32] = (byte) (encall ? 1 : 0);
System.arraycopy(bMainClass, 0, config, 33, bMainClass.length);
ZipEntry entry = new ZipEntry(ENCRYPTED_ARCHIVE);
out.putNextEntry(entry);
entry.setExtra(config);
out.write(baos.toByteArray());
out.closeEntry();
out.close();
}Example 19
| Project: jdk7u-jdk-master File: NullIV.java View source code |
public static void main(String[] args) throws Exception {
try {
IvParameterSpec ivParams = new IvParameterSpec(null);
throw new Exception("expected NullPointerException");
} catch (NullPointerException npe) {
}
try {
IvParameterSpec ivParams = new IvParameterSpec(null, 0, 0);
throw new Exception("expected IllegalArgumentException");
} catch (IllegalArgumentException iae) {
}
}Example 20
| Project: logdb-master File: Decrypt.java View source code |
@Override
public Object eval(Row row) {
Object key = keyExpr.eval(row);
Object data = dataExpr.eval(row);
Object iv = null;
if (ivExpr != null)
iv = ivExpr.eval(row);
if (key == null || data == null)
return null;
if (!(key instanceof byte[]))
return null;
if (!(data instanceof byte[]))
return null;
if (iv != null && !(iv instanceof byte[]))
return null;
byte[] keyBytes = (byte[]) key;
byte[] ivBytes = (byte[]) iv;
byte[] dataBytes = (byte[]) data;
try {
SecretKey secureKey = new SecretKeySpec(keyBytes, keyAlgorithm);
if (ivBytes != null)
cipher.init(Cipher.DECRYPT_MODE, secureKey, new IvParameterSpec(ivBytes));
else
cipher.init(Cipher.DECRYPT_MODE, secureKey);
return cipher.doFinal(dataBytes);
} catch (Throwable t) {
if (slog.isDebugEnabled()) {
slog.debug("araqne logdb: decrypt failure", t);
}
return null;
}
}Example 21
| Project: ManagedRuntimeInitiative-master File: NullIV.java View source code |
public static void main(String[] args) throws Exception {
try {
IvParameterSpec ivParams = new IvParameterSpec(null);
throw new Exception("expected NullPointerException");
} catch (NullPointerException npe) {
}
try {
IvParameterSpec ivParams = new IvParameterSpec(null, 0, 0);
throw new Exception("expected IllegalArgumentException");
} catch (IllegalArgumentException iae) {
}
}Example 22
| Project: muon-java-master File: SymmetricAESEncryptionAlgorithm.java View source code |
@Override
public byte[] decrypt(byte[] input) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return cipher.doFinal(input);
} catch (NoSuchAlgorithmExceptionNoSuchProviderException | NoSuchPaddingException | IllegalBlockSizeException | InvalidAlgorithmParameterException | BadPaddingException | UnsupportedEncodingException | InvalidKeyException | e) {
throw new MuonException("Unable to decrypt payload", e);
}
}Example 23
| Project: oobd-master File: JcePBEDataDecryptorFactoryBuilder.java View source code |
public byte[] recoverSessionData(int keyAlgorithm, byte[] key, byte[] secKeyData) throws PGPException {
try {
if (secKeyData != null && secKeyData.length > 0) {
String cipherName = PGPUtil.getSymmetricCipherName(keyAlgorithm);
Cipher keyCipher = helper.createCipher(cipherName + "/CFB/NoPadding");
keyCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, cipherName), new IvParameterSpec(new byte[keyCipher.getBlockSize()]));
return keyCipher.doFinal(secKeyData);
} else {
byte[] keyBytes = new byte[key.length + 1];
keyBytes[0] = (byte) keyAlgorithm;
System.arraycopy(key, 0, keyBytes, 1, key.length);
return keyBytes;
}
} catch (Exception e) {
throw new PGPException("Exception recovering session info", e);
}
}Example 24
| Project: openjdk-master File: NullIV.java View source code |
public static void main(String[] args) throws Exception {
try {
IvParameterSpec ivParams = new IvParameterSpec(null);
throw new Exception("expected NullPointerException");
} catch (NullPointerException npe) {
}
try {
IvParameterSpec ivParams = new IvParameterSpec(null, 0, 0);
throw new Exception("expected IllegalArgumentException");
} catch (IllegalArgumentException iae) {
}
}Example 25
| Project: openjdk8-jdk-master File: NullIV.java View source code |
public static void main(String[] args) throws Exception {
try {
IvParameterSpec ivParams = new IvParameterSpec(null);
throw new Exception("expected NullPointerException");
} catch (NullPointerException npe) {
}
try {
IvParameterSpec ivParams = new IvParameterSpec(null, 0, 0);
throw new Exception("expected IllegalArgumentException");
} catch (IllegalArgumentException iae) {
}
}Example 26
| Project: phresco-master File: EncryptString.java View source code |
/**
* Constructor
*
* @return
*
* @throws Exception
*/
public void Crypto(String key) throws Exception {
this.key = key;
// Make sure the key length should be 16
int len = this.key.length();
if (len < 16) {
int addSpaces = 16 - len;
for (int i = 0; i < addSpaces; i++) {
this.key = this.key + " ";
}
} else {
this.key = this.key.substring(0, 16);
}
this.keySpec = new SecretKeySpec(this.key.getBytes(), "AES");
this.ivSpec = new IvParameterSpec(iv.getBytes());
this.cipher = Cipher.getInstance("AES/CBC/NoPadding");
}Example 27
| Project: QRCode-APG-master File: Camellia.java View source code |
protected AlgorithmParameters engineGenerateParameters() {
byte[] iv = new byte[16];
if (random == null) {
random = new SecureRandom();
}
random.nextBytes(iv);
AlgorithmParameters params;
try {
params = AlgorithmParameters.getInstance("Camellia", "BC2");
params.init(new IvParameterSpec(iv));
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return params;
}Example 28
| Project: redPandaj-master File: AESstreamcipher.java View source code |
public static byte[] encodeCTR(byte[] bytes, byte[] pass, long ivbytes) throws Exception {
byte[] ivBytes2 = new byte[16];
ByteBuffer buffer = ByteBuffer.wrap(ivBytes2);
buffer.putLong(12312L);
buffer.putLong(ivbytes);
IvParameterSpec iv = new IvParameterSpec(ivBytes2, 0, 16);
System.out.println("iv: " + Utils.bytesToHexString(ivBytes2));
Cipher c = Cipher.getInstance("AES/CTR/NoPadding");
Key k = new SecretKeySpec(pass, "AES");
c.init(Cipher.ENCRYPT_MODE, k, iv);
ByteArrayOutputStream encodedBytes = new ByteArrayOutputStream();
OutputStream cos = new CipherOutputStream(encodedBytes, c);
cos.write(bytes);
cos.close();
System.out.println("new: " + Utils.bytesToHexString(c.getIV()));
return encodedBytes.toByteArray();
}Example 29
| Project: remusic-master File: AESTools.java View source code |
public static String encrpty(String paramString) {
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
messageDigest.update(INPUT.getBytes());
byte[] stringBytes = messageDigest.digest();
StringBuilder stringBuilder = new StringBuilder(stringBytes.length * 2);
for (int i = 0; i < stringBytes.length; i++) {
stringBuilder.append(CHARS[((stringBytes[i] & 0xF0) >>> 4)]);
stringBuilder.append(CHARS[(stringBytes[i] & 0xF)]);
}
String str = stringBuilder.toString();
SecretKeySpec localSecretKeySpec = new SecretKeySpec(str.substring(str.length() / 2).getBytes(), "AES");
Cipher localCipher;
try {
localCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
localCipher.init(1, localSecretKeySpec, new IvParameterSpec(IV.getBytes()));
return URLEncoder.encode(new String(BytesHandler.getChars(localCipher.doFinal(paramString.getBytes()))), "utf-8");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return "";
}Example 30
| Project: ripme-master File: AES.java View source code |
public static String decrypt(String cipherText, String key, int nBits) throws Exception {
String res = null;
nBits = nBits / 8;
byte[] data = Base64.decode(cipherText);
byte[] k = Arrays.copyOf(key.getBytes(), nBits);
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
SecretKey secretKey = generateSecretKey(k, nBits);
byte[] nonceBytes = Arrays.copyOf(Arrays.copyOf(data, 8), nBits / 2);
IvParameterSpec nonce = new IvParameterSpec(nonceBytes);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, nonce);
res = new String(cipher.doFinal(data, 8, data.length - 8));
return res;
}Example 31
| Project: robovm-master File: CipherSymmetricKeyThread.java View source code |
@Override
public void crypt() throws Exception {
byte[] output = new byte[128];
byte[] decrypted = new byte[128];
byte[] input = getData().getBytes();
SecureRandom sr = new SecureRandom();
//new byte[16];
byte[] iv = null;
int outputSize = 0;
KeyGenerator kg = KeyGenerator.getInstance(getAlgName());
kg.init(getKeyLength(), new SecureRandom());
Key key = kg.generateKey();
Cipher cip = Cipher.getInstance(getAlgName() + "/" + getMode() + "/" + getPadding());
if (getAlgName() != "AES") {
iv = new byte[8];
} else {
iv = new byte[16];
}
sr.nextBytes(iv);
IvParameterSpec ivspec = new IvParameterSpec(iv);
if (getMode() != "ECB") {
cip.init(Cipher.ENCRYPT_MODE, key, ivspec);
cip.doFinal(input, 0, input.length, output);
outputSize = cip.getOutputSize(input.length);
iv = cip.getIV();
ivspec = new IvParameterSpec(iv);
cip.init(Cipher.DECRYPT_MODE, key, ivspec);
cip.doFinal(output, 0, outputSize, decrypted);
} else {
cip.init(Cipher.ENCRYPT_MODE, key);
cip.doFinal(input, 0, input.length, output);
outputSize = cip.getOutputSize(input.length);
cip.init(Cipher.DECRYPT_MODE, key);
cip.doFinal(output, 0, outputSize, decrypted);
}
checkEncodedData(getData().getBytes(), decrypted);
}Example 32
| Project: school_shop-master File: DESUtil.java View source code |
// private static byte[] iv = {A,1,B,2,C,3,D,4,E,5,F,6,0,7,0,8};
/**
* åŠ å¯†æ•°æ?®
* @param encryptString å¾…åŠ å¯†æ•°æ?®
* @param key 密钥
* @return åŠ å¯†å?Žçš„æ•°æ?®
*/
public static String encryptDES(String encryptString, String encryptKey) throws Exception {
// IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);
IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
return Base64.encode(encryptedData);
}Example 33
| Project: SML-master File: CyptoUtils.java View source code |
public static String encode(String key, String data) {
if (data == null)
return null;
try {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
IvParameterSpec iv = new IvParameterSpec(IV);
AlgorithmParameterSpec paramSpec = iv;
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
byte[] bytes = cipher.doFinal(data.getBytes());
return byte2hex(bytes);
} catch (Exception e) {
return data;
}
}Example 34
| Project: TLS-Attacker-master File: UnlimitedStrengthTest.java View source code |
@Test
public void testAES256() throws Exception {
try {
UnlimitedStrengthHelper.removeCryptoStrengthRestriction();
Cipher encryptCipher = Cipher.getInstance("AES/CBC/NoPadding", new BouncyCastleProvider());
IvParameterSpec encryptIv = new IvParameterSpec(new byte[16]);
SecretKey encryptKey = new SecretKeySpec(new byte[32], "AES");
encryptCipher.init(Cipher.ENCRYPT_MODE, encryptKey, encryptIv);
} catch (InvalidKeyException ex) {
logger.warn("AES256 is probably not supported, you have to install Java Cryptography " + "Extension (JCE) Unlimited Strength Jurisdiction Policy Files.");
}
}Example 35
| Project: with-aes-master File: BaseAesImplementation.java View source code |
@Override
public InputStream decrypt(final Key key, final InputStream encrypted) throws CryptographyException, IOException {
final byte[] iv = new byte[IV_LENGTH];
final int read = encrypted.read(iv);
if (read != IV_LENGTH) {
throw new IOException("unable to read initialization vector expected: " + IV_LENGTH + ", got: " + read);
}
final AlgorithmParameterSpec parameter = new IvParameterSpec(iv);
return decrypt(key, parameter, encrypted);
}Example 36
| Project: YiTouQian-master File: Crypt.java View source code |
// iv 动��化,增强安全
// AES-128-CBCåŠ å¯†
// iv, 例如:8c32510d64a7be9adb38c09e672541de
public static String encrypt(String plainText, String iv) throws Exception {
byte[] skey = decodeHex(s_key.toCharArray());
byte[] siv = decodeHex(iv.toCharArray());
SecretKeySpec skeySpec1 = new SecretKeySpec(skey, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec1, new IvParameterSpec(siv));
byte[] encrypted = cipher.doFinal(plainText.getBytes());
return encodeHex(encrypted);
}Example 37
| Project: diceros-master File: TestCipher.java View source code |
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("/tmp/Entity0");
ObjectInputStream ois = new ObjectInputStream(fis);
Entity entity = (Entity) ois.readObject();
byte[] encryptResult = new byte[entity.input.length + 18];
byte[] decryptResult = new byte[entity.input.length];
Security.addProvider(new DicerosProvider());
Cipher cipher = Cipher.getInstance("AES/MBCBC/PKCS5Padding", "DC");
IvParameterSpec ivSpec = new IvParameterSpec(entity.iv);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(entity.key, "AES"), ivSpec);
cipher.doFinal(entity.input, 0, entity.input.length, encryptResult, 0);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(entity.key, "AES"), ivSpec);
decryptResult = cipher.doFinal(entity.encontent);
if (Arrays.areEqual(decryptResult, entity.input)) {
System.out.println("decry right");
} else if (Arrays.areEqual(decryptResult, entity.decontent)) {
System.out.println("same error");
} else {
System.out.println("error");
}
printArray(entity.decontent);
printArray(decryptResult);
printArray(entity.input);
System.out.println();
printArray(entity.encontent);
printArray(encryptResult);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (ShortBufferException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
}Example 38
| Project: recordloader-master File: Crypto.java View source code |
public static String decryptPassword() throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("keyfile"));
DESKeySpec ks = new DESKeySpec((byte[]) ois.readObject());
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey key = skf.generateSecret(ks);
Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec((byte[]) ois.readObject()));
CipherInputStream cis = new CipherInputStream(new FileInputStream("ciphertext"), c);
BufferedReader br = new BufferedReader(new InputStreamReader(cis));
String decrypted = br.readLine();
return decrypted;
}Example 39
| Project: andbase-master File: AbAes.java View source code |
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Cipher cipher = Cipher.getInstance("AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[cipher.getBlockSize()]));
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}Example 40
| Project: android-15-master File: CipherSymmetricKeyThread.java View source code |
@Override
public void crypt() throws Exception {
byte[] output = new byte[128];
byte[] decrypted = new byte[128];
byte[] input = getData().getBytes();
SecureRandom sr = new SecureRandom();
//new byte[16];
byte[] iv = null;
int outputSize = 0;
KeyGenerator kg = KeyGenerator.getInstance(getAlgName());
kg.init(getKeyLength(), new SecureRandom());
Key key = kg.generateKey();
Cipher cip = Cipher.getInstance(getAlgName() + "/" + getMode() + "/" + getPadding());
if (getAlgName() != "AES") {
iv = new byte[8];
} else {
iv = new byte[16];
}
sr.nextBytes(iv);
IvParameterSpec ivspec = new IvParameterSpec(iv);
if (getMode() != "ECB") {
cip.init(Cipher.ENCRYPT_MODE, key, ivspec);
cip.doFinal(input, 0, input.length, output);
outputSize = cip.getOutputSize(input.length);
iv = cip.getIV();
ivspec = new IvParameterSpec(iv);
cip.init(Cipher.DECRYPT_MODE, key, ivspec);
cip.doFinal(output, 0, outputSize, decrypted);
} else {
cip.init(Cipher.ENCRYPT_MODE, key);
cip.doFinal(input, 0, input.length, output);
outputSize = cip.getOutputSize(input.length);
cip.init(Cipher.DECRYPT_MODE, key);
cip.doFinal(output, 0, outputSize, decrypted);
}
checkEncodedData(getData().getBytes(), decrypted);
}Example 41
| Project: android-libcore64-master File: CipherBenchmark.java View source code |
@Override
protected void setUp() throws Exception {
cipherAlgorithm = algorithm.toString() + "/" + mode.toString() + "/" + padding.toString();
String keyAlgorithm = algorithm.toString();
key = KEY_SIZES.get(keySize);
if (key == null) {
KeyGenerator generator = KeyGenerator.getInstance(keyAlgorithm);
generator.init(keySize);
key = generator.generateKey();
KEY_SIZES.put(keySize, key);
}
switch(implementation) {
case OpenSSL:
providerName = "AndroidOpenSSL";
break;
case BouncyCastle:
providerName = "BC";
break;
default:
throw new RuntimeException(implementation.toString());
}
if (mode != Mode.ECB) {
spec = new IvParameterSpec(IV);
}
cipherEncrypt = Cipher.getInstance(cipherAlgorithm, providerName);
cipherEncrypt.init(Cipher.ENCRYPT_MODE, key, spec);
cipherDecrypt = Cipher.getInstance(cipherAlgorithm, providerName);
cipherDecrypt.init(Cipher.DECRYPT_MODE, key, spec);
}Example 42
| Project: android-sdk-sources-for-api-level-23-master File: CipherBenchmark.java View source code |
@Override
protected void setUp() throws Exception {
cipherAlgorithm = algorithm.toString() + "/" + mode.toString() + "/" + padding.toString();
String keyAlgorithm = algorithm.toString();
key = KEY_SIZES.get(keySize);
if (key == null) {
KeyGenerator generator = KeyGenerator.getInstance(keyAlgorithm);
generator.init(keySize);
key = generator.generateKey();
KEY_SIZES.put(keySize, key);
}
switch(implementation) {
case OpenSSL:
providerName = "AndroidOpenSSL";
break;
case BouncyCastle:
providerName = "BC";
break;
default:
throw new RuntimeException(implementation.toString());
}
if (mode != Mode.ECB) {
spec = new IvParameterSpec(IV);
}
cipherEncrypt = Cipher.getInstance(cipherAlgorithm, providerName);
cipherEncrypt.init(Cipher.ENCRYPT_MODE, key, spec);
cipherDecrypt = Cipher.getInstance(cipherAlgorithm, providerName);
cipherDecrypt.init(Cipher.DECRYPT_MODE, key, spec);
}Example 43
| Project: android-util-master File: DES.java View source code |
/**
* å°†å—符串进行DESåŠ å¯†
* @param source æœªåŠ å¯†æº?å—符串
* @return åŠ å¯†å?Žå—符串
*/
public String encrypt(String source) {
byte[] retByte = null;
// Create SecretKey object
DESKeySpec dks = null;
try {
dks = new DESKeySpec(KEY);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey securekey = keyFactory.generateSecret(dks);
// Create IvParameterSpec object with initialization vector
IvParameterSpec spec = new IvParameterSpec(IV);
// Create Cipter object
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
// Initialize Cipher object
cipher.init(Cipher.ENCRYPT_MODE, securekey, spec);
// Decrypting data
retByte = cipher.doFinal(source.getBytes());
String result = "";
if (code == 0) {
result = new String(retByte, "ISO-8859-1");
} else if (code == 1) {
result = Base64.encodeToString(retByte, false);
} else {
result = new String(retByte);
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 44
| Project: AndroidFire-master File: AESUtil.java View source code |
// åŠ å¯†
public static String Encrypt(String sSrc) throws Exception {
if (key == null) {
System.out.print("Key为空null");
return null;
}
// 判æ–Key是å?¦ä¸º16ä½?
if (key.length() != 16) {
System.out.print("Key长度�是16�");
return null;
}
byte[] raw = key.getBytes("UTF-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
//"算法/模å¼?/è¡¥ç ?æ–¹å¼?"
Cipher cipher = Cipher.getInstance("AES/CBC/Iso10126Padding");
//使用CBC模å¼?,需è¦?一个å?‘é‡?iv,å?¯å¢žåŠ åŠ å¯†ç®—æ³•çš„å¼ºåº¦
IvParameterSpec ivps = new IvParameterSpec(iv.getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivps);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
//æ¤å¤„使用BAES64å?šè½¬ç ?功能,å?Œæ—¶èƒ½èµ·åˆ°2æ¬¡åŠ å¯†çš„ä½œç”¨ã€‚
return new String(Base64.encodeBase64(encrypted), "UTF-8");
}Example 45
| Project: androidutils-master File: DES.java View source code |
/**
* å°†å—符串进行DESåŠ å¯†
* @param source æœªåŠ å¯†æº?å—符串
* @return åŠ å¯†å?Žå—符串
*/
public String encrypt(String source) {
byte[] retByte = null;
// Create SecretKey object
DESKeySpec dks = null;
try {
dks = new DESKeySpec(KEY);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey securekey = keyFactory.generateSecret(dks);
// Create IvParameterSpec object with initialization vector
IvParameterSpec spec = new IvParameterSpec(IV);
// Create Cipter object
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
// Initialize Cipher object
cipher.init(Cipher.ENCRYPT_MODE, securekey, spec);
// Decrypting data
retByte = cipher.doFinal(source.getBytes());
String result = "";
if (code == 0) {
result = new String(retByte, "ISO-8859-1");
} else if (code == 1) {
result = Base64.encodeToString(retByte, false);
} else {
result = new String(retByte);
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 46
| Project: android_libcore-master File: CipherSymmetricKeyThread.java View source code |
@Override
public void crypt() throws Exception {
byte[] output = new byte[128];
byte[] decrypted = new byte[128];
byte[] input = getData().getBytes();
SecureRandom sr = new SecureRandom();
//new byte[16];
byte[] iv = null;
int outputSize = 0;
KeyGenerator kg = KeyGenerator.getInstance(getAlgName());
kg.init(getKeyLength(), new SecureRandom());
Key key = kg.generateKey();
Cipher cip = Cipher.getInstance(getAlgName() + "/" + getMode() + "/" + getPadding());
if (getAlgName() != "AES") {
iv = new byte[8];
} else {
iv = new byte[16];
}
sr.nextBytes(iv);
IvParameterSpec ivspec = new IvParameterSpec(iv);
if (getMode() != "ECB") {
cip.init(Cipher.ENCRYPT_MODE, key, ivspec);
cip.doFinal(input, 0, input.length, output);
outputSize = cip.getOutputSize(input.length);
iv = cip.getIV();
ivspec = new IvParameterSpec(iv);
cip.init(Cipher.DECRYPT_MODE, key, ivspec);
cip.doFinal(output, 0, outputSize, decrypted);
} else {
cip.init(Cipher.ENCRYPT_MODE, key);
cip.doFinal(input, 0, input.length, output);
outputSize = cip.getOutputSize(input.length);
cip.init(Cipher.DECRYPT_MODE, key);
cip.doFinal(output, 0, outputSize, decrypted);
}
checkEncodedData(getData().getBytes(), decrypted);
}Example 47
| Project: android_platform_libcore-master File: CipherSymmetricKeyThread.java View source code |
@Override
public void crypt() throws Exception {
byte[] output = new byte[128];
byte[] decrypted = new byte[128];
byte[] input = getData().getBytes();
SecureRandom sr = new SecureRandom();
//new byte[16];
byte[] iv = null;
int outputSize = 0;
KeyGenerator kg = KeyGenerator.getInstance(getAlgName());
kg.init(getKeyLength(), new SecureRandom());
Key key = kg.generateKey();
Cipher cip = Cipher.getInstance(getAlgName() + "/" + getMode() + "/" + getPadding());
if (getAlgName() != "AES") {
iv = new byte[8];
} else {
iv = new byte[16];
}
sr.nextBytes(iv);
IvParameterSpec ivspec = new IvParameterSpec(iv);
if (getMode() != "ECB") {
cip.init(Cipher.ENCRYPT_MODE, key, ivspec);
cip.doFinal(input, 0, input.length, output);
outputSize = cip.getOutputSize(input.length);
iv = cip.getIV();
ivspec = new IvParameterSpec(iv);
cip.init(Cipher.DECRYPT_MODE, key, ivspec);
cip.doFinal(output, 0, outputSize, decrypted);
} else {
cip.init(Cipher.ENCRYPT_MODE, key);
cip.doFinal(input, 0, input.length, output);
outputSize = cip.getOutputSize(input.length);
cip.init(Cipher.DECRYPT_MODE, key);
cip.doFinal(output, 0, outputSize, decrypted);
}
checkEncodedData(getData().getBytes(), decrypted);
}Example 48
| Project: apn-proxy-master File: TestAes.java View source code |
@Test
public void test() {
try {
Key securekey = new SecretKeySpec("fuckgfw123456789".getBytes(), "AES");
IvParameterSpec iv = new IvParameterSpec("1234567890123456".getBytes());
Cipher c1 = Cipher.getInstance("AES/CFB/NoPadding");
c1.init(Cipher.ENCRYPT_MODE, securekey, iv);
byte[] raw = c1.doFinal(new byte[] { 1, 2, 3 });
Cipher c2 = Cipher.getInstance("AES/CFB/NoPadding");
c2.init(Cipher.DECRYPT_MODE, securekey, iv);
byte[] orig = c2.doFinal(raw);
byte[] orig2 = c2.doFinal(new byte[] { raw[0] });
System.out.println(orig2);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
}Example 49
| Project: ARTPart-master File: CipherBenchmark.java View source code |
@Override
protected void setUp() throws Exception {
cipherAlgorithm = algorithm.toString() + "/" + mode.toString() + "/" + padding.toString();
String keyAlgorithm = algorithm.toString();
key = KEY_SIZES.get(keySize);
if (key == null) {
KeyGenerator generator = KeyGenerator.getInstance(keyAlgorithm);
generator.init(keySize);
key = generator.generateKey();
KEY_SIZES.put(keySize, key);
}
switch(implementation) {
case OpenSSL:
providerName = "AndroidOpenSSL";
break;
case BouncyCastle:
providerName = "BC";
break;
default:
throw new RuntimeException(implementation.toString());
}
if (mode != Mode.ECB) {
spec = new IvParameterSpec(IV);
}
cipherEncrypt = Cipher.getInstance(cipherAlgorithm, providerName);
cipherEncrypt.init(Cipher.ENCRYPT_MODE, key, spec);
cipherDecrypt = Cipher.getInstance(cipherAlgorithm, providerName);
cipherDecrypt.init(Cipher.DECRYPT_MODE, key, spec);
}Example 50
| Project: Asynchronous-SSHD-master File: BaseCipher.java View source code |
public void init(Mode mode, byte[] key, byte[] iv) throws Exception {
key = resize(key, bsize);
iv = resize(iv, ivsize);
try {
cipher = SecurityUtils.getCipher(transformation);
cipher.init((mode == Mode.Encrypt ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE), new SecretKeySpec(key, algorithm), new IvParameterSpec(iv));
} catch (Exception e) {
cipher = null;
throw e;
}
}Example 51
| Project: BaseMoudle-master File: AESUtil.java View source code |
// åŠ å¯†
public static String Encrypt(String sSrc) throws Exception {
if (key == null) {
System.out.print("Key为空null");
return null;
}
// 判æ–Key是å?¦ä¸º16ä½?
if (key.length() != 16) {
System.out.print("Key长度�是16�");
return null;
}
byte[] raw = key.getBytes("UTF-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
//"算法/模å¼?/è¡¥ç ?æ–¹å¼?"
Cipher cipher = Cipher.getInstance("AES/CBC/Iso10126Padding");
//使用CBC模å¼?,需è¦?一个å?‘é‡?iv,å?¯å¢žåŠ åŠ å¯†ç®—æ³•çš„å¼ºåº¦
IvParameterSpec ivps = new IvParameterSpec(iv.getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivps);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
//æ¤å¤„使用BAES64å?šè½¬ç ?功能,å?Œæ—¶èƒ½èµ·åˆ°2æ¬¡åŠ å¯†çš„ä½œç”¨ã€‚
return new String(Base64.encodeBase64(encrypted), "UTF-8");
}Example 52
| Project: bugvm-master File: BaseMac.java View source code |
protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException {
CipherParameters param;
if (key == null) {
throw new InvalidKeyException("key is null");
}
if (key instanceof BCPBEKey) {
BCPBEKey k = (BCPBEKey) key;
if (k.getParam() != null) {
param = k.getParam();
} else if (params instanceof PBEParameterSpec) {
param = PBE.Util.makePBEMacParameters(k, params);
} else {
throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
}
} else if (params instanceof IvParameterSpec) {
param = new ParametersWithIV(new KeyParameter(key.getEncoded()), ((IvParameterSpec) params).getIV());
} else if (params == null) {
param = new KeyParameter(key.getEncoded());
} else {
throw new InvalidAlgorithmParameterException("unknown parameter type.");
}
macEngine.init(param);
}Example 53
| Project: CarpoolBackend-master File: SessionCrypto.java View source code |
public static String encrypt(String plainText) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, InvalidAlgorithmParameterException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
byte[] plainTextBytes = plainText.getBytes("UTF8");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encrypted = cipher.doFinal(plainTextBytes);
return toHex(encrypted);
}Example 54
| Project: cattle-master File: Aes256Encrypter.java View source code |
public String encrypt(String plainText, Key key) {
try {
Cipher encrypter = Cipher.getInstance("AES/CBC/PKCS5PADDING", "SunJCE");
byte[] ivbytes = new byte[16];
rn.nextBytes(ivbytes);
String IV = new String(Hex.encodeHex(ivbytes));
encrypter.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(ivbytes));
return IV + ":" + String.valueOf(Hex.encodeHex(encrypter.doFinal(plainText.getBytes("UTF-8"))));
} catch (Exception e) {
e.printStackTrace();
throw new IllegalArgumentException(e);
}
}Example 55
| Project: com.revolsys.open-master File: PasswordUtil.java View source code |
public static byte[] decryptSqlDeveloper(final byte[] result) {
final byte constant = result[0];
if (constant != (byte) 5) {
throw new IllegalArgumentException();
}
final byte[] secretKey = new byte[8];
System.arraycopy(result, 1, secretKey, 0, 8);
final byte[] encryptedPassword = new byte[result.length - 9];
System.arraycopy(result, 9, encryptedPassword, 0, encryptedPassword.length);
final byte[] iv = new byte[8];
for (int i = 0; i < iv.length; i++) {
iv[i] = 0;
}
try {
final Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
final SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "DES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(iv));
return cipher.doFinal(encryptedPassword);
} catch (final Throwable e) {
Exceptions.throwUncheckedException(e);
return null;
}
}Example 56
| Project: dataservices-sdk-java-master File: AESTest.java View source code |
public static void main(String[] args) {
try {
Mode m = Mode.valueOf(args[0]);
if (m == Mode.ENCRYPT) {
int bits = Integer.valueOf(args[1]);
String infile = args[2];
String outfile = args[3];
// Generate key
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(bits);
SecretKey sk = kg.generateKey();
Cipher cipher = Cipher.getInstance(TransformConstants.DEFAULT_ENCRYPTION_TRANSFORM);
cipher.init(Cipher.ENCRYPT_MODE, sk);
System.out.println("Key: " + new String(Base64.encodeBase64(sk.getEncoded()), "US-ASCII"));
System.out.println("IV: " + new String(Base64.encodeBase64(cipher.getIV()), "US-ASCII"));
CipherOutputStream out = new CipherOutputStream(new FileOutputStream(new File(outfile)), cipher);
InputStream in = new FileInputStream(new File(infile));
doStream(in, out);
out.close();
in.close();
} else if (m == Mode.DECRYPT) {
String key = args[1];
String iv = args[2];
String infile = args[3];
String outfile = args[4];
SecretKeySpec sk = new SecretKeySpec(Base64.decodeBase64(key.getBytes("US-ASCII")), "AES");
IvParameterSpec ivspec = new IvParameterSpec(Base64.decodeBase64(iv.getBytes("US-ASCII")));
Cipher cipher = Cipher.getInstance(TransformConstants.DEFAULT_ENCRYPTION_TRANSFORM);
cipher.init(Cipher.DECRYPT_MODE, sk, ivspec);
CipherInputStream in = new CipherInputStream(new FileInputStream(new File(infile)), cipher);
OutputStream out = new FileOutputStream(new File(outfile));
doStream(in, out);
out.close();
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}Example 57
| Project: dummydroid-master File: DownloadData.java View source code |
/**
* Access the APK file
*
* @return an inputstream from which the app can be read (already processed
* through crypto).
* @throws NoSuchPaddingException
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
*/
public InputStream openApp() throws IOException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
InputStream ret = api.executeDownload(downloadUrl, downloadAuthCookie.getName() + "=" + downloadAuthCookie.getValue());
if (appDeliveryData.hasEncryptionParams()) {
int version = ret.read();
if (version != 0) {
throw new IOException("Unknown crypto container!");
}
// Meta data
ret.skip(4);
byte[] iv = new byte[16];
ret.read(iv);
byte[] encoded = appDeliveryData.getEncryptionParams().getEncryptionKey().getBytes("UTF-8");
byte[] decoded = Base64.decode(encoded, Base64.DEFAULT);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(decoded, "AES");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
return new CipherInputStream(ret, cipher);
} else {
return ret;
}
}Example 58
| Project: ebean-master File: SimpleAesEncryptor.java View source code |
@Override
public byte[] decrypt(byte[] data, EncryptKey encryptKey) {
if (data == null) {
return null;
}
String key = paddKey(encryptKey);
try {
byte[] keyBytes = getKeyBytes(key);
IvParameterSpec iv = getIvParameterSpec(key);
SecretKeySpec sks = new SecretKeySpec(keyBytes, "AES");
Cipher c = Cipher.getInstance(AES_CIPHER);
c.init(Cipher.DECRYPT_MODE, sks, iv);
return c.doFinal(data);
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 59
| Project: Exoplayer_VLC-master File: Aes128DataSource.java View source code |
@Override
public long open(DataSpec dataSpec) throws IOException {
Cipher cipher;
try {
cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (NoSuchPaddingException e) {
throw new RuntimeException(e);
}
Key cipherKey = new SecretKeySpec(secretKey, "AES");
AlgorithmParameterSpec cipherIV = new IvParameterSpec(iv);
try {
cipher.init(Cipher.DECRYPT_MODE, cipherKey, cipherIV);
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new RuntimeException(e);
}
cipherInputStream = new CipherInputStream(new DataSourceInputStream(upstream, dataSpec), cipher);
return C.LENGTH_UNBOUNDED;
}Example 60
| Project: glowroot-master File: Encryption.java View source code |
public static String encrypt(String text, LazySecretKey lazySecretKey) throws Exception {
SecretKey secretKey = lazySecretKey.getOrCreate();
byte[] iv = new byte[16];
secureRandom.nextBytes(iv);
Cipher aesCipherForEncryption = Cipher.getInstance("AES/CBC/PKCS5Padding");
aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
byte[] encryptedBytes = aesCipherForEncryption.doFinal(text.getBytes(Charsets.UTF_8));
return encoder.encode(encryptedBytes) + ':' + encoder.encode(iv);
}Example 61
| Project: graylog2-server-master File: AESTools.java View source code |
@Nullable
public static String encrypt(String plainText, String encryptionKey, String salt) {
try {
@SuppressWarnings("CIPHER_INTEGRITY") Cipher cipher = Cipher.getInstance("AES/CBC/ISO10126Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(salt.getBytes("UTF-8")));
return Hex.encodeToString(cipher.doFinal(plainText.getBytes("UTF-8")));
} catch (Exception e) {
LOG.error("Could not encrypt value.", e);
}
return null;
}Example 62
| Project: hbase-master File: AESDecryptor.java View source code |
protected void init() {
try {
if (iv == null) {
throw new NullPointerException("IV is null");
}
cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new RuntimeException(e);
}
initialized = true;
}Example 63
| Project: itol-master File: PasswordEncryption.java View source code |
public static String encrypt(String plainText) {
try {
byte[] data = plainText.getBytes("UTF-8");
if (data.length % 16 != 0) {
byte[] ndata = new byte[data.length + 16 - (data.length & 0x0F)];
System.arraycopy(data, 0, ndata, 0, data.length);
data = ndata;
}
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return bytesToString(cipher.doFinal(data));
} catch (Throwable e) {
throw new IllegalStateException(e);
}
}Example 64
| Project: jencrypt-master File: AESEncryptor.java View source code |
/**
* Encrypts given bytes with AES algorithm and protects
* it with given password
*
* @param data
* @param password
* @return encrypted data
*/
public byte[] encrypt(byte[] data, char[] password) throws AESException {
byte[] salt = new byte[8];
random.nextBytes(salt);
try {
if (factory == null)
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp = factory.generateSecret(new PBEKeySpec(password, salt, 65536, 128));
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
byte[] iv = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal(data);
byte[] encryptedData = new byte[8 + 16 + ciphertext.length];
int index = 0;
for (int i = 0; i < salt.length; i++) encryptedData[index++] = salt[i];
for (int i = 0; i < iv.length; i++) encryptedData[index++] = iv[i];
for (int i = 0; i < ciphertext.length; i++) encryptedData[index++] = ciphertext[i];
return encryptedData;
} catch (Exception e) {
throw new AESException("Failed to encrypt: " + e);
}
}Example 65
| Project: kaif-master File: Decryptor.java View source code |
/**
* @see Encryptor#create(byte[], byte[])) for key algorithm
*/
public static Decryptor create(final byte[] key, final byte[] iv) {
try {
final IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
return new Decryptor(key, "AES/CBC/PKCS5Padding", ivParameterSpec);
} catch (final GeneralSecurityException e) {
e.printStackTrace();
throw new RuntimeException("unsupported type of encryption: AES");
}
}Example 66
| Project: kanqiu_letv-master File: DEs.java View source code |
/**
*
* @param key 必须长度必须是8的�数
* @param data
* @return
* @throws Exception
*/
public static String encode(String key, byte[] data) throws Exception {
try {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
AlgorithmParameterSpec paramSpec = iv;
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
byte[] bytes = cipher.doFinal(data);
return LetvBase64.encode(bytes);
// return Base64.encodeToString(bytes, 3);
} catch (Exception e) {
throw new Exception(e);
}
}Example 67
| Project: keepassdroid-master File: TwofishEngine.java View source code |
@Override
public Cipher getCipher(int opmode, byte[] key, byte[] IV, boolean androidOverride) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
Cipher cipher;
if (opmode == Cipher.ENCRYPT_MODE) {
cipher = CipherFactory.getInstance("Twofish/CBC/ZeroBytePadding", androidOverride);
} else {
cipher = CipherFactory.getInstance("Twofish/CBC/NoPadding", androidOverride);
}
cipher.init(opmode, new SecretKeySpec(key, "AES"), new IvParameterSpec(IV));
return cipher;
}Example 68
| Project: Lazy-master File: AES.java View source code |
/**åŠ å¯†
* @throws Exception
*/
public static String Encrypt(String sSrc, String sKey) throws Exception {
if (sKey == null) {
Log.e("Key为空null", "Key为空null");
return null;
}
// 判æ–Key是å?¦ä¸º16ä½?
if (sKey.length() != 16) {
Log.e("\"Key长度�是16�\"", "Key长度�是16�");
return null;
}
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
//"算法/模å¼?/è¡¥ç ?æ–¹å¼?"
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//使用CBC模å¼?,需è¦?一个å?‘é‡?iv,å?¯å¢žåŠ åŠ å¯†ç®—æ³•çš„å¼ºåº¦
IvParameterSpec iv = new IvParameterSpec("1234567890123456".getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
//æ¤å¤„使用BASE64å?šè½¬ç ?功能,å?Œæ—¶èƒ½èµ·åˆ°2æ¬¡åŠ å¯†çš„ä½œç”¨ã€‚
return Base64_2.encode(encrypted);
}Example 69
| Project: LntuOnline-Android-master File: Crypto.java View source code |
public byte[] encrypt(@NonNull SecretKey secret, @NonNull IvParameterSpec iv, @NonNull byte[] data) throws CryptoException {
try {
Cipher cipher = Cipher.getInstance(algorithm + "/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret, iv);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmExceptionInvalidKeyException | InvalidAlgorithmParameterException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | e) {
throw new CryptoException("Encrypt error", e);
}
}Example 70
| Project: MyWeather-master File: DecodeUtil.java View source code |
public static String decodeResponse(String str) throws Exception {
if (TextUtils.isEmpty(str))
return null;
String CIPHER_ALGORITHM_CBC_NoPadding = "AES/CBC/NoPadding";
String KEY_ALGORITHM = "AES";
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC_NoPadding);
SecretKeySpec secretKey = new SecretKeySpec("2345android_key_".getBytes(), KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(// 使用解密模��始化 密钥
"2345tqIv_shiqing".getBytes()));
byte[] decrypt = cipher.doFinal(hexString2Bytes(str));
// String response = decodeUnicode(new String(decrypt));
String response = new String(decrypt);
int last = response.lastIndexOf("}");
response = response.substring(0, last + 1);
// System.out.println(response);
return response;
}Example 71
| Project: neembuunow-master File: an.java View source code |
public static byte[] a(byte[] paramArrayOfByte, String paramString) throws an.a, ap {
if (paramArrayOfByte.length != 16) {
throw new a();
}
try {
arrayOfByte1 = aq.a(paramString);
if (arrayOfByte1.length <= 16) {
throw new a();
}
} catch (NoSuchAlgorithmException localNoSuchAlgorithmException) {
byte[] arrayOfByte1;
throw new a(localNoSuchAlgorithmException);
ByteBuffer localByteBuffer = ByteBuffer.allocate(arrayOfByte1.length);
localByteBuffer.put(arrayOfByte1);
localByteBuffer.flip();
byte[] arrayOfByte2 = new byte[16];
byte[] arrayOfByte3 = new byte[-16 + arrayOfByte1.length];
localByteBuffer.get(arrayOfByte2);
localByteBuffer.get(arrayOfByte3);
SecretKeySpec localSecretKeySpec = new SecretKeySpec(paramArrayOfByte, "AES");
Cipher localCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
localCipher.init(2, localSecretKeySpec, new IvParameterSpec(arrayOfByte2));
byte[] arrayOfByte4 = localCipher.doFinal(arrayOfByte3);
return arrayOfByte4;
} catch (InvalidKeyException localInvalidKeyException) {
throw new a(localInvalidKeyException);
} catch (IllegalBlockSizeException localIllegalBlockSizeException) {
throw new a(localIllegalBlockSizeException);
} catch (NoSuchPaddingException localNoSuchPaddingException) {
throw new a(localNoSuchPaddingException);
} catch (BadPaddingException localBadPaddingException) {
throw new a(localBadPaddingException);
} catch (InvalidAlgorithmParameterException localInvalidAlgorithmParameterException) {
throw new a(localInvalidAlgorithmParameterException);
}
}Example 72
| Project: niolex-common-utils-master File: TripleDESCoder.java View source code |
/**
* Init the secret key and IV parameter by the specified Base64 encoded key.
*
* @param key the Base64 encoded key
*/
@Override
public void initKey(String key) {
byte[] keyData = Base64Util.base64ToByte(key);
ivParam = new IvParameterSpec(keyData, 0, 8);
try {
// DESedeKey always length 24 bytes
KeySpec keySpec = new DESedeKeySpec(keyData, keyData.length - 24);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
secretKey = keyFactory.generateSecret(keySpec);
} catch (Exception e) {
throw new IllegalArgumentException("Failed to init this key.", e);
}
}Example 73
| Project: open-keychain-master File: SessionKeySecretKeyDecryptorBuilder.java View source code |
public byte[] recoverKeyData(int encAlgorithm, byte[] key, byte[] iv, byte[] keyData, int keyOff, int keyLen) throws PGPException {
try {
Cipher c = helper.createCipher(PGPUtil.getSymmetricCipherName(encAlgorithm) + "/CFB/NoPadding");
c.init(Cipher.DECRYPT_MODE, PGPUtil.makeSymmetricKey(encAlgorithm, key), new IvParameterSpec(iv));
return c.doFinal(keyData, keyOff, keyLen);
} catch (IllegalBlockSizeException e) {
throw new PGPException("illegal block size: " + e.getMessage(), e);
} catch (BadPaddingException e) {
throw new PGPException("bad padding: " + e.getMessage(), e);
} catch (InvalidAlgorithmParameterException e) {
throw new PGPException("invalid parameter: " + e.getMessage(), e);
} catch (InvalidKeyException e) {
throw new PGPException("invalid key: " + e.getMessage(), e);
}
}Example 74
| Project: open-mika-master File: CipherSymmetricKeyThread.java View source code |
@Override
public void crypt() throws Exception {
byte[] output = new byte[128];
byte[] decrypted = new byte[128];
byte[] input = getData().getBytes();
SecureRandom sr = new SecureRandom();
//new byte[16];
byte[] iv = null;
int outputSize = 0;
KeyGenerator kg = KeyGenerator.getInstance(getAlgName());
kg.init(getKeyLength(), new SecureRandom());
Key key = kg.generateKey();
Cipher cip = Cipher.getInstance(getAlgName() + "/" + getMode() + "/" + getPadding());
if (getAlgName() != "AES") {
iv = new byte[8];
} else {
iv = new byte[16];
}
sr.nextBytes(iv);
IvParameterSpec ivspec = new IvParameterSpec(iv);
if (getMode() != "ECB") {
cip.init(Cipher.ENCRYPT_MODE, key, ivspec);
cip.doFinal(input, 0, input.length, output);
outputSize = cip.getOutputSize(input.length);
iv = cip.getIV();
ivspec = new IvParameterSpec(iv);
cip.init(Cipher.DECRYPT_MODE, key, ivspec);
cip.doFinal(output, 0, outputSize, decrypted);
} else {
cip.init(Cipher.ENCRYPT_MODE, key);
cip.doFinal(input, 0, input.length, output);
outputSize = cip.getOutputSize(input.length);
cip.init(Cipher.DECRYPT_MODE, key);
cip.doFinal(output, 0, outputSize, decrypted);
}
checkEncodedData(getData().getBytes(), decrypted);
}Example 75
| Project: Openfire-master File: K.java View source code |
byte[] A(byte abyte0[], int i, int j) {
if (C == null)
return abyte0;
try {
byte abyte1[] = new byte[16];
IvParameterSpec ivparameterspec = new IvParameterSpec(abyte1);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
if (E == Encryption.ENCRYPT)
cipher.init(1, C, ivparameterspec);
if (E == Encryption.DECRYPT)
cipher.init(2, C, ivparameterspec);
return cipher.doFinal(abyte0, i, j);
} catch (NoSuchAlgorithmException nosuchalgorithmexception) {
D.error(nosuchalgorithmexception.getMessage(), nosuchalgorithmexception);
} catch (NoSuchPaddingException nosuchpaddingexception) {
D.error(nosuchpaddingexception.getMessage(), nosuchpaddingexception);
} catch (InvalidKeyException invalidkeyexception) {
D.error(invalidkeyexception.getMessage(), invalidkeyexception);
} catch (BadPaddingException badpaddingexception) {
D.error(badpaddingexception.getMessage(), badpaddingexception);
} catch (IllegalBlockSizeException illegalblocksizeexception) {
D.error(illegalblocksizeexception.getMessage(), illegalblocksizeexception);
} catch (InvalidAlgorithmParameterException invalidalgorithmparameterexception) {
D.error(invalidalgorithmparameterexception.getMessage(), invalidalgorithmparameterexception);
}
return null;
}Example 76
| Project: passrepo-master File: Encryption.java View source code |
public static byte[] decrypt(CipherText cipherText, byte[] key) {
try {
Preconditions.checkArgument(key.length == REQUIRED_KEY_LENGTH_IN_BITS / 8);
Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(cipherText.iv));
return cipher.doFinal(cipherText.bytes);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}Example 77
| Project: pbase-master File: AESDecryptor.java View source code |
protected void init() {
try {
if (iv == null) {
throw new NullPointerException("IV is null");
}
cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new RuntimeException(e);
}
initialized = true;
}Example 78
| Project: picketbox-json-master File: EncUtil.java View source code |
public static byte[] encryptUsingAES_CBC(String plainText, byte[] key, IvParameterSpec parameters) throws ProcessingException {
if (key == null || key.length == 0) {
throw PicketBoxJSONMessages.MESSAGES.invalidNullArgument("key");
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance(AES_CBC);
SecretKeySpec keyspec = new SecretKeySpec(key, AES);
cipher.init(Cipher.ENCRYPT_MODE, keyspec, parameters);
return cipher.doFinal(plainText.getBytes());
} catch (Exception e) {
throw PicketBoxJSONMessages.MESSAGES.processingException(e);
}
}Example 79
| Project: property-db-master File: CipherSymmetricKeyThread.java View source code |
@Override
public void crypt() throws Exception {
byte[] output = new byte[128];
byte[] decrypted = new byte[128];
byte[] input = getData().getBytes();
SecureRandom sr = new SecureRandom();
//new byte[16];
byte[] iv = null;
int outputSize = 0;
KeyGenerator kg = KeyGenerator.getInstance(getAlgName());
kg.init(getKeyLength(), new SecureRandom());
Key key = kg.generateKey();
Cipher cip = Cipher.getInstance(getAlgName() + "/" + getMode() + "/" + getPadding());
if (getAlgName() != "AES") {
iv = new byte[8];
} else {
iv = new byte[16];
}
sr.nextBytes(iv);
IvParameterSpec ivspec = new IvParameterSpec(iv);
if (getMode() != "ECB") {
cip.init(Cipher.ENCRYPT_MODE, key, ivspec);
cip.doFinal(input, 0, input.length, output);
outputSize = cip.getOutputSize(input.length);
iv = cip.getIV();
ivspec = new IvParameterSpec(iv);
cip.init(Cipher.DECRYPT_MODE, key, ivspec);
cip.doFinal(output, 0, outputSize, decrypted);
} else {
cip.init(Cipher.ENCRYPT_MODE, key);
cip.doFinal(input, 0, input.length, output);
outputSize = cip.getOutputSize(input.length);
cip.init(Cipher.DECRYPT_MODE, key);
cip.doFinal(output, 0, outputSize, decrypted);
}
checkEncodedData(getData().getBytes(), decrypted);
}Example 80
| Project: Raccoon-master File: DownloadData.java View source code |
/**
* Access the APK file
*
* @return an inputstream from which the app can be read (already processed
* through crypto).
* @throws NoSuchPaddingException
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
*/
public InputStream openApp() throws IOException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
InputStream ret = api.executeDownload(downloadUrl, downloadAuthCookie.getName() + "=" + downloadAuthCookie.getValue());
if (appDeliveryData.hasEncryptionParams()) {
int version = ret.read();
if (version != 0) {
throw new IOException("Unknown crypto container!");
}
// Meta data
ret.skip(4);
byte[] iv = new byte[16];
ret.read(iv);
byte[] encoded = appDeliveryData.getEncryptionParams().getEncryptionKey().getBytes("UTF-8");
byte[] decoded = Base64.decode(encoded, Base64.DEFAULT);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(decoded, "AES");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
return new CipherInputStream(ret, cipher);
} else {
return ret;
}
}Example 81
| Project: Rap-ID-Android-master File: Crypto.java View source code |
/**
* 解密
* @param message
* @param key
* @return
* @throws Exception
*/
public static String decrypt(String message, String key) throws Exception {
byte[] bytesrc = convertHexString(message);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS7Padding", "BC");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("utf-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("utf-8"));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] retByte = cipher.doFinal(bytesrc);
return new String(retByte, "utf-8");
}Example 82
| Project: RapidFTR-Android-master File: EncryptionUtil.java View source code |
/**
* Reference: http://nelenkov.blogspot.in/2012/04/using-password-based-encryption-on.html
* NOTE: Using the seed as both Salt & IV, since we have no space to store the Salt & IV in the encrypted data
*/
public static Cipher getCipher(String password, String seed, int mode) throws IOException, GeneralSecurityException {
byte salt[] = seed.getBytes();
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, KEY_ITERATION_COUNT, KEY_LENGTH);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY_ALGORITHM);
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
SecretKey key = new SecretKeySpec(keyBytes, SECRET_KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte[] iv = paddedByteArray(seed, cipher.getBlockSize());
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(mode, key, ivSpec);
return cipher;
}Example 83
| Project: RipplePower-master File: Shacal2.java View source code |
protected AlgorithmParameters engineGenerateParameters() {
// block size 256
byte[] iv = new byte[32];
if (random == null) {
random = new SecureRandom();
}
random.nextBytes(iv);
AlgorithmParameters params;
try {
params = createParametersInstance("Shacal2");
params.init(new IvParameterSpec(iv));
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return params;
}Example 84
| Project: scumd-master File: BaseCipher.java View source code |
public void init(Mode mode, byte[] key, byte[] iv) throws Exception {
key = resize(key, bsize);
iv = resize(iv, ivsize);
try {
cipher = SecurityUtils.getCipher(transformation);
cipher.init((mode == Mode.Encrypt ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE), new SecretKeySpec(key, algorithm), new IvParameterSpec(iv));
} catch (Exception e) {
cipher = null;
throw e;
}
}Example 85
| Project: shopizer-master File: EncryptionImpl.java View source code |
@Override
public String encrypt(String value) throws Exception {
// value = StringUtils.rightPad(value, 16,"*");
// Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
// NEED TO UNDERSTAND WHY PKCS5Padding DOES NOT WORK
Cipher cipher = Cipher.getInstance(CYPHER_SPEC);
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), KEY_SPEC);
IvParameterSpec ivSpec = new IvParameterSpec(IV_P.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] inpbytes = value.getBytes();
byte[] encrypted = cipher.doFinal(inpbytes);
return new String(bytesToHex(encrypted));
}Example 86
| Project: SprintNBA-master File: DESEncrypt.java View source code |
public static String encode(String key, String data) {
if (data == null)
return null;
try {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// key的长度ä¸?能够å°?于8ä½?å—节
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
AlgorithmParameterSpec paramSpec = iv;
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
byte[] bytes = cipher.doFinal(data.getBytes());
return byte2hex(bytes);
} catch (Exception e) {
e.printStackTrace();
return data;
}
}Example 87
| Project: waspdb-master File: CipherManager.java View source code |
protected Cipher getDecCipher(byte[] iv) {
try {
Cipher cipher = Cipher.getInstance(cipher_algorithm);
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, ivParams);
return cipher;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}Example 88
| Project: wechat-master File: DES.java View source code |
/**
* æ•°æ?®åР坆
*
* @param encryptString
* @return
* @throws Exception
*/
public static String encryptDES(String encryptString) throws Exception {
IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key = new SecretKeySpec(getkeys().getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
return BASE64.encode(encryptedData);
}Example 89
| Project: ABPlayer-master File: Crypto.java View source code |
private void setupCrypto(SecretKey key) {
byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
try {
ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
} catch (Exception e) {
ecipher = null;
Log.e("setupCrypto", e);
}
}Example 90
| Project: AcademicTorrents-Downloader-master File: PEMUtilities.java View source code |
static byte[] crypt(boolean encrypt, String provider, byte[] bytes, char[] password, String dekAlgName, byte[] iv) throws IOException {
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
String alg;
String blockMode = "CBC";
String padding = "PKCS5Padding";
Key sKey;
// Figure out block mode and padding.
if (dekAlgName.endsWith("-CFB")) {
blockMode = "CFB";
padding = "NoPadding";
}
if (dekAlgName.endsWith("-ECB") || "DES-EDE".equals(dekAlgName) || "DES-EDE3".equals(dekAlgName)) {
// ECB is actually the default (though seldom used) when OpenSSL
// uses DES-EDE (des2) or DES-EDE3 (des3).
blockMode = "ECB";
paramSpec = null;
}
if (dekAlgName.endsWith("-OFB")) {
blockMode = "OFB";
padding = "NoPadding";
}
// Figure out algorithm and key size.
if (dekAlgName.startsWith("DES-EDE")) {
alg = "DESede";
// "DES-EDE" is actually des2 in OpenSSL-speak!
// "DES-EDE3" is des3.
boolean des2 = !dekAlgName.startsWith("DES-EDE3");
sKey = getKey(password, alg, 24, iv, des2);
} else if (dekAlgName.startsWith("DES-")) {
alg = "DES";
sKey = getKey(password, alg, 8, iv);
} else if (dekAlgName.startsWith("BF-")) {
alg = "Blowfish";
sKey = getKey(password, alg, 16, iv);
} else if (dekAlgName.startsWith("RC2-")) {
alg = "RC2";
int keyBits = 128;
if (dekAlgName.startsWith("RC2-40-")) {
keyBits = 40;
} else if (dekAlgName.startsWith("RC2-64-")) {
keyBits = 64;
}
sKey = getKey(password, alg, keyBits / 8, iv);
if (// ECB block mode
paramSpec == null) {
paramSpec = new RC2ParameterSpec(keyBits);
} else {
paramSpec = new RC2ParameterSpec(keyBits, iv);
}
} else if (dekAlgName.startsWith("AES-")) {
alg = "AES";
byte[] salt = iv;
if (salt.length > 8) {
salt = new byte[8];
System.arraycopy(iv, 0, salt, 0, 8);
}
int keyBits;
if (dekAlgName.startsWith("AES-128-")) {
keyBits = 128;
} else if (dekAlgName.startsWith("AES-192-")) {
keyBits = 192;
} else if (dekAlgName.startsWith("AES-256-")) {
keyBits = 256;
} else {
throw new IOException("unknown AES encryption with private key");
}
sKey = getKey(password, "AES", keyBits / 8, salt);
} else {
throw new IOException("unknown encryption with private key");
}
String transformation = alg + "/" + blockMode + "/" + padding;
try {
Cipher c = Cipher.getInstance(transformation, provider);
int mode = encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE;
if (// ECB block mode
paramSpec == null) {
c.init(mode, sKey);
} else {
c.init(mode, sKey, paramSpec);
}
return c.doFinal(bytes);
} catch (Exception e) {
throw new IOException("exception using cipher: " + e.toString());
}
}Example 91
| Project: AirPlay-Receiver-on-Android-master File: Crypto.java View source code |
private void setupCrypto(SecretKey key) {
byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
try {
ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
} catch (Exception e) {
ecipher = null;
Log.e("setupCrypto", e);
}
}Example 92
| Project: amazon-cognito-developer-authentication-sample-master File: AESEncryption.java View source code |
private static byte[] encrypt(String clearText, String key, byte[] iv) {
try {
Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
params.init(new IvParameterSpec(iv));
cipher.init(Cipher.ENCRYPT_MODE, getKey(key), params);
return cipher.doFinal(clearText.getBytes());
} catch (GeneralSecurityException e) {
throw new RuntimeException("Failed to encrypt.", e);
}
}Example 93
| Project: android-simple-storage-master File: SecurityUtil.java View source code |
/**
* Encrypt or Descrypt the content. <br>
*
* @param content
* The content to encrypt or descrypt.
* @param encryptionMode
* Use: {@link Cipher#ENCRYPT_MODE} or
* {@link Cipher#DECRYPT_MODE}
* @param secretKey
* Set the secret key for encryption of file content.
* <b>Important: The length must be 16 long</b>. <i>Uses SHA-256
* to generate a hash from your key and trim the result to 128
* bit (16 bytes)</i>
* @param ivx
* This is not have to be secret. It used just for better
* randomizing the cipher. You have to use the same IV parameter
* within the same encrypted and written files. Means, if you
* want to have the same content after descryption then the same
* IV must be used. <i>About this parameter from wiki:
* https://en.wikipedia.org/wiki/Block_cipher_modes_of_operation
* #Initialization_vector_.28IV.29</i> <b>Important: The length
* must be 16 long</b>
* @return
*/
public static byte[] encrypt(byte[] content, int encryptionMode, final byte[] secretKey, final byte[] ivx) {
if (secretKey.length != 16 || ivx.length != 16) {
throw new RuntimeException("Set the encryption parameters correctly. The must be 16 length long each");
}
try {
final SecretKey secretkey = new SecretKeySpec(secretKey, CipherAlgorithmType.AES.getAlgorithmName());
final IvParameterSpec IV = new IvParameterSpec(ivx);
final String transformation = CipherTransformationType.AES_CBC_PKCS5Padding;
final Cipher decipher = Cipher.getInstance(transformation);
decipher.init(encryptionMode, secretkey, IV);
final byte[] plainText = decipher.doFinal(content);
return plainText;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Failed to encrypt/descrypt - Unknown Algorithm", e);
} catch (NoSuchPaddingException e) {
throw new RuntimeException("Failed to encrypt/descrypt- Unknown Padding", e);
} catch (InvalidKeyException e) {
throw new RuntimeException("Failed to encrypt/descrypt - Invalid Key", e);
} catch (InvalidAlgorithmParameterException e) {
throw new RuntimeException("Failed to encrypt/descrypt - Invalid Algorithm Parameter", e);
} catch (IllegalBlockSizeException e) {
throw new RuntimeException("Failed to encrypt/descrypt", e);
} catch (BadPaddingException e) {
throw new RuntimeException("Failed to encrypt/descrypt", e);
}
}Example 94
| Project: AndroidLibraryProject-master File: JavaDESEncryption.java View source code |
public static void cryptFile(String filePath) {
//"C:/Users/nikos7/Desktop/input.txt";
String clearFile = "/mnt/sdcard/Notes/contactbkp.db";
//"C:/Users/nikos7/Desktop/encrypted.txt";
String encryptedFile = "/mnt/sdcard/Notes/contactbkpE.db";
//"C:/Users/nikos7/Desktop/decrypted.txt";
String decryptedFile = "/mnt/sdcard/Notes/contactbkpD.db";
//File
try {
SecretKey secret_key = KeyGenerator.getInstance("DES").generateKey();
AlgorithmParameterSpec alogrithm_specs = new IvParameterSpec(initialization_vector);
// set encryption mode ...
encrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");
encrypt.init(Cipher.ENCRYPT_MODE, secret_key, alogrithm_specs);
// set decryption mode
decrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");
decrypt.init(Cipher.DECRYPT_MODE, secret_key, alogrithm_specs);
// encrypt file
encrypt(new FileInputStream(clearFile), new FileOutputStream(encryptedFile));
// decrypt file
decrypt(new FileInputStream(encryptedFile), new FileOutputStream(decryptedFile));
System.out.println("End of Encryption/Decryption procedure!");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}Example 95
| Project: AndroidStudyDemo-master File: DES.java View source code |
/**
* DESç®—æ³•ï¼ŒåŠ å¯†
* @param data å¾…åŠ å¯†å—符串
* @param key åŠ å¯†ç§?钥,长度ä¸?能够å°?于8ä½?
* @return åŠ å¯†å?Žçš„å—节数组,一般结å?ˆBase64ç¼–ç ?使用
* @throws Exception
*/
public static String encode(String key, String data) {
if (data == null)
return null;
try {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// key的长度ä¸?能够å°?于8ä½?å—节
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
AlgorithmParameterSpec paramSpec = iv;
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
byte[] bytes = cipher.doFinal(data.getBytes());
return byte2String(bytes);
} catch (Exception e) {
e.printStackTrace();
return data;
}
}Example 96
| Project: Android_App_OpenSource-master File: CyptoUtils.java View source code |
/**
* DESç®—æ³•ï¼ŒåŠ å¯†
*
* @param data å¾…åŠ å¯†å—符串
* @param key åŠ å¯†ç§?钥,长度ä¸?能够å°?于8ä½?
* @return åŠ å¯†å?Žçš„å—节数组,一般结å?ˆBase64ç¼–ç ?使用
* @throws InvalidAlgorithmParameterException
* @throws Exception
*/
public static String encode(String key, String data) {
if (data == null)
return null;
try {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
//key的长度ä¸?能够å°?于8ä½?å—节
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
AlgorithmParameterSpec paramSpec = iv;
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
byte[] bytes = cipher.doFinal(data.getBytes());
return byte2hex(bytes);
} catch (Exception e) {
e.printStackTrace();
return data;
}
}Example 97
| Project: appone-master File: Crypto.java View source code |
private void setupCrypto(SecretKey key) {
byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
try {
ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
} catch (Exception e) {
ecipher = null;
Log.e("setupCrypto", e);
}
}Example 98
| Project: AppWorkUtils-master File: Crypto.java View source code |
/**
* Decrypt data which has been encrypted width
* {@link Crypto#encrypt(String, byte[], byte[])}
*
* @param b
* data to decrypt
* @param key
* to use (128Bit (16 Byte))
* @param iv
* to use (128Bit (16 Byte))
* @return
*/
public static String decrypt(final byte[] b, final byte[] key, final byte[] iv) {
Cipher cipher;
try {
final IvParameterSpec ivSpec = new IvParameterSpec(iv);
final SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
return new String(cipher.doFinal(b), "UTF-8");
} catch (final Exception e) {
Log.exception(Level.WARNING, e);
final IvParameterSpec ivSpec = new IvParameterSpec(iv);
final SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
try {
cipher = Cipher.getInstance("AES/CBC/nopadding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
return new String(cipher.doFinal(b), "UTF-8");
} catch (final Exception e1) {
Log.exception(Level.WARNING, e1);
}
}
return null;
}Example 99
| Project: aws-dynamodb-encryption-java-master File: TestDelegatedKey.java View source code |
@Override
public byte[] decrypt(byte[] cipherText, byte[] additionalAssociatedData, String algorithm) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException {
final byte ivLength = cipherText[0];
IvParameterSpec iv = new IvParameterSpec(cipherText, 1, ivLength);
Cipher cipher = Cipher.getInstance(extractAlgorithm(algorithm));
cipher.init(Cipher.DECRYPT_MODE, realKey, iv);
return cipher.doFinal(cipherText, ivLength + 1, cipherText.length - ivLength - 1);
}Example 100
| Project: axelor-business-suite-master File: AESTest2.java View source code |
@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 };
// Where you get this from is beyond
byte[] sessionKey = CRYPTO_KEY_EXT;
// the scope of this post
// Ditto
byte[] iv = CRYPTO_IV_EXT;
// Whatever you want to
byte[] plaintext = message.getBytes("UTF8");
// 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);
}Example 101
| Project: azure-sdk-for-java-samples-master File: EncryptionHelper.java View source code |
public static InputStream encryptFile(InputStream inputStream, byte[] key, byte[] initializationVector) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(initializationVector);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec);
CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
return cipherInputStream;
}