Search in sources :

Example 56 with KeyGenerator

use of javax.crypto.KeyGenerator in project uavstack by uavorg.

the class EncryptionHelper method encryptByAesCBC.

/**
 * AES CBC加密
 *
 * 数据块:128位
 *
 * @param strMsg
 *            : 需要加密的字符串
 * @param sKey
 *            :加密key(16位)
 * @param sKeyFormat
 *            :skey是否格式处理
 * @param ivParameter
 *            :偏移量(16位)使用CBC模式,需要一个向量iv,可增加加密算法的强度
 * @param encoding
 *            :编码
 * @return :16进制的加密字符串
 */
public static String encryptByAesCBC(String strMsg, String sKey, boolean sKeyFormat, String ivParameter, String encoding) {
    try {
        byte[] keyByte = null;
        if (sKeyFormat) {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(sKey.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            keyByte = secretKey.getEncoded();
        } else {
            keyByte = sKey.getBytes(encoding);
        }
        SecretKeySpec skeySpec = new SecretKeySpec(keyByte, "AES");
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
        // 算法/模式/补码方式
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] resultByte = cipher.doFinal(strMsg.getBytes(encoding));
        // 传输过程,转成16进制
        String resultStr = parseByte2HexStr(resultByte);
        return resultStr;
    } catch (Exception ex) {
        ex.printStackTrace();
        return "";
    }
}
Also used : SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) SecureRandom(java.security.SecureRandom) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) KeyGenerator(javax.crypto.KeyGenerator)

Example 57 with KeyGenerator

use of javax.crypto.KeyGenerator in project coprhd-controller by CoprHD.

the class SignatureHelper method generateKey.

/**
 * Generate a new secret key, encoded as string
 *
 * @param algo
 * @return
 * @throws NoSuchAlgorithmException
 */
public static String generateKey(String algo) throws NoSuchAlgorithmException {
    KeyGenerator keyGenerator = KeyGenerator.getInstance(algo);
    SecretKey key = keyGenerator.generateKey();
    return new String(Base64.encodeBase64(key.getEncoded()), UTF_8);
}
Also used : SecretKey(javax.crypto.SecretKey) KeyGenerator(javax.crypto.KeyGenerator)

Example 58 with KeyGenerator

use of javax.crypto.KeyGenerator in project coprhd-controller by CoprHD.

the class DummyEncryptionProvider method generateKey.

private void generateKey() throws Exception {
    KeyGenerator keygen = KeyGenerator.getInstance(ALGO);
    SecretKey key = keygen.generateKey();
    _key = key;
}
Also used : SecretKey(javax.crypto.SecretKey) KeyGenerator(javax.crypto.KeyGenerator)

Example 59 with KeyGenerator

use of javax.crypto.KeyGenerator in project jdk8u_jdk by JetBrains.

the class Pair method doGenSecretKey.

/**
     * Creates a new secret key.
     */
private void doGenSecretKey(String alias, String keyAlgName, int keysize) throws Exception {
    if (alias == null) {
        alias = keyAlias;
    }
    if (keyStore.containsAlias(alias)) {
        MessageFormat form = new MessageFormat(rb.getString("Secret.key.not.generated.alias.alias.already.exists"));
        Object[] source = { alias };
        throw new Exception(form.format(source));
    }
    // Use the keystore's default PBE algorithm for entry protection
    boolean useDefaultPBEAlgorithm = true;
    SecretKey secKey = null;
    if (keyAlgName.toUpperCase(Locale.ENGLISH).startsWith("PBE")) {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBE");
        // User is prompted for PBE credential
        secKey = factory.generateSecret(new PBEKeySpec(promptForCredential()));
        // Check whether a specific PBE algorithm was specified
        if (!"PBE".equalsIgnoreCase(keyAlgName)) {
            useDefaultPBEAlgorithm = false;
        }
        if (verbose) {
            MessageFormat form = new MessageFormat(rb.getString("Generated.keyAlgName.secret.key"));
            Object[] source = { useDefaultPBEAlgorithm ? "PBE" : secKey.getAlgorithm() };
            System.err.println(form.format(source));
        }
    } else {
        KeyGenerator keygen = KeyGenerator.getInstance(keyAlgName);
        if (keysize == -1) {
            if ("DES".equalsIgnoreCase(keyAlgName)) {
                keysize = 56;
            } else if ("DESede".equalsIgnoreCase(keyAlgName)) {
                keysize = 168;
            } else {
                throw new Exception(rb.getString("Please.provide.keysize.for.secret.key.generation"));
            }
        }
        keygen.init(keysize);
        secKey = keygen.generateKey();
        if (verbose) {
            MessageFormat form = new MessageFormat(rb.getString("Generated.keysize.bit.keyAlgName.secret.key"));
            Object[] source = { new Integer(keysize), secKey.getAlgorithm() };
            System.err.println(form.format(source));
        }
    }
    if (keyPass == null) {
        keyPass = promptForKeyPass(alias, null, storePass);
    }
    if (useDefaultPBEAlgorithm) {
        keyStore.setKeyEntry(alias, secKey, keyPass, null);
    } else {
        keyStore.setEntry(alias, new KeyStore.SecretKeyEntry(secKey), new KeyStore.PasswordProtection(keyPass, keyAlgName, null));
    }
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) MessageFormat(java.text.MessageFormat) KeyStore(java.security.KeyStore) KeyStoreException(java.security.KeyStoreException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) CertStoreException(java.security.cert.CertStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) BigInteger(java.math.BigInteger) SecretKey(javax.crypto.SecretKey) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyGenerator(javax.crypto.KeyGenerator)

Example 60 with KeyGenerator

use of javax.crypto.KeyGenerator in project jdk8u_jdk by JetBrains.

the class CICODESFuncTest method runTest.

private static void runTest(Provider p, String algo, String mo, String pad, ReadModel whichRead) throws GeneralSecurityException, IOException {
    // Do initialization
    byte[] plainText = TestUtilities.generateBytes(TEXT_LENGTH);
    byte[] iv = TestUtilities.generateBytes(IV_LENGTH);
    AlgorithmParameterSpec aps = new IvParameterSpec(iv);
    try {
        KeyGenerator kg = KeyGenerator.getInstance(algo, p);
        out.println(algo + "/" + mo + "/" + pad + "/" + whichRead);
        SecretKey key = kg.generateKey();
        Cipher ci1 = Cipher.getInstance(algo + "/" + mo + "/" + pad, p);
        if ("CFB72".equalsIgnoreCase(mo) || "OFB20".equalsIgnoreCase(mo)) {
            throw new RuntimeException("NoSuchAlgorithmException not throw when mode" + " is CFB72 or OFB20");
        }
        Cipher ci2 = Cipher.getInstance(algo + "/" + mo + "/" + pad, p);
        if ("ECB".equalsIgnoreCase(mo)) {
            ci1.init(Cipher.ENCRYPT_MODE, key);
            ci2.init(Cipher.DECRYPT_MODE, key);
        } else {
            ci1.init(Cipher.ENCRYPT_MODE, key, aps);
            ci2.init(Cipher.DECRYPT_MODE, key, aps);
        }
        ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
        try (CipherInputStream cInput = new CipherInputStream(new ByteArrayInputStream(plainText), ci1);
            CipherOutputStream ciOutput = new CipherOutputStream(baOutput, ci2)) {
            // Read from the input and write to the output using 2 types
            // of buffering : byte[] and int
            whichRead.read(cInput, ciOutput, ci1, plainText.length);
        }
        // Verify input and output are same.
        if (!Arrays.equals(plainText, baOutput.toByteArray())) {
            throw new RuntimeException("Test failed due to compare fail ");
        }
    } catch (NoSuchAlgorithmException nsaEx) {
        if ("CFB72".equalsIgnoreCase(mo) || "OFB20".equalsIgnoreCase(mo)) {
            out.println("NoSuchAlgorithmException is expected for CFB72 and OFB20");
        } else {
            throw new RuntimeException("Unexpected exception testing: " + algo + "/" + mo + "/" + pad + "/" + whichRead, nsaEx);
        }
    }
}
Also used : SecretKey(javax.crypto.SecretKey) CipherOutputStream(javax.crypto.CipherOutputStream) CipherInputStream(javax.crypto.CipherInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) ByteArrayOutputStream(java.io.ByteArrayOutputStream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) KeyGenerator(javax.crypto.KeyGenerator)

Aggregations

KeyGenerator (javax.crypto.KeyGenerator)464 SecretKey (javax.crypto.SecretKey)343 Test (org.junit.Test)106 ArrayList (java.util.ArrayList)104 SecureRandom (java.security.SecureRandom)99 Document (org.w3c.dom.Document)98 InputStream (java.io.InputStream)95 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)93 ByteArrayOutputStream (java.io.ByteArrayOutputStream)87 NodeList (org.w3c.dom.NodeList)82 Cipher (javax.crypto.Cipher)79 ByteArrayInputStream (java.io.ByteArrayInputStream)75 XMLStreamReader (javax.xml.stream.XMLStreamReader)68 XMLSecurityProperties (org.apache.xml.security.stax.ext.XMLSecurityProperties)68 DocumentBuilder (javax.xml.parsers.DocumentBuilder)62 Key (java.security.Key)58 QName (javax.xml.namespace.QName)47 IOException (java.io.IOException)45 SecurePart (org.apache.xml.security.stax.ext.SecurePart)40 SecretKeySpec (javax.crypto.spec.SecretKeySpec)39