/** * Generates a random secret key using the algorithm specified in the first DataReference URI * * @param dataRefURIs * @param doc * @param wsDocInfo * @return * @throws WSSecurityException */ private static byte[] getRandomKey(List<String> dataRefURIs, Document doc, WSDocInfo wsDocInfo) throws WSSecurityException { try { String alg = "AES"; int size = 16; if (!dataRefURIs.isEmpty()) { String uri = dataRefURIs.iterator().next(); Element ee = ReferenceListProcessor.findEncryptedDataElement(doc, uri); String algorithmURI = X509Util.getEncAlgo(ee); alg = JCEMapper.getJCEKeyAlgorithmFromURI(algorithmURI); size = WSSecurityUtil.getKeyLength(algorithmURI); } KeyGenerator kgen = KeyGenerator.getInstance(alg); kgen.init(size * 8); SecretKey k = kgen.generateKey(); return k.getEncoded(); } catch (Throwable ex) { // Fallback to just using AES to avoid attacks on EncryptedData algorithms try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey k = kgen.generateKey(); return k.getEncoded(); } catch (NoSuchAlgorithmException e) { throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e); } } }
public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta = (RandomValueMeta) smi; data = (RandomValueData) sdi; if (super.init(smi, sdi)) { data.readsRows = getStepMeta().getRemoteInputSteps().size() > 0; List<StepMeta> previous = getTransMeta().findPreviousSteps(getStepMeta()); if (previous != null && previous.size() > 0) { data.readsRows = true; } boolean genHmacMD5 = false; boolean genHmacSHA1 = false; boolean uuid4 = false; for (int i = 0; i < meta.getFieldName().length; i++) { switch (meta.getFieldType()[i]) { case RandomValueMeta.TYPE_RANDOM_MAC_HMACMD5: genHmacMD5 = true; break; case RandomValueMeta.TYPE_RANDOM_MAC_HMACSHA1: genHmacSHA1 = true; break; case RandomValueMeta.TYPE_RANDOM_UUID4: uuid4 = true; break; default: break; } } if (genHmacMD5) { try { data.keyGenHmacMD5 = KeyGenerator.getInstance("HmacMD5"); } catch (NoSuchAlgorithmException s) { logError( BaseMessages.getString( PKG, "RandomValue.Log.HmacMD5AlgorithmException", s.getMessage())); return false; } } if (genHmacSHA1) { try { data.keyGenHmacSHA1 = KeyGenerator.getInstance("HmacSHA1"); } catch (NoSuchAlgorithmException s) { logError( BaseMessages.getString( PKG, "RandomValue.Log.HmacSHA1AlgorithmException", s.getMessage())); return false; } } if (uuid4) { data.u4 = new UUID4Util(); } return true; } return false; }
public boolean shareAESkey() { try { Envelope message = null, e = null; // Generate AES key KeyGenerator keyGen = KeyGenerator.getInstance("AES"); AESkey = keyGen.generateKey(); keyGen = KeyGenerator.getInstance("HmacSHA1"); HMACkey = keyGen.generateKey(); byte[] keyBytes = AESkey.getEncoded(); byte[] hashBytes = HMACkey.getEncoded(); System.out.println("AES key generated"); System.out.println("HMAC key generated"); System.out.println("Begin Encryption..."); // Encrypt message w/ provided public key Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] cipherBytes = cipher.doFinal(keyBytes); byte[] cipherBytes1 = cipher.doFinal(hashBytes); System.out.println("Encryption Complete"); message = new Envelope("SKEY"); message.addObject(cipherBytes); // Add AESkey to message message.addObject(cipherBytes1); message.addObject(nonce); nonce++; byte[] messageBytes = Envelope.toByteArray(message); output.writeObject(messageBytes); byte[] inCipherBytes = (byte[]) input.readObject(); // Decrypt response cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, AESkey); byte[] responseBytes = cipher.doFinal(inCipherBytes); Envelope response = Envelope.getEnvelopefromBytes(responseBytes); // If server indicates success, return the member list if (response.getMessage().equals("OK") && (Integer) response.getObjContents().get(0) == nonce) { return true; } else { return false; } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(System.err); return false; } }
/** * Used to initialise the symmetric key if none is supplied in a keystore. * * @throws Exception */ public void initSymKey() throws Exception { KeyGenerator keyGen = null; // see if we have a provider specified if (symProvider != null && !symProvider.trim().isEmpty()) keyGen = KeyGenerator.getInstance(getAlgorithm(symAlgorithm), symProvider); else keyGen = KeyGenerator.getInstance(getAlgorithm(symAlgorithm)); // generate the key using the defined init properties keyGen.init(symInit); secretKey = keyGen.generateKey(); setSecretKey(secretKey); log.debug("symmetric key generated "); }
/** * Generate a random symmetric key. * * @param algo key algorithm * @param keyLength key length * @param provider JCA provider * @return randomly generated symmetric key * @throws NoSuchAlgorithmException algorithm not found * @throws NoSuchProviderException provider not found */ public static SecretKey generateKey(String algo, int keyLength, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { SecretKey key = null; KeyGenerator keyGenerator = null; if (provider != null) { keyGenerator = KeyGenerator.getInstance(algo, provider); } else { keyGenerator = KeyGenerator.getInstance(algo); } keyGenerator.init(keyLength); key = keyGenerator.generateKey(); return key; }
protected String encrypt(String content, String key) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(key.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES"); byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] byteRresult = cipher.doFinal(byteContent); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteRresult.length; i++) { String hex = Integer.toHexString(byteRresult[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; }
/** * Generate key encryption key. * * @return the secret key * @throws Exception the exception */ public static SecretKey generateKeyEncryptionKey() throws Exception { String jceAlgorithmName = "DESede"; KeyGenerator keyGenerator = KeyGenerator.getInstance(jceAlgorithmName); SecretKey kek = keyGenerator.generateKey(); return kek; }
protected String decrypt(String content, String key) { if (content.length() < 1) return null; byte[] byteRresult = new byte[content.length() / 2]; for (int i = 0; i < content.length() / 2; i++) { int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16); byteRresult[i] = (byte) (high * 16 + low); } try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(key.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); byte[] result = cipher.doFinal(byteRresult); return new String(result); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; }
private static byte[] key(final byte[] key) throws Exception { final KeyGenerator gen = KeyGenerator.getInstance(ALGORITHM); final SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(key); gen.init(128, sr); return gen.generateKey().getEncoded(); }
/** * This method broadcasts a payload onto the given topic. * * @param topic the topic to broadcast onto * @param visibility the visibility of the message * @param payload the payload of the message */ public void broadcast(String topic, Visibility visibility, byte[] payload) throws IOException { byte[] payloadToSend = payload; SecureMessage message = new SecureMessage(); message.setVisibility(visibility); if (isProduction) { try { // Generate a new symmetric key and encrypt the message Cipher cipher = Cipher.getInstance(ALGO); KeyGenerator gen = KeyGenerator.getInstance(ALGO); gen.init(256); SecretKey key = gen.generateKey(); cipher.init(Cipher.ENCRYPT_MODE, key); payloadToSend = cipher.doFinal(payload); // Get topic crypto object, encrypt the key and embed it into the message RSAKeyCrypto crypto = topicKeys.get(topic); message.setKey(crypto.encrypt(key.getEncoded())); } catch (Exception e) { log.error("Could not encrypt message for topic [{}].", topic, e); throw new RuntimeException(e); } } message.setContent(payloadToSend); byte[] serializedMessage; try { serializedMessage = ThriftUtils.serialize(message); } catch (TException e) { throw new IOException("Could not serialize message", e); } broadcastImpl(topic, serializedMessage); }
private void init() { try { /** * 为指定算法生成一个 KeyGenerator 对象。 此类提供(对称)密钥生成器的功能。 密钥生成器是使用此类的某个 getInstance 类方法构造的。 KeyGenerator * 对象可重复使用,也就是说,在生成密钥后, 可以重复使用同一 KeyGenerator 对象来生成进一步的密钥。 生成密钥的方式有两种:与算法无关的方式,以及特定于算法的方式。 * 两者之间的惟一不同是对象的初始化: 与算法无关的初始化 所有密钥生成器都具有密钥长度 和随机源 的概念。 此 KeyGenerator 类中有一个 init * 方法,它可采用这两个通用概念的参数。 还有一个只带 keysize 参数的 init 方法, 它使用具有最高优先级的提供程序的 SecureRandom 实现作为随机源 * (如果安装的提供程序都不提供 SecureRandom 实现,则使用系统提供的随机源)。 此 KeyGenerator 类还提供一个只带随机源参数的 inti 方法。 * 因为调用上述与算法无关的 init 方法时未指定其他参数, 所以由提供程序决定如何处理将与每个密钥相关的特定于算法的参数(如果有)。 特定于算法的初始化 * 在已经存在特定于算法的参数集的情况下, 有两个具有 AlgorithmParameterSpec 参数的 init 方法。 其中一个方法还有一个 SecureRandom 参数, * 而另一个方法将已安装的高优先级提供程序的 SecureRandom 实现用作随机源 (或者作为系统提供的随机源,如果安装的提供程序都不提供 SecureRandom 实现)。 * 如果客户端没有显式地初始化 KeyGenerator(通过调用 init 方法), 每个提供程序必须提供(和记录)默认初始化。 */ keyGen = KeyGenerator.getInstance("AES"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } // 初始化此密钥生成器,使其具有确定的密钥长度。 keyGen.init(128); // 128位的AES加密 try { // 生成一个实现指定转换的 Cipher 对象。 cipher = Cipher.getInstance(algorithmStr); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } // 标识已经初始化过了的字段 isInited = true; }
private static byte[] doAes(int mode, byte[] input, String password) { try { KeyGenerator keygen = KeyGenerator.getInstance(AES_ALGORITHM_NAME); keygen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = keygen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES_ALGORITHM_NAME); Cipher cipher = Cipher.getInstance(AES_ALGORITHM_NAME); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(input); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; }
/** * Get the signing key unique to this installation, or create it if it doesn't exist. The purpose * of this key is to allow signing of backup files (and any other such files) to ensure they are * not modified by some other program. Of course, if the other program has root then it can modify * or read this key anyway, so all bets are off. * * @return secret key for signing and verification */ public SecretKey getOrCreateSigningKey() { String signingKey = this.prefs.getString(BACKUP_SIGNING_KEY, null); SecretKey secretKey = null; if (signingKey != null) { secretKey = new SecretKeySpec( Base64.decode(signingKey, Base64.DEFAULT), 0, Base64.decode(signingKey, Base64.DEFAULT).length, "HmacSHA1"); } else { // supporting multiple algorithms would be good, but then we also need to store the key // type... try { secretKey = KeyGenerator.getInstance("HmacSHA1").generateKey(); } catch (NoSuchAlgorithmException e) { } Editor editor = this.prefs.edit(); editor.putString( BACKUP_SIGNING_KEY, Base64.encodeToString(secretKey.getEncoded(), Base64.DEFAULT)); editor.commit(); } return secretKey; }
public static void main(String[] args) throws Exception { // // check args and get plaintext if (args.length != 1) { System.err.println("Usage: java MessageAuthenticationCodeExample text"); System.exit(1); } byte[] plainText = args[0].getBytes("UTF8"); // // get a key for the HmacMD5 algorithm System.out.println("\nStart generating key"); KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5"); SecretKey MD5key = keyGen.generateKey(); System.out.println("Finish generating key"); // // get a MAC object and update it with the plaintext Mac mac = Mac.getInstance("HmacMD5"); mac.init(MD5key); mac.update(plainText); // // print out the provider used and the MAC System.out.println("\n" + mac.getProvider().getInfo()); System.out.println("\nMAC: "); System.out.println(new String(mac.doFinal(), "UTF8")); }
private void oidTest() { String[] oids = { CryptoProObjectIdentifiers.gostR28147_gcfb.getId(), }; String[] names = {"GOST28147/GCFB/NoPadding"}; try { byte[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; IvParameterSpec ivSpec = new IvParameterSpec(new byte[8]); for (int i = 0; i != oids.length; i++) { Cipher c1 = Cipher.getInstance(oids[i], "BC"); Cipher c2 = Cipher.getInstance(names[i], "BC"); KeyGenerator kg = KeyGenerator.getInstance(oids[i], "BC"); SecretKey k = kg.generateKey(); c1.init(Cipher.ENCRYPT_MODE, k, ivSpec); c2.init(Cipher.DECRYPT_MODE, k, ivSpec); byte[] result = c2.doFinal(c1.doFinal(data)); if (!areEqual(data, result)) { fail("failed OID test"); } } } catch (Exception ex) { fail("failed exception " + ex.toString(), ex); } }
private void testCipherNameWithWrap(String name, String simpleName) throws Exception { KeyGenerator kg = KeyGenerator.getInstance("AES"); kg.init(new SecureRandom()); SecretKey key = kg.generateKey(); byte[] salt = { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 }; char[] password = {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20); PBEKeySpec pbeKeySpec = new PBEKeySpec(password); SecretKeyFactory keyFac = SecretKeyFactory.getInstance(name); SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); Cipher pbeEncryptCipher = Cipher.getInstance(name, "SC"); pbeEncryptCipher.init(Cipher.WRAP_MODE, pbeKey, pbeParamSpec); byte[] symKeyBytes = pbeEncryptCipher.wrap(key); Cipher simpleCipher = Cipher.getInstance(simpleName, "SC"); simpleCipher.init(Cipher.UNWRAP_MODE, pbeKey, pbeParamSpec); SecretKey unwrappedKey = (SecretKey) simpleCipher.unwrap(symKeyBytes, "AES", Cipher.SECRET_KEY); if (!Arrays.areEqual(unwrappedKey.getEncoded(), key.getEncoded())) { fail("key mismatch on unwrapping"); } }
/** Generate the AES file key for encrypting files */ private void genAESFileKey() { try { // randomly generate a 64-bit string, used for generating the AES key char[] chars = "abcdefghijklmnopqrstuvwxyz0123456789".toCharArray(); StringBuilder sb = new StringBuilder(); Random randomString = new Random(); for (int i = 0; i < 64; i++) { char c = chars[randomString.nextInt(chars.length)]; sb.append(c); } aesFileString = sb.toString(); // System.out.println("AES file String: " + aesFileString); KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = new SecureRandom(aesFileString.getBytes()); keygen.init(256, random); aesFileKey = keygen.generateKey(); // System.out.println("AES file key: " + aesFileKey); } catch (Exception e) { System.out.println("Failed to generate DES key for encrypting files!\n" + e.toString()); } }
/** * Generate a new MWK * * @return Hex String of the new encrypted MWK ready for transmission to ValueLink */ public byte[] generateMwk() { KeyGenerator keyGen = null; try { keyGen = KeyGenerator.getInstance("DES"); } catch (NoSuchAlgorithmException e) { Debug.logError(e, module); } // generate the DES key 1 SecretKey des1 = keyGen.generateKey(); SecretKey des2 = keyGen.generateKey(); if (des1 != null && des2 != null) { byte[] desByte1 = des1.getEncoded(); byte[] desByte2 = des2.getEncoded(); byte[] desByte3 = des1.getEncoded(); // check for weak keys try { if (DESKeySpec.isWeak(des1.getEncoded(), 0) || DESKeySpec.isWeak(des2.getEncoded(), 0)) { return generateMwk(); } } catch (Exception e) { Debug.logError(e, module); } byte[] des3 = copyBytes(desByte1, copyBytes(desByte2, desByte3, 0), 0); return generateMwk(des3); } else { Debug.logInfo("Null DES keys returned", module); } return null; }
private static void _initKeys() { ClassLoader classLoader = ClassLoaderUtil.getPortalClassLoader(); if ((classLoader == null) || (_encryptedSymmetricKey != null)) { return; } try { URL url = classLoader.getResource("com/liferay/portal/license/public.key"); byte[] bytes = IOUtils.toByteArray(url.openStream()); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(bytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128, new SecureRandom()); _symmetricKey = keyGenerator.generateKey(); byte[] encryptedSymmetricKey = Encryptor.encryptUnencoded(publicKey, _symmetricKey.getEncoded()); _encryptedSymmetricKey = Base64.objectToString(encryptedSymmetricKey); } catch (Exception e) { _log.error(e, e); } }
public void readConfig() throws Exception { // debugging aspect if (ds().getProperty("debug", "false").equalsIgnoreCase("true")) { LOG.debug_on(); LOG.info("working directory = " + System.getProperty("user.dir")); } Iterator<String> it = ds().iterator(); while (it.hasNext()) { String key = it.next(); String value = ds().getProperty(key); LOG.info(key + "=" + value); } name = ds().getProperty("name", "anonymous"); // each agent has its own symmetric key cipher // TODO: test with other algo than AES KeyGenerator keyGen = KeyGenerator.getInstance(this.ds().getProperty("cypher.algo", "AES")); keyGen.init(Integer.parseInt(this.ds().getProperty("cipher.keysize", "128"))); secretKey = keyGen.generateKey(); cipher = Cipher.getInstance(this.ds().getProperty("cipher.algo", "AES")); // user cipher byte[] salt = {1, 1, 1, 2, 2, 2, 3, 3}; int count = 20; userParamSpec = new PBEParameterSpec(salt, count); }
private static byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(seed); kgen.init(128, sr); // 192 and 256 bits may not be available return kgen.generateKey().getEncoded(); }
/** Generates secret key. Initializes MAC(s). */ private void setupKeyAndMac() { /* * Lets see if an encoded key was given to the application, if so use * it and skip the code to generate it. */ try { InitialContext context = new InitialContext(); String encodedKeyArray = (String) context.lookup("java:comp/env/jsf/ClientSideSecretKey"); byte[] keyArray = DatatypeConverter.parseBase64Binary(encodedKeyArray); sk = new SecretKeySpec(keyArray, KEY_ALGORITHM); } catch (NamingException exception) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Unable to find the encoded key.", exception); } } if (sk == null) { try { KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM); kg.init(KEY_LENGTH); // 256 if you're using the Unlimited Policy Files sk = kg.generateKey(); // System.out.print("SecretKey: " + // DatatypeConverter.printBase64Binary(sk.getEncoded())); } catch (Exception e) { throw new FacesException(e); } } }
public static Message encrypt(PublicKey pubKey, byte[] input) throws CryptoException { Message message = new Message(); message.pubKey = pubKey.getEncoded(); KeyGenerator keyGen; try { keyGen = KeyGenerator.getInstance("AES"); } catch (NoSuchAlgorithmException e) { throw new CryptoException(e); } keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); try { Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsaCipher.init(Cipher.ENCRYPT_MODE, pubKey); message.sessionKey = rsaCipher.doFinal(secretKey.getEncoded()); Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); aesCipher.init(Cipher.ENCRYPT_MODE, secretKey); AlgorithmParameters params = aesCipher.getParameters(); message.iv = params.getParameterSpec(IvParameterSpec.class).getIV(); message.ciphertext = aesCipher.doFinal(input); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidParameterSpecException e) { throw new CryptoException(e); } return message; }
public DESEncrypter() { try { final SecretKey key = KeyGenerator.getInstance("DES").generateKey(); this.init(key); } catch (Throwable t) { } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Bitmap bm = null; bm.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm is the bitmap object byte[] b = baos.toByteArray(); byte[] keyStart = "this is a key".getBytes(); KeyGenerator kgen; try { kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(keyStart); kgen.init(128, sr); // 192 and 256 bits may not be available SecretKey skey = kgen.generateKey(); byte[] key = skey.getEncoded(); // encrypt byte[] encryptedData = encrypt(key, b); // decrypt byte[] decryptedData = decrypt(key, encryptedData); } catch (NoSuchAlgorithmException e) { // TODO 自動產生的 catch 區塊 e.printStackTrace(); } catch (Exception e) { // TODO 自動產生的 catch 區塊 e.printStackTrace(); } }
/** * 加密 * * @param content 需要加密的内容 * @param password 加密密码 * @return */ public static byte[] encryptAES(String content, String password) { try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128, new SecureRandom(password.getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES"); // 创建密码器 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key); // 初始化 byte[] result = cipher.doFinal(byteContent); return result; // 加密 } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null; }
private DERObject createDERForRecipient(byte[] in, X509Certificate cert) throws IOException, GeneralSecurityException { String s = "1.2.840.113549.3.2"; AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s); AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters(); ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(algorithmparameters.getEncoded("ASN.1")); ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream); DERObject derobject = asn1inputstream.readObject(); KeyGenerator keygenerator = KeyGenerator.getInstance(s); keygenerator.init(128); SecretKey secretkey = keygenerator.generateKey(); Cipher cipher = Cipher.getInstance(s); cipher.init(1, secretkey, algorithmparameters); byte[] abyte1 = cipher.doFinal(in); DEROctetString deroctetstring = new DEROctetString(abyte1); KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded()); DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo)); AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new DERObjectIdentifier(s), derobject); EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring); EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, null); ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env); return contentinfo.getDERObject(); }
/** @see de.freese.base.security.codec.pbe.AbstractCryptoCodecPBE#createKey(int) */ @Override public Key createKey(final int keySize) throws GeneralSecurityException { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES", getProviderKey()); keyGenerator.init(keySize); Key key = keyGenerator.generateKey(); return key; }
@Provides public KeyGenerator providesKeyGenerator() { try { return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new RuntimeException("Failed to get an instance of KeyGenerator", e); } }
public String createKey() throws NoSuchAlgorithmException, NoSuchProviderException { KeyGenerator keygen = KeyGenerator.getInstance("AES", "BC"); keygen.init(256); Key key = keygen.generateKey(); return Base64.encodeBase64String(key.getEncoded()); }