/**
  * 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 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;
    }
  }
Exemple #3
0
  /** 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 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);
    }
  }
Exemple #5
0
  /**
   * 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;
  }
Exemple #6
0
  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);
  }
Exemple #9
0
  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");
    }
  }
 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();
 }
Exemple #11
0
  /** 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);
      }
    }
  }
Exemple #12
0
 /**
  * 加密
  *
  * @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;
 }
 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 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();
  }
Exemple #15
0
  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);
    }
  }
Exemple #16
0
  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;
  }
Exemple #17
0
  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;
  }
Exemple #18
0
 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;
 }
Exemple #19
0
  /**
   * 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();
    }
  }
Exemple #21
0
  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;
  }
  /** @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;
  }
Exemple #23
0
 private byte[] genKey() {
   if (!isInited) {
     init();
   }
   // 首先 生成一个密钥(SecretKey),
   // 然后,通过这个秘钥,返回基本编码格式的密钥,如果此密钥不支持编码,则返回 null。
   return keyGen.generateKey().getEncoded();
 }
Exemple #24
0
  public String createKey() throws NoSuchAlgorithmException, NoSuchProviderException {

    KeyGenerator keygen = KeyGenerator.getInstance("AES", "BC");
    keygen.init(256);
    Key key = keygen.generateKey();

    return Base64.encodeBase64String(key.getEncoded());
  }
Exemple #25
0
  // 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
Exemple #26
0
 public static void setKeyCode() {
   try {
     KeyGenerator keygen = KeyGenerator.getInstance("DES");
     SecretKey deskey = keygen.generateKey();
     keyCode = baseEncode(deskey.getEncoded());
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Exemple #27
0
  public static void main(String[] args) throws Exception {
    // Gen Key
    KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
    SecretKey key = keyGenerator.generateKey();
    bytesKey = key.getEncoded();

    jdkDES();
    bcDES();
  }
 static {
   try {
     KeyGenerator generator = KeyGenerator.getInstance("AES");
     key = generator.generateKey();
   } catch (NoSuchAlgorithmException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Exemple #29
0
 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;
 }
 static {
   try {
     KeyGenerator kg = KeyGenerator.getInstance(algorithm);
     kg.init(keyLen, new SecureRandom());
     cipherKey = kg.generateKey();
   } catch (Exception e) {
     fail("No key " + e);
   }
 }