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(); }
/** * 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); }
/** * 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; }
/** 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); } } }
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; }
/** * 加密 * * @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 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 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(); }
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 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; }
/** * 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; }
@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(); } }
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 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"); } }
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; }
/** 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()); } }
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(); }
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; }
public String createKey() throws NoSuchAlgorithmException, NoSuchProviderException { KeyGenerator keygen = KeyGenerator.getInstance("AES", "BC"); keygen.init(256); Key key = keygen.generateKey(); return Base64.encodeBase64String(key.getEncoded()); }
/** @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; }
// Generate Random Key static Key makeKey(int keyBit) throws NoSuchAlgorithmException { KeyGenerator kg = KeyGenerator.getInstance("AES"); SecureRandom rd = SecureRandom.getInstance("SHA1PRNG"); kg.init(keyBit, rd); Key key = kg.generateKey(); return key; } // makeKey
public static void setKeyCode() { try { KeyGenerator keygen = KeyGenerator.getInstance("DES"); SecretKey deskey = keygen.generateKey(); keyCode = baseEncode(deskey.getEncoded()); } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) throws Exception { // Gen Key KeyGenerator keyGenerator = KeyGenerator.getInstance("DES"); SecretKey key = keyGenerator.generateKey(); bytesKey = key.getEncoded(); jdkDES(); bcDES(); }
private static byte[] generateMacSecret() { try { KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1"); return generator.generateKey().getEncoded(); } catch (NoSuchAlgorithmException e) { Log.w("keyutil", e); return null; } }
static { try { KeyGenerator kg = KeyGenerator.getInstance(algorithm); kg.init(keyLen, new SecureRandom()); cipherKey = kg.generateKey(); } catch (Exception e) { fail("No key " + e); } }
static { try { KeyGenerator generator = KeyGenerator.getInstance("AES"); key = generator.generateKey(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto"); sr.setSeed(seed); kgen.init(128, sr); SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); return raw; }
private byte[] getRawKey(byte[] seed) throws NoSuchAlgorithmException { KeyGenerator kgen = KeyGenerator.getInstance(PASS_ALGO); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(seed); kgen.init(128, sr); SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); return raw; }