下面列出了java.security.spec.InvalidParameterSpecException#javax.crypto.spec.IvParameterSpec 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static String decrypt(byte[] key, byte[] initVector, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector);
SecretKeySpec skeySpec = new SecretKeySpec(key, SECRET_KEY_SPEC);
Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* Initiate the Cipher object for PBKDF2 algorithm using given "mode".
*
* @param mode Cipher mode: encrypt or decrypt
* @return Cipher object for PBKDF2 algorithm
* @throws GeneralSecurityException all security exceptions are thrown.
*/
@Override
protected Cipher initCipher(int mode) throws GeneralSecurityException {
Provider provider = Security.getProvider("SunJCE");
if (provider == null) {
throw new RuntimeException("SunJCE provider does not exist.");
}
// Generate secret key
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(),
salt, DEFAULT_ITERATION, PKDF2_DEFAULT_KEY_LEN);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(baseAlgo);
SecretKey key = keyFactory.generateSecret(pbeKeySpec);
// get Cipher instance
Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION, provider);
cipher.init(mode,
new SecretKeySpec(key.getEncoded(),KEY_ALGORITHM),
new IvParameterSpec(iv));
return cipher;
}
/**
* 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;
}
}
/**
* Initiate the Cipher object for PBKDF2 algorithm using given "mode".
*
* @param mode Cipher mode: encrypt or decrypt
* @return Cipher object for PBKDF2 algorithm
* @throws GeneralSecurityException all security exceptions are thrown.
*/
@Override
protected Cipher initCipher(int mode) throws GeneralSecurityException {
Provider provider = Security.getProvider("SunJCE");
if (provider == null) {
throw new RuntimeException("SunJCE provider does not exist.");
}
// Generate secret key
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(),
salt, DEFAULT_ITERATION, PKDF2_DEFAULT_KEY_LEN);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(baseAlgo);
SecretKey key = keyFactory.generateSecret(pbeKeySpec);
// get Cipher instance
Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION, provider);
cipher.init(mode,
new SecretKeySpec(key.getEncoded(),KEY_ALGORITHM),
new IvParameterSpec(iv));
return cipher;
}
/**
* Initiate the Cipher object for PBKDF2 algorithm using given "mode".
*
* @param mode Cipher mode: encrypt or decrypt
* @return Cipher object for PBKDF2 algorithm
* @throws GeneralSecurityException all security exceptions are thrown.
*/
@Override
protected Cipher initCipher(int mode) throws GeneralSecurityException {
Provider provider = Security.getProvider("SunJCE");
if (provider == null) {
throw new RuntimeException("SunJCE provider does not exist.");
}
// Generate secret key
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(),
salt, DEFAULT_ITERATION, PKDF2_DEFAULT_KEY_LEN);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(baseAlgo);
SecretKey key = keyFactory.generateSecret(pbeKeySpec);
// get Cipher instance
Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION, provider);
cipher.init(mode,
new SecretKeySpec(key.getEncoded(),KEY_ALGORITHM),
new IvParameterSpec(iv));
return cipher;
}
@Override
protected synchronized AlgorithmParameters engineGetParameters() {
AlgorithmParameters params = null;
try {
if (iv != null) {
IvParameterSpec ivSpec = new IvParameterSpec(iv.clone());
params = AlgorithmParameters.getInstance(keyAlgo);
params.init(ivSpec);
}
} catch (GeneralSecurityException e) {
// NoSuchAlgorithmException, NoSuchProviderException
// InvalidParameterSpecException
throw new UcryptoException("Could not encode parameters", e);
}
return params;
}
/**
* getAlgorithmParameterSpec() method testing. Tests that returned value is equal
* to the value specified in the constructor.
*/
public void testGetAlgorithmParameterSpec() {
byte[] salt = new byte[] {1, 2, 3, 4, 5};
int iterationCount = 10;
// Check that the constructor works with a null AlgorithmParameterSpec and it's correctly
// returned in the getter.
PBEParameterSpec pbeps = new PBEParameterSpec(salt, iterationCount, null);
assertNull("The returned AlgorithmParameterSpec is not null, as the specified "
+ "in the constructor.",
pbeps.getParameterSpec());
// Check that a non-null AlgorithmParameterSpec is returned correctly.
AlgorithmParameterSpec aps = new IvParameterSpec(new byte[16]);
pbeps = new PBEParameterSpec(salt, iterationCount, aps);
assertSame("The returned AlgorithmParameterSpec is not the same as the specified "
+ "in the constructor.",
aps, pbeps.getParameterSpec());
}
/**
* DES解密字符串
*
* @param password 解密密码,长度不能够小于8位
* @param data 待解密字符串
* @return 解密后内容
*/
public static String decrypt(String password, String data) {
if (password == null || password.length() < 8) {
throw new RuntimeException("加密失败,key不能小于8位");
}
if (data == null)
return null;
try {
Key secretKey = generateKey(password);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHARSET))), CHARSET);
} catch (Exception e) {
e.printStackTrace();
return data;
}
}
/**
* @param salt an array of random bytes to use for each (un)obfuscation
* @param applicationId application identifier, e.g. the package name
* @param deviceId device identifier. Use as many sources as possible to
* create this unique identifier.
*/
public AESObfuscator(byte[] salt, String applicationId, String deviceId) {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM);
KeySpec keySpec =
new PBEKeySpec((applicationId + deviceId).toCharArray(), salt, 1024, 256);
SecretKey tmp = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM);
mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV));
mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM);
mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
} catch (GeneralSecurityException e) {
// This can't happen on a compatible Android device.
throw new RuntimeException("Invalid environment", e);
}
}
public static String DESDecrypt(String ivString, String keyString, String content) {
try {
if (Check.NuNStr(content)) {
return null;
}
IvParameterSpec iv = new IvParameterSpec(ivString.getBytes());
DESKeySpec dks = new DESKeySpec(keyString.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] result = cipher.doFinal(hexStr2ByteArr(content));
return new String(result, "utf-8");
} catch (Exception e) {
LOGGER.error("ENCRYPT ERROR:"+e);
}
return null;
}
public AES() {
try {
keyfactory = SecretKeyFactory.getInstance(KEY_GENERATION_ALG);
sk = keyfactory.generateSecret(myKeyspec);
} catch (NoSuchAlgorithmException nsae) {
Log.e("no key factory support for PBEWITHSHAANDTWOFISH-CBC");
} catch (InvalidKeySpecException ikse) {
Log.e("invalid key spec for PBEWITHSHAANDTWOFISH-CBC");
}
// This is our secret key. We could just save this to a file instead of
// regenerating it
// each time it is needed. But that file cannot be on the device (too
// insecure). It could
// be secure if we kept it on a server accessible through https.
byte[] skAsByteArray = sk.getEncoded();
skforAES = new SecretKeySpec(skAsByteArray, "AES");
IV = new IvParameterSpec(iv);
}
/**
* Obtains an initialized DES cipher.
*
* @param encryptMode true if encryption is desired, false is decryption
* is desired.
* @param key the bytes for the DES key
* @param ivBytes the initial vector bytes
*/
private final Cipher getInitializedDes(boolean encryptMode, byte[] key,
byte[] ivBytes)
throws GSSException {
try {
IvParameterSpec iv = new IvParameterSpec(ivBytes);
SecretKey jceKey = (SecretKey) (new SecretKeySpec(key, "DES"));
Cipher desCipher = Cipher.getInstance("DES/CBC/NoPadding");
desCipher.init(
(encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE),
jceKey, iv);
return desCipher;
} catch (GeneralSecurityException e) {
GSSException ge = new GSSException(GSSException.FAILURE, -1,
e.getMessage());
ge.initCause(e);
throw ge;
}
}
/**
* Obtains an initialized DES cipher.
*
* @param encryptMode true if encryption is desired, false is decryption
* is desired.
* @param key the bytes for the DES key
* @param ivBytes the initial vector bytes
*/
private final Cipher getInitializedDes(boolean encryptMode, byte[] key,
byte[] ivBytes)
throws GSSException {
try {
IvParameterSpec iv = new IvParameterSpec(ivBytes);
SecretKey jceKey = (SecretKey) (new SecretKeySpec(key, "DES"));
Cipher desCipher = Cipher.getInstance("DES/CBC/NoPadding");
desCipher.init(
(encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE),
jceKey, iv);
return desCipher;
} catch (GeneralSecurityException e) {
GSSException ge = new GSSException(GSSException.FAILURE, -1,
e.getMessage());
ge.initCause(e);
throw ge;
}
}
protected String encrypt(final String value, final String hashedKey) {
if (value == null) {
return null;
}
try {
final Cipher cipher = getCipherObject();
final byte[] ivValue = generateIV(this.ivSize);
final IvParameterSpec ivSpec = new IvParameterSpec(ivValue);
cipher.init(Cipher.ENCRYPT_MODE, this.key, ivSpec);
final byte[] ciphertext = cipher.doFinal(value.getBytes());
final byte[] ivCiphertext = new byte[INTEGER_LEN + this.ivSize + ciphertext.length];
System.arraycopy(int2byte(this.ivSize), 0, ivCiphertext, 0, INTEGER_LEN);
System.arraycopy(ivValue, 0, ivCiphertext, INTEGER_LEN, this.ivSize);
System.arraycopy(ciphertext, 0, ivCiphertext, INTEGER_LEN + this.ivSize, ciphertext.length);
return new String(encode(ivCiphertext));
} catch(final Exception e) {
throw new RuntimeException(e);
}
}
private static byte[] performCipherOperation(
int mode, byte[] iv, byte[] encryptKey, byte[] text) throws CipherException {
try {
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey, "AES");
cipher.init(mode, secretKeySpec, ivParameterSpec);
return cipher.doFinal(text);
} catch (NoSuchPaddingException
| NoSuchAlgorithmException
| InvalidAlgorithmParameterException
| InvalidKeyException
| BadPaddingException
| IllegalBlockSizeException e) {
throw new CipherException("Error performing cipher operation", e);
}
}
/**
* @param salt an array of random bytes to use for each (un)obfuscation
* @param applicationId application identifier, e.g. the package name
* @param deviceId device identifier. Use as many sources as possible to
* create this unique identifier.
*/
public AESObfuscator(byte[] salt, String applicationId, String deviceId) {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM);
KeySpec keySpec =
new PBEKeySpec((applicationId + deviceId).toCharArray(), salt, 1024, 256);
SecretKey tmp = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM);
mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV));
mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM);
mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
} catch (GeneralSecurityException e) {
// This can't happen on a compatible Android device.
throw new RuntimeException("Invalid environment", e);
}
}
/**
* Encrypts a given string based on a shared secret.
*
* @param text
* the text to encrypt
* @return the iv and encrypted text as Base64 separated with ':'.
* @throws GeneralSecurityException
* on any problem during encryption
*/
public static String encrypt(String text) throws GeneralSecurityException {
if (text == null) {
return null;
}
byte[] decrypted;
try {
decrypted = text.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
byte[] iv = new byte[IV_BYTES];
new SecureRandom().nextBytes(iv);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] encrypted = cipher.doFinal(decrypted);
return new String(Base64.encodeBase64(iv)) + ":"
+ new String(Base64.encodeBase64(encrypted));
}
/**
* AES 自定义秘钥解密
*
* @param ciphertext 密文
* @param key 秘钥(必须16位)
* @return 明文
*/
public static String decrypt(String ciphertext, String key) {
if (StringUtils.isEmpty(ciphertext) || StringUtils.isEmpty(key) || 16 != key.length()) {
return null;
}
try {
byte[] encryptedBytes = Base64.getDecoder().decode(ciphertext);
byte[] enCodeFormat = key.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, AES);
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
Cipher cipher = Cipher.getInstance(CIPHER);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] result = cipher.doFinal(encryptedBytes);
return new String(result, ENCODEING);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
public String encryptText(final String text) {
if (text == null || text.isEmpty()) {
return text;
}
try {
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
final SecretKeySpec keySpec = new SecretKeySpec(this.keyIvPair.getKeyBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(this.keyIvPair.getIvBytes()));
final byte[] encryptedBytes = cipher.doFinal(text.getBytes());
final byte[] ivcipher = concat(this.keyIvPair.getIvBytes(), encryptedBytes);
final byte[] hmac = generateHMAC(this.authenticationKey, ivcipher);
return Base64.encodeBase64URLSafeString(concat(ivcipher, hmac));
} catch (Exception e) {
s_logger.error("Unexpected exception ", e);
return null;
}
}
/**
* Obtains an initialized DES cipher.
*
* @param encryptMode true if encryption is desired, false is decryption
* is desired.
* @param key the bytes for the DES key
* @param ivBytes the initial vector bytes
*/
private final Cipher getInitializedDes(boolean encryptMode, byte[] key,
byte[] ivBytes)
throws GSSException {
try {
IvParameterSpec iv = new IvParameterSpec(ivBytes);
SecretKey jceKey = (SecretKey) (new SecretKeySpec(key, "DES"));
Cipher desCipher = Cipher.getInstance("DES/CBC/NoPadding");
desCipher.init(
(encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE),
jceKey, iv);
return desCipher;
} catch (GeneralSecurityException e) {
GSSException ge = new GSSException(GSSException.FAILURE, -1,
e.getMessage());
ge.initCause(e);
throw ge;
}
}
/**
* 3DES解密
* @param encryptText 加密文本
* @param secretKey 密钥
* @param iv 向量
* @return 解密后明文,失败返回null
*/
public static String decode(String encryptText, String secretKey, String iv) {
String result = null;
try {
DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("desede");
Key desKey = secretKeyFactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, desKey, ips);
byte[] decryptData = cipher.doFinal(Base64Utils.decodeFromString(encryptText));
result = new String(decryptData, encoding);
} catch (Exception e) {
log.error("DesCbcUtil decode error : {}", e.getMessage());
}
return result;
}
/**
* DES加密
* @param HexString 字符串(16位16进制字符串)
* @param keyStr 密钥16个1
* @param keyENCODED Keybyte转换编码
* @param HexStringENCODED 要加密值的转换byte编码
* @param CipherInstanceType 需要加密类型
* @return
* @throws Exception
*/
public static String ENCRYPTMethod(String HexString, String keyStr,String keyENCODED,String HexStringENCODED,String CipherInstanceType)
throws Exception {
String jmstr = "";
try {
byte[] theKey = null;
String jqstr = getstrByte(keyStr).substring(0,8).toUpperCase();
theKey = jqstr.getBytes(keyENCODED);
Cipher cipher = Cipher.getInstance(CipherInstanceType);
DESKeySpec desKeySpec = new DESKeySpec(theKey);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(theKey);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] theCph = cipher.doFinal(HexString.getBytes(HexStringENCODED));
jmstr = toHexString(theCph).toUpperCase();
jmstr = toHexString(theCph);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return jmstr;
}
/**
* Decrypt the value.
*
* @param value the value
* @param hashedKey the hashed key
* @return the string
*/
protected String decrypt(final String value, final String hashedKey) {
if (value == null) {
return null;
}
try {
final Cipher cipher = getCipherObject();
final byte[] ivCiphertext = CompressionUtils.decodeBase64ToByteArray(value);
final int ivSize = byte2int(Arrays.copyOfRange(ivCiphertext, 0, INTEGER_LEN));
final byte[] ivValue = Arrays.copyOfRange(ivCiphertext, INTEGER_LEN, (INTEGER_LEN + ivSize));
final byte[] ciphertext = Arrays.copyOfRange(ivCiphertext, INTEGER_LEN + ivSize, ivCiphertext.length);
final IvParameterSpec ivSpec = new IvParameterSpec(ivValue);
cipher.init(Cipher.DECRYPT_MODE, this.key, ivSpec);
final byte[] plaintext = cipher.doFinal(ciphertext);
return new String(plaintext, Charset.defaultCharset());
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
public AesFlushingCipher(int mode, byte[] secretKey, long nonce, long offset) {
try {
cipher = Cipher.getInstance("AES/CTR/NoPadding");
blockSize = cipher.getBlockSize();
zerosBlock = new byte[blockSize];
flushedBlock = new byte[blockSize];
long counter = offset / blockSize;
int startPadding = (int) (offset % blockSize);
cipher.init(
mode,
new SecretKeySpec(secretKey, Util.splitAtFirst(cipher.getAlgorithm(), "/")[0]),
new IvParameterSpec(getInitializationVector(nonce, counter)));
if (startPadding != 0) {
updateInPlace(new byte[startPadding], 0, startPadding);
}
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
| InvalidAlgorithmParameterException e) {
// Should never happen.
throw new RuntimeException(e);
}
}
/**
* @param salt an array of random bytes to use for each (un)obfuscation
* @param applicationId application identifier, e.g. the package name
* @param deviceId device identifier. Use as many sources as possible to
* create this unique identifier.
*/
public AESObfuscator(byte[] salt, String applicationId, String deviceId) {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM);
KeySpec keySpec =
new PBEKeySpec((applicationId + deviceId).toCharArray(), salt, 1024, 256);
SecretKey tmp = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM);
mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV));
mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM);
mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
} catch (GeneralSecurityException e) {
// This can't happen on a compatible Android device.
throw new RuntimeException("Invalid environment", e);
}
}
/**
* 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;
}
}
/**
* Obtains an initialized DES cipher.
*
* @param encryptMode true if encryption is desired, false is decryption
* is desired.
* @param key the bytes for the DES key
* @param ivBytes the initial vector bytes
*/
private final Cipher getInitializedDes(boolean encryptMode, byte[] key,
byte[] ivBytes)
throws GSSException {
try {
IvParameterSpec iv = new IvParameterSpec(ivBytes);
SecretKey jceKey = (SecretKey) (new SecretKeySpec(key, "DES"));
Cipher desCipher = Cipher.getInstance("DES/CBC/NoPadding");
desCipher.init(
(encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE),
jceKey, iv);
return desCipher;
} catch (GeneralSecurityException e) {
GSSException ge = new GSSException(GSSException.FAILURE, -1,
e.getMessage());
ge.initCause(e);
throw ge;
}
}
public static byte[] aes256decrypt(byte[] ivBytes, byte[] keyBytes, byte[] textBytes)
throws UnsupportedEncodingException,
NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
IllegalBlockSizeException,
BadPaddingException {
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
return cipher.doFinal(textBytes);
}
public XmppAxolotlPlaintextMessage decrypt(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
XmppAxolotlPlaintextMessage plaintextMessage = null;
byte[] key = unpackKey(session, sourceDeviceId);
if (key != null) {
try {
if (key.length < 32) {
throw new OutdatedSenderException("Key did not contain auth tag. Sender needs to update their OMEMO client");
}
final int authTagLength = key.length - 16;
byte[] newCipherText = new byte[key.length - 16 + ciphertext.length];
byte[] newKey = new byte[16];
System.arraycopy(ciphertext, 0, newCipherText, 0, ciphertext.length);
System.arraycopy(key, 16, newCipherText, ciphertext.length, authTagLength);
System.arraycopy(key, 0, newKey, 0, newKey.length);
ciphertext = newCipherText;
key = newKey;
final Cipher cipher = Compatibility.twentyEight() ? Cipher.getInstance(CIPHERMODE) : Cipher.getInstance(CIPHERMODE, PROVIDER);
SecretKeySpec keySpec = new SecretKeySpec(key, KEYTYPE);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
String plaintext = new String(cipher.doFinal(ciphertext));
plaintextMessage = new XmppAxolotlPlaintextMessage(Config.OMEMO_PADDING ? plaintext.trim() : plaintext, session.getFingerprint());
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
| InvalidAlgorithmParameterException | IllegalBlockSizeException
| BadPaddingException | NoSuchProviderException e) {
throw new CryptoFailedException(e);
}
}
return plaintextMessage;
}
/**
* Constructor for AESEncryption.
* This class it to be used for encrypting/decrypting data.
*
* @throws Exception if something fails
*/
public AESEncryption(GuildSettings gs) throws Exception {
String SECRET_KEY_2 = gs.getPrivateKey();
ivParameterSpec = new IvParameterSpec(SECRET_KEY_1.getBytes(StandardCharsets.UTF_8));
secretKeySpec = new SecretKeySpec(SECRET_KEY_2.getBytes(StandardCharsets.UTF_8), "AES");
cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
}