javax.crypto.SecretKey Java Examples

The following examples show how to use javax.crypto.SecretKey. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Des3DkCrypto.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: KcinitDriver.java    From keycloak with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: AsymmetricStaticProviderTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #4
Source File: AesUtil.java    From OneBlog with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 生成加密秘钥
 *
 * @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);
}
 
Example #5
Source File: DES3Coder.java    From ToolsFinal with Apache License 2.0 6 votes vote down vote up
/**
 * 加密方法
 * @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;
}
 
Example #6
Source File: RangerMasterKey.java    From ranger with Apache License 2.0 6 votes vote down vote up
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");
    }
}
 
Example #7
Source File: WebappAuthenticator.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #8
Source File: DESEncrypt.java    From AsuraFramework with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #9
Source File: AsymmetricStaticProviderTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #10
Source File: GPKey.java    From openjavacard-tools with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #11
Source File: PBKDF2TranslateTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #12
Source File: PBKDF2Core.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example #13
Source File: SensitiveDataPreApi23.java    From android-java-connect-rest-sample with MIT License 6 votes vote down vote up
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;
}
 
Example #14
Source File: PBKDF2Core.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example #15
Source File: ToolMAC.java    From protools with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #16
Source File: UsageStatisticsControllerV3.java    From gocd with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #17
Source File: EncryptionUtil.java    From java-trader with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #18
Source File: DOMHMACSignatureMethod.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example #19
Source File: IntegrityHmac.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #20
Source File: TestKeyMaterial.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example #21
Source File: AESCrypto.java    From weMessage with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #22
Source File: SecretKeyResolver.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #23
Source File: ContentCryptoMaterial.java    From markdown-image-kit with MIT License 5 votes vote down vote up
/**
 * Recreates a new content crypto material from the current material given a new KEK
 * material-descriptions. The purpose is to re-encrypt the CEK under a different KEK.
 *
 * Note network calls are involved if the CEK has been or is to be protected by KMS.
 *
 * @param newKEKMatDesc material descriptions for the new KEK; never null
 * @param accessor used to retrieve the KEK given the corresponding material description
 * @param targetScheme the target crypto scheme to be used for key wrapping, etc.
 * @param p optional security provider; null means to use the default.
 * @throws SecurityException if the old and new material description are the same; or if the old
 *         and new KEK are the same
 */
ContentCryptoMaterial recreate(Map<String, String> newKEKMatDesc,
        EncryptionMaterialsAccessor accessor, COSCryptoScheme targetScheme, Provider p,
        QCLOUDKMS kms, CosServiceRequest req) {
    if (!usesKMSKey() && newKEKMatDesc.equals(kekMaterialsDescription)) {
        throw new SecurityException(
                "Material description of the new KEK must differ from the current one");
    }
    final EncryptionMaterials origKEK;
    if (usesKMSKey()) {
        origKEK = new KMSEncryptionMaterials(
                kekMaterialsDescription.get(KMSEncryptionMaterials.CUSTOMER_MASTER_KEY_ID));
    } else {
        origKEK = accessor.getEncryptionMaterials(kekMaterialsDescription);
        if (origKEK == null) {
            throw new CosClientException("Unable to retrieve the origin encryption materials");
        }
    }
    EncryptionMaterials newKEK = accessor.getEncryptionMaterials(newKEKMatDesc);
    if (newKEK == null) {
        throw new CosClientException("No material available with the description "
                + newKEKMatDesc + " from the encryption material provider");
    }
    SecretKey cek =
            cek(encryptedCEK, keyWrappingAlgorithm, origKEK, p, getContentCryptoScheme(), kms);
    ContentCryptoMaterial output =
            create(cek, cipherLite.getIV(), newKEK, getContentCryptoScheme(), // must use same
                                                                              // content crypto
                                                                              // scheme
                    targetScheme, p, kms, req);
    if (Arrays.equals(output.encryptedCEK, encryptedCEK)) {
        throw new SecurityException("The new KEK must differ from the original");
    }
    return output;
}
 
Example #24
Source File: HmacCoder.java    From bird-java with MIT License 5 votes vote down vote up
/**
 * 初始化HmacSHA512密钥
 *
 * @return
 * @throws Exception
 */
public static byte[] initHmacSHA512Key() throws Exception {
    // 初始化KeyGenerator
    KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacSHA512");
    // 产生秘密密钥
    SecretKey secretKey = keyGenerator.generateKey();
    // 获得密钥
    return secretKey.getEncoded();
}
 
Example #25
Source File: CICOSkipTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
CipherGenerator(String algo) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, InvalidKeyException,
        NoSuchPaddingException, InvalidKeySpecException {
    // Do initialization
    byte[] salt = TestUtilities.generateBytes(IV_LENGTH);
    int iterCnt = 6;
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algo.split("/")[0]);
    SecretKey key = skf
            .generateSecret(new PBEKeySpec(PASSWD.toCharArray()));
    AlgorithmParameterSpec aps = new PBEParameterSpec(salt, iterCnt);
    initCiphers(algo, key, aps);
}
 
Example #26
Source File: TestKeyMaterial.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void match(int lineNumber, byte[] out, Object res,
        String cipherAlgorithm) 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();
        if (cipherAlgorithm.equalsIgnoreCase("DES") ||
                cipherAlgorithm.equalsIgnoreCase("DESede")) {
            // strip DES parity bits before comparision
            stripParity(out);
            stripParity(b);
        }
    } else if (res instanceof IvParameterSpec) {
        b = ((IvParameterSpec)res).getIV();
    } else {
        throw new Exception(res.getClass().getName());
    }
    if (Arrays.equals(out, b) == false) {
        System.out.println();
        System.out.println("out: " + toString(out));
        System.out.println("b:   " + toString(b));
        throw new Exception("mismatch line " + lineNumber);
    }
}
 
Example #27
Source File: HmacCore.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initializes the HMAC with the given secret key and algorithm parameters.
 *
 * @param key the secret key.
 * @param params the algorithm parameters.
 *
 * @exception InvalidKeyException if the given key is inappropriate for
 * initializing this MAC.
 * @exception InvalidAlgorithmParameterException if the given algorithm
 * parameters are inappropriate for this MAC.
 */
protected void engineInit(Key key, AlgorithmParameterSpec params)
        throws InvalidKeyException, InvalidAlgorithmParameterException {
    if (params != null) {
        throw new InvalidAlgorithmParameterException
            ("HMAC does not use parameters");
    }

    if (!(key instanceof SecretKey)) {
        throw new InvalidKeyException("Secret key expected");
    }

    byte[] secret = key.getEncoded();
    if (secret == null) {
        throw new InvalidKeyException("Missing key data");
    }

    // if key is longer than the block length, reset it using
    // the message digest object.
    if (secret.length > blockLen) {
        byte[] tmp = md.digest(secret);
        // now erase the secret
        Arrays.fill(secret, (byte)0);
        secret = tmp;
    }

    // XOR k with ipad and opad, respectively
    for (int i = 0; i < blockLen; i++) {
        int si = (i < secret.length) ? secret[i] : 0;
        k_ipad[i] = (byte)(si ^ 0x36);
        k_opad[i] = (byte)(si ^ 0x5c);
    }

    // now erase the secret
    Arrays.fill(secret, (byte)0);
    secret = null;

    engineReset();
}
 
Example #28
Source File: Des3DkCrypto.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
protected byte[] getHmac(byte[] key, byte[] msg)
    throws GeneralSecurityException {

    SecretKey keyKi = new SecretKeySpec(key, "HmacSHA1");
    Mac m = Mac.getInstance("HmacSHA1");
    m.init(keyKi);
    return m.doFinal(msg);
}
 
Example #29
Source File: SecKFTranslateTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private void runTest(Algorithm algo) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeyException,
        InvalidKeySpecException, NoSuchPaddingException,
        InvalidAlgorithmParameterException, ShortBufferException,
        IllegalBlockSizeException, BadPaddingException {
    AlgorithmParameterSpec[] aps = new AlgorithmParameterSpec[1];
    byte[] plainText = new byte[800];

    SecretKey key1 = algo.intSecurityKey(aps);
    Random random = new Random();
    // Initialization
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algo.toString(),
            SUN_JCE);

    random.nextBytes(plainText);
    Cipher ci = Cipher.getInstance(algo.toString(), SUN_JCE);
    // Encryption
    ci.init(Cipher.ENCRYPT_MODE, key1, aps[0]);
    byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
    int offset = ci.update(plainText, 0, plainText.length, cipherText, 0);
    ci.doFinal(cipherText, offset);
    // translate key
    SecretKey key2 = skf.translateKey(key1);

    // Decryption
    ci.init(Cipher.DECRYPT_MODE, key2, aps[0]);
    byte[] recoveredText = new byte[ci.getOutputSize(plainText.length)];
    ci.doFinal(cipherText, 0, cipherText.length, recoveredText);

    // Comparison
    if (!Arrays.equals(plainText, recoveredText)) {
        System.out.println("Key1:" + new String(key1.getEncoded())
                + " Key2:" + new String(key2.getEncoded()));
        throw new RuntimeException("Testing translate key failed with "
                + algo);
    }

}
 
Example #30
Source File: FileEncrypterDecrypterIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenStringAndFilename_whenEncryptingIntoFile_andDecryptingFileAgain_thenOriginalStringIsReturned() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, InvalidAlgorithmParameterException {
    String originalContent = "foobar";
    SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();

    FileEncrypterDecrypter fileEncrypterDecrypter = new FileEncrypterDecrypter(secretKey, "AES/CBC/PKCS5Padding");
    fileEncrypterDecrypter.encrypt(originalContent, "baz.enc");

    String decryptedContent = fileEncrypterDecrypter.decrypt("baz.enc");
    assertThat(decryptedContent, is(originalContent));

    new File("baz.enc").delete(); // cleanup
}