下面列出了java.security.spec.InvalidParameterSpecException#javax.crypto.SecretKey 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void explicitWrappingAlgorithmPkcs2() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<>();
desc.put(WrappedRawMaterials.KEY_WRAPPING_ALGORITHM, "RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
AsymmetricStaticProvider prov = new AsymmetricStaticProvider(encryptionPair, sigPair, desc);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertThat(encryptionKey, is(not(nullValue())));
assertEquals(sigPair.getPrivate(), eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals("RSA/ECB/OAEPWithSHA-256AndMGF1Padding", eMat.getMaterialDescription().get(WrappedRawMaterials.KEY_WRAPPING_ALGORITHM));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(sigPair.getPublic(), dMat.getVerificationKey());
}
/**
* 加密方法
* @param src 源数据的字节数组
* @param password
* @return
*/
public static byte[] encryptMode(byte[] src, String password) {
try {
SecretKey deskey = new SecretKeySpec(build3DesKey(password), Algorithm); //生成密钥
Cipher c1 = Cipher.getInstance(Algorithm); //实例化负责加密/解密的Cipher工具类
c1.init(Cipher.ENCRYPT_MODE, deskey); //初始化为加密模式
return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return null;
}
@Test
public void explicitContentKeyLength128() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<>();
desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/128");
AsymmetricStaticProvider prov = new AsymmetricStaticProvider(encryptionPair, sigPair, desc);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertThat(encryptionKey, is(not(nullValue())));
assertEquals(16, encryptionKey.getEncoded().length); // 128 Bits
assertEquals(sigPair.getPrivate(), eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals("AES", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(sigPair.getPublic(), dMat.getVerificationKey());
}
@Test
public void externalJweAes128CbcHmacSha256Test() throws JWEException {
String externalJwe = "eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..qysUrI1iVtiG4Z4jyr7XXg.apdNSQhR7WDMg6IHf5aLVI0gGp6JuOHYmIUtflns4WHmyxOOnh_GShLI6DWaK_SiywTV5gZvZYtl8H8Iv5fTfLkc4tiDDjbdtmsOP7tqyRxVh069gU5UvEAgmCXbIKALutgYXcYe2WM4E6BIHPTSt8jXdkktFcm7XHiD7mpakZyjXsG8p3XVkQJ72WbJI_t6.Ks6gHeko7BRTZ4CFs5ijRA";
System.out.println("External encoded content length: " + externalJwe.length());
final SecretKey aesKey = new SecretKeySpec(AES_128_KEY, "AES");
final SecretKey hmacKey = new SecretKeySpec(HMAC_SHA256_KEY, "HMACSHA2");
JWE jwe = new JWE();
jwe.getKeyStorage()
.setCEKKey(aesKey, JWEKeyStorage.KeyUse.ENCRYPTION)
.setCEKKey(hmacKey, JWEKeyStorage.KeyUse.SIGNATURE);
jwe.verifyAndDecodeJwe(externalJwe);
String decodedContent = new String(jwe.getContent(), StandardCharsets.UTF_8);
Assert.assertEquals(PAYLOAD, decodedContent);
}
/**
* Method engineResolveSecretKey
*
* @param element
* @param baseURI
* @param storage
* @return resolved SecretKey key or null if no {@link SecretKey} could be obtained
*
* @throws KeyResolverException
*/
public SecretKey engineResolveSecretKey(
Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
}
if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
String keyName = element.getFirstChild().getNodeValue();
try {
Key key = keyStore.getKey(keyName, password);
if (key instanceof SecretKey) {
return (SecretKey) key;
}
} catch (Exception e) {
log.log(java.util.logging.Level.FINE, "Cannot recover the key", e);
}
}
log.log(java.util.logging.Level.FINE, "I can't");
return null;
}
/**
* A function that generates password-based AES & HMAC keys. It prints out exceptions but
* doesn't throw them since none should be encountered. If they are
* encountered, the return value is null.
*
* @param password The password to derive the keys from.
* @return The AES & HMAC keys.
* @throws GeneralSecurityException if AES is not implemented on this system,
* or a suitable RNG is not available
*/
public static SecretKeys generateKeyFromPassword(String password, byte[] salt) throws GeneralSecurityException {
fixPrng();
//Get enough random bytes for both the AES key and the HMAC key:
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt,
PBE_ITERATION_COUNT, AES_KEY_LENGTH_BITS + HMAC_KEY_LENGTH_BITS);
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance(PBE_ALGORITHM);
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
// Split the random bytes into two parts:
byte[] confidentialityKeyBytes = copyOfRange(keyBytes, 0, AES_KEY_LENGTH_BITS /8);
byte[] integrityKeyBytes = copyOfRange(keyBytes, AES_KEY_LENGTH_BITS /8, AES_KEY_LENGTH_BITS /8 + HMAC_KEY_LENGTH_BITS /8);
//Generate the AES key
SecretKey confidentialityKey = new SecretKeySpec(confidentialityKeyBytes, CIPHER);
//Generate the HMAC key
SecretKey integrityKey = new SecretKeySpec(integrityKeyBytes, HMAC_ALGORITHM);
return new SecretKeys(confidentialityKey, integrityKey);
}
private static void match(int lineNumber, byte[] out, Object res)
throws Exception {
if ((out == null) || (res == null)) {
if (out != res) {
throw new Exception("null mismatch line " + lineNumber);
} else {
return;
}
}
byte[] b;
if (res instanceof SecretKey) {
b = ((SecretKey)res).getEncoded();
} else if (res instanceof IvParameterSpec) {
b = ((IvParameterSpec)res).getIV();
} else {
throw new Exception(res.getClass().getName());
}
if (Arrays.equals(out, b) == false) {
throw new Exception("mismatch line " + lineNumber);
}
}
/**
* HmacSHA384加密
*
* @param data
* 待加密数据
* @param key
* 密钥
*
* @return byte[] 消息摘要
*
* @throws Exception
*/
public static byte[] encodeHmacSHA384(byte[] data, byte[] key)
throws NoSuchAlgorithmException, InvalidKeyException {
// 还原密钥
SecretKey secretKey = new SecretKeySpec(key, "HmacSHA384");
// 实例化Mac
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
// 初始化Mac
mac.init(secretKey);
// 执行消息摘要
return mac.doFinal(data);
}
/**
* Returns a specification (key material) of the given key
* in the requested format.
*
* @param key the key
*
* @param keySpec the requested format in which the key material shall be
* returned
*
* @return the underlying key specification (key material) in the
* requested format
*
* @exception InvalidKeySpecException if the requested key
* specification is inappropriate for the given key, or the
* given key cannot be processed (e.g., the given key has an
* unrecognized algorithm or format).
*/
protected KeySpec engineGetKeySpec(SecretKey key, Class<?> keySpecCl)
throws InvalidKeySpecException {
if (key instanceof javax.crypto.interfaces.PBEKey) {
// Check if requested key spec is amongst the valid ones
if ((keySpecCl != null)
&& PBEKeySpec.class.isAssignableFrom(keySpecCl)) {
javax.crypto.interfaces.PBEKey pKey =
(javax.crypto.interfaces.PBEKey) key;
return new PBEKeySpec
(pKey.getPassword(), pKey.getSalt(),
pKey.getIterationCount(), pKey.getEncoded().length*8);
} else {
throw new InvalidKeySpecException("Invalid key spec");
}
} else {
throw new InvalidKeySpecException("Invalid key " +
"format/algorithm");
}
}
protected Cipher getCipher(byte[] key, byte[] ivec, int mode)
throws GeneralSecurityException {
// NoSuchAlgorithException
SecretKeyFactory factory = SecretKeyFactory.getInstance("desede");
// InvalidKeyException
KeySpec spec = new DESedeKeySpec(key, 0);
// InvalidKeySpecException
SecretKey secretKey = factory.generateSecret(spec);
// IV
if (ivec == null) {
ivec = ZERO_IV;
}
// NoSuchAlgorithmException, NoSuchPaddingException
// NoSuchProviderException
Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
IvParameterSpec encIv = new IvParameterSpec(ivec, 0, ivec.length);
// InvalidKeyException, InvalidAlgorithParameterException
cipher.init(mode, secretKey, encIv);
return cipher;
}
public String getEncryptedUsageStatistics(Request request, Response response) throws Exception {
HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
Map<String, Object> body = readRequestBodyAsJSON(request);
String signature = (String) body.get(SIGNATURE_KEY);
String publicKey = (String) body.get(SUBORDINATE_PUBLIC_KEY);
boolean isVerified = verifySignatureAndPublicKey(signature, publicKey, result);
if (isVerified) {
SecretKey secretKey = EncryptionHelper.generateAESKey();
String aesEncryptedData = EncryptionHelper.encryptUsingAES(secretKey, getUsageStatistics(request, response));
String rsaEncryptedKey = EncryptionHelper.encryptUsingRSA(Base64.getEncoder().encodeToString(secretKey.getEncoded()), publicKey);
return jsonizeAsTopLevelObject(request, writer -> EncryptedDataRepresenter.toJSON(writer, aesEncryptedData, rsaEncryptedKey));
}
return renderHTTPOperationResult(result, request, response);
}
private static Cipher getPBECipher(byte[] salt, int cipherMode) throws Exception
{
String MYPBEALG = "PBEWithSHA1AndDESede";
int count = 32;// hash iteration count
// Create PBE parameter set
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
PBEKeySpec pbeKeySpec = new PBEKeySpec(KEY_PASSWORD);
SecretKeyFactory keyFac = SecretKeyFactory.getInstance(MYPBEALG);
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
Cipher pbeCipher = Cipher.getInstance(MYPBEALG);
// Initialize PBE Cipher with key and parameters
pbeCipher.init(cipherMode, pbeKey, pbeParamSpec);
return pbeCipher;
}
byte[] sign(Key key, SignedInfo si, XMLSignContext context)
throws InvalidKeyException, XMLSignatureException
{
if (key == null || si == null) {
throw new NullPointerException();
}
if (!(key instanceof SecretKey)) {
throw new InvalidKeyException("key must be SecretKey");
}
if (hmac == null) {
try {
hmac = Mac.getInstance(getJCAAlgorithm());
} catch (NoSuchAlgorithmException nsae) {
throw new XMLSignatureException(nsae);
}
}
if (outputLengthSet && outputLength < getDigestLength()) {
throw new XMLSignatureException
("HMACOutputLength must not be less than " + getDigestLength());
}
hmac.init((SecretKey)key);
((DOMSignedInfo)si).canonicalize(context, new MacOutputStream(hmac));
return hmac.doFinal();
}
/**
* Method engineInitSign
*
* @param secretKey
* @throws XMLSignatureException
*/
protected void engineInitSign(Key secretKey) throws XMLSignatureException {
if (!(secretKey instanceof SecretKey)) {
String supplied = secretKey.getClass().getName();
String needed = SecretKey.class.getName();
Object exArgs[] = { supplied, needed };
throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
}
try {
this.macAlgorithm.init(secretKey);
} catch (InvalidKeyException ex) {
throw new XMLSignatureException("empty", ex);
}
}
protected byte[] encrypt(byte[] data) {
// 16 bytes is the IV size for AES256
try {
SecretKey key = loadKey();
// Random IV
SecureRandom rng = new SecureRandom();
byte[] ivBytes = new byte[16]; // 16 bytes is the IV size for AES256
rng.nextBytes(ivBytes);
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
cipher.init(true, new ParametersWithIV(new KeyParameter(key.getEncoded()), ivBytes));
byte[] encryptedData = cipherData(cipher, data);
byte[] encryptedDataWithIV = new byte[encryptedData.length + ivBytes.length]; // Make room for IV
System.arraycopy(ivBytes, 0, encryptedDataWithIV, 0, ivBytes.length); // Add IV
System.arraycopy(encryptedData, 0, encryptedDataWithIV, ivBytes.length, encryptedData.length); // Then the encrypted data
return encryptedDataWithIV;
}
catch(InvalidCipherTextException e) {
Log.e(TAG, "Can't encrypt data", e);
}
return null;
}
/**
* Returns a specification (key material) of the given key
* in the requested format.
*
* @param key the key
*
* @param keySpec the requested format in which the key material shall be
* returned
*
* @return the underlying key specification (key material) in the
* requested format
*
* @exception InvalidKeySpecException if the requested key
* specification is inappropriate for the given key, or the
* given key cannot be processed (e.g., the given key has an
* unrecognized algorithm or format).
*/
protected KeySpec engineGetKeySpec(SecretKey key, Class<?> keySpecCl)
throws InvalidKeySpecException {
if (key instanceof javax.crypto.interfaces.PBEKey) {
// Check if requested key spec is amongst the valid ones
if ((keySpecCl != null)
&& PBEKeySpec.class.isAssignableFrom(keySpecCl)) {
javax.crypto.interfaces.PBEKey pKey =
(javax.crypto.interfaces.PBEKey) key;
return new PBEKeySpec
(pKey.getPassword(), pKey.getSalt(),
pKey.getIterationCount(), pKey.getEncoded().length*8);
} else {
throw new InvalidKeySpecException("Invalid key spec");
}
} else {
throw new InvalidKeySpecException("Invalid key " +
"format/algorithm");
}
}
public SecretKey getMasterSecretKey(String password) throws Throwable {
if (logger.isDebugEnabled()) {
logger.debug("==> RangerMasterKey.getMasterSecretKey()");
}
logger.info("Getting Master Key");
List result = getEncryptedMK();
String encryptedPassString = null;
byte masterKeyByte[] = null;
if (CollectionUtils.isNotEmpty(result) && result.size() == 2) {
masterKeyByte = (byte[]) result.get(0);
encryptedPassString = (String) result.get(1);
} else if (CollectionUtils.isNotEmpty(result)) {
masterKeyByte = (byte[]) result.get(0);
}
if (masterKeyByte != null && masterKeyByte.length > 0) {
if (logger.isDebugEnabled()) {
logger.debug("<== RangerMasterKey.getMasterSecretKey()");
}
return decryptMasterKeySK(masterKeyByte, password, encryptedPassString);
} else {
throw new Exception("No Master Key Found");
}
}
public JWE createJWE() {
String key = getEncryptionKey();
if (key == null) {
throw new RuntimeException(KC_SESSION_KEY + " env var not set");
}
byte[] aesKey = null;
try {
aesKey = Base64.decode(key.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new RuntimeException("invalid " + KC_SESSION_KEY + "env var");
}
JWE jwe = new JWE();
final SecretKey aesSecret = new SecretKeySpec(aesKey, "AES");
jwe.getKeyStorage()
.setDecryptionKey(aesSecret);
return jwe;
}
/**
* 生成加密秘钥
*
* @return
*/
private static SecretKeySpec getSecretKey(final String password) throws NoSuchAlgorithmException {
//返回生成指定算法密钥生成器的 KeyGenerator 对象
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
// javax.crypto.BadPaddingException: Given final block not properly padded解决方案
// https://www.cnblogs.com/zempty/p/4318902.html - 用此法解决的
// https://www.cnblogs.com/digdeep/p/5580244.html - 留作参考吧
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(password.getBytes());
//AES 要求密钥长度为 128
kg.init(128, random);
//生成一个密钥
SecretKey secretKey = kg.generateKey();
// 转换为AES专用密钥
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
}
/**
* The key is generating by SecretKeyFactory and its value just copying
* in the key field of MySecretKey class. So, this is real key derived
* using the given algo.
*/
public MyPBKDF2SecretKey(String passPhrase, String algo, byte[] salt1,
int iterationCount, int keySize)
throws InvalidKeySpecException, NoSuchAlgorithmException {
algorithm = algo;
salt = salt1;
itereationCount = iterationCount;
pass = passPhrase;
PBEKeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt,
iterationCount, keySize);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo);
SecretKey realKey = keyFactory.generateSecret(spec);
keyLength = realKey.getEncoded().length;
key = new byte[keyLength];
System.arraycopy(realKey.getEncoded(), 0, key, 0, keyLength);
}
/**
* Generates the authentication encryption key in a background thread (if necessary).
*/
private static void triggerMacKeyGeneration() {
synchronized (sLock) {
if (sKey != null || sMacKeyGenerator != null) {
return;
}
sMacKeyGenerator = new FutureTask<SecretKey>(new Callable<SecretKey>() {
// SecureRandomInitializer addresses the bug in SecureRandom that "TrulyRandom"
// warns about, so this lint warning can safely be suppressed.
@SuppressLint("TrulyRandom")
@Override
public SecretKey call() throws Exception {
KeyGenerator generator = KeyGenerator.getInstance(MAC_ALGORITHM_NAME);
SecureRandom random = new SecureRandom();
SecureRandomInitializer.initialize(random);
generator.init(MAC_KEY_BYTE_COUNT * 8, random);
return generator.generateKey();
}
});
AsyncTask.THREAD_POOL_EXECUTOR.execute(sMacKeyGenerator);
}
}
public static String DESDecrypt(final String ivString, final String keyString, final String content) {
try {
if (Check.isNullOrEmpty(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;
}
/**
* Return a SecretKey for a specific cipher
* <p/>
* Will coerce the key if required, such as for GENERIC keys.
* <p/>
* @param cipher for the new key
* @return the secret key
*/
public SecretKey getSecretKey(GPKeyCipher cipher) {
if(!isCompatible(cipher)) {
throw new UnsupportedOperationException("Cannot use " + mCipher + " key with cipher " + cipher);
}
switch (cipher) {
case DES:
return new SecretKeySpec(enlarge(mSecret, 8), "DES");
case DES3:
return new SecretKeySpec(enlarge(mSecret, 24), "DESede");
case AES:
return new SecretKeySpec(mSecret, "AES");
default:
throw new IllegalArgumentException("Cannot make secret key for cipher " + cipher);
}
}
/**
* Tests Mac.update(ByteBuffer input) method. Three test cases are
* performed: - large ByteBuffer test case to test if the update() method
* process a large ByteBuffer correctly; - empty ByteBuffer test case to
* test if the update() method process an empty ByteBuffer correctly; - NULL
* ByteBuffer test case to test if the update() method throws expected
* IllegalArgumentException exception.
*
* @param theMacAlgo PBMAC algorithm to test
* @param thePBKDF2Algo PBKDF2 algorithm to test
* @return true - test passed; false - otherwise.
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws InvalidKeySpecException
* @see javax.crypto.Mac
*/
protected boolean doTest(String theMacAlgo, String thePBKDF2Algo)
throws NoSuchAlgorithmException, InvalidKeyException,
InvalidKeySpecException {
// obtain a SecretKey using PBKDF2
SecretKey key = getSecretKey(thePBKDF2Algo);
// Instantiate Mac object and init it with a SecretKey
Mac theMac = Mac.getInstance(theMacAlgo);
theMac.init(key);
// Do large ByteBuffer test case
if (!largeByteBufferTest(theMac)) {
System.out.println("Large ByteBuffer test case failed.");
return false;
}
// Do empty ByteBuffer test case
if (!emptyByteBufferTest(theMac)) {
System.out.println("Empty ByteBuffer test case failed.");
return false;
}
// Do null ByteBuffer test case
if (!nullByteBufferTest(theMac)) {
System.out.println("NULL ByteBuffer test case failed.");
return false;
}
return true;
}
private static void test(KeyGenerator kg,
int clientVersion, int serverVersion) throws Exception {
System.out.printf(
"Testing RSA pre-master secret key generation between " +
"client (0x%04X) and server(0x%04X)%n",
clientVersion, serverVersion);
kg.init(new TlsRsaPremasterSecretParameterSpec(
clientVersion, serverVersion));
SecretKey key = kg.generateKey();
byte[] encoded = key.getEncoded();
if (encoded != null) { // raw key material may be not extractable
if (encoded.length != 48) {
throw new Exception("length: " + encoded.length);
}
int v = versionOf(encoded[0], encoded[1]);
if (clientVersion != v) {
if (serverVersion != v || clientVersion >= 0x0302) {
throw new Exception(String.format(
"version mismatch: (0x%04X) rather than (0x%04X) " +
"is used in pre-master secret", v, clientVersion));
}
System.out.printf("Use compatible version (0x%04X)%n", v);
}
System.out.println("Passed, version matches!");
} else {
System.out.println("Raw key material is not extractable");
}
}
public static byte[] doPBKDF2(byte[] password, byte[] salt, int iterations, int length)
throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
char[] charPassword = new char[password.length];
for (int i = 0; i < password.length; i++) {
charPassword[i] = (char) (password[i] & 0xFF);
}
KeySpec spec = new PBEKeySpec(charPassword, salt, iterations, length);
SecretKey tmp = factory.generateSecret(spec);
return tmp.getEncoded();
}
public static void main(String[] args) throws Exception {
Provider provider = Security.getProvider("SunJCE");
if (provider == null) {
throw new RuntimeException("SunJCE provider not exist");
}
// generate no-padding cipher with secret key
Cipher c = Cipher.getInstance("DES/CBC/NoPadding", provider);
KeyGenerator kgen = KeyGenerator.getInstance("DES", provider);
SecretKey skey = kgen.generateKey();
// this is the improperly padded plaintext
c.init(Cipher.ENCRYPT_MODE, skey);
// encrypt plaintext
byte[] cipher = c.doFinal(PLAIN_TEXT);
AlgorithmParameters params = c.getParameters();
// generate cipher that enforces PKCS5 padding
c = Cipher.getInstance("DES/CBC/PKCS5Padding", provider);
c.init(Cipher.DECRYPT_MODE, skey, params);
try {
c.doFinal(cipher);
throw new RuntimeException(
"ERROR: Expected BadPaddingException not thrown");
} catch (BadPaddingException expected) {
out.println("Expected BadPaddingException thrown");
}
}
public static Object streamDecrypt(byte[] data, SecretKey key,
MessageDigest digest) throws Exception {
Cipher decCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
decCipher.init(Cipher.DECRYPT_MODE, key);
digest.reset();
try (ByteArrayInputStream bis = new ByteArrayInputStream(data);
DigestInputStream dis = new DigestInputStream(bis, digest);
CipherInputStream cis = new CipherInputStream(dis, decCipher)) {
try (ObjectInputStream ois = new ObjectInputStream(cis)) {
return ois.readObject();
}
}
}
public static byte[] hmacSha1Encrypt(String encryptText, String encryptKey) throws Exception {
byte[] data = encryptKey.getBytes(UTF8);
SecretKey secretKey = new SecretKeySpec(data, HMAC_SHA1);
Mac mac = Mac.getInstance(HMAC_SHA1);
mac.init(secretKey);
byte[] text = encryptText.getBytes(UTF8);
return mac.doFinal(text);
}
/**
* Creates a cipher according to given arguments and configuration.
*
* @param mode encryption or decryption mode
*
* @return initialized {@link Cipher}
* @throws Exception
*/
private Cipher createCipher(int mode) throws Exception {
SecretKey key = new SecretKeySpec(this.keyProvider.getEncryptionKey(), "DES");
IvParameterSpec ivectorSpecv = new IvParameterSpec(keyProvider.getEncryptionKey());
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(mode, key, ivectorSpecv);
return cipher;
}