Пример #1
0
 /**
  * Generate a new MWK
  *
  * @param desBytes byte array of the DES key (24 bytes)
  * @return Hex String of the new encrypted MWK ready for transmission to ValueLink
  */
 public byte[] generateMwk(byte[] desBytes) {
   if (debug) {
     Debug.logInfo(
         "DES Key : " + StringUtil.toHexString(desBytes) + " / " + desBytes.length, module);
   }
   SecretKeyFactory skf1 = null;
   SecretKey mwk = null;
   try {
     skf1 = SecretKeyFactory.getInstance("DESede");
   } catch (NoSuchAlgorithmException e) {
     Debug.logError(e, module);
   }
   DESedeKeySpec desedeSpec2 = null;
   try {
     desedeSpec2 = new DESedeKeySpec(desBytes);
   } catch (InvalidKeyException e) {
     Debug.logError(e, module);
   }
   if (skf1 != null && desedeSpec2 != null) {
     try {
       mwk = skf1.generateSecret(desedeSpec2);
     } catch (InvalidKeySpecException e) {
       Debug.logError(e, module);
     }
   }
   if (mwk != null) {
     return generateMwk(mwk);
   } else {
     return null;
   }
 }
Пример #2
0
  protected SecretKey getDesEdeKey(byte[] rawKey) {
    SecretKeyFactory skf = null;
    try {
      skf = SecretKeyFactory.getInstance("DESede");
    } catch (NoSuchAlgorithmException e) {
      // should never happen since DESede is a standard algorithm
      Debug.logError(e, module);
      return null;
    }

    // load the raw key
    if (rawKey.length > 0) {
      DESedeKeySpec desedeSpec1 = null;
      try {
        desedeSpec1 = new DESedeKeySpec(rawKey);
      } catch (InvalidKeyException e) {
        Debug.logError(e, "Not a valid DESede key", module);
        return null;
      }

      // create the SecretKey Object
      SecretKey key = null;
      try {
        key = skf.generateSecret(desedeSpec1);
      } catch (InvalidKeySpecException e) {
        Debug.logError(e, module);
      }
      return key;
    } else {
      throw new RuntimeException("No valid DESede key available");
    }
  }
Пример #3
0
  public static String decryptIt(String value) {
    try {
      DESKeySpec keySpec = new DESKeySpec(cryptoPass.getBytes("UTF8"));
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
      SecretKey key = keyFactory.generateSecret(keySpec);

      byte[] encrypedPwdBytes = Base64.decode(value, Base64.DEFAULT);
      // cipher is not thread safe
      Cipher cipher = Cipher.getInstance("DES");
      cipher.init(Cipher.DECRYPT_MODE, key);
      byte[] decrypedValueBytes = (cipher.doFinal(encrypedPwdBytes));

      String decrypedValue = new String(decrypedValueBytes);
      Log.d(TAG, "Decrypted: " + value + " -> " + decrypedValue);
      return decrypedValue;

    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    }
    return value;
  }
Пример #4
0
 /**
  * This method helps in decrypting the password
  *
  * @param property
  * @return
  * @throws GeneralSecurityException
  * @throws IOException
  */
 public static String decrypt(String property) throws GeneralSecurityException, IOException {
   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
   SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
   Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
   pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
   return new String(pbeCipher.doFinal(base64Decode(property)));
 }
Пример #5
0
 /**
  * 转换密钥
  *
  * @param password
  * @return
  * @throws NoSuchAlgorithmException
  * @throws InvalidKeySpecException
  */
 public static Key toKey(String password)
     throws NoSuchAlgorithmException, InvalidKeySpecException {
   PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
   SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
   SecretKey key = factory.generateSecret(keySpec);
   return key;
 }
Пример #6
0
 public static String encrypt(String property) throws GeneralSecurityException {
   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
   SecretKey key = keyFactory.generateSecret(new PBEKeySpec(getPassword()));
   Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
   pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
   return ENCODING_MODE_1 + base64Encode(pbeCipher.doFinal(property.getBytes()));
 }
Пример #7
0
  /**
   * @param s
   * @return
   * @throws GeneralSecurityException
   * @throws UnsupportedEncodingException
   */
  public static String decrypt(final String s)
      throws GeneralSecurityException, UnsupportedEncodingException {
    String decrypted = null;

    try {
      if (s != null) {
        final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        final SecretKey secretKey =
            secretKeyFactory.generateSecret(new PBEKeySpec(secret.toCharArray()));
        final Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new PBEParameterSpec(SALT, 20));
        final byte[] stringBytes = s.getBytes("UTF-8");
        final byte[] decodedBytes = Base64.decode(stringBytes, Base64.DEFAULT);
        final byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        decrypted = new String(decryptedBytes, "UTF-8");
      }
    } catch (GeneralSecurityException x) {
      throw x;
    } catch (UnsupportedEncodingException x) {
      throw x;
    } catch (Exception x) {
      DBG.m(x);
    }

    return decrypted;
  }
Пример #8
0
  // Creates a PBKDF2 hash of the password string using the random salted
  // provided
  private byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes)
      throws NoSuchAlgorithmException, InvalidKeySpecException {
    PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
    SecretKeyFactory skf = SecretKeyFactory.getInstance(ReadProperties.getProperty("pbkdf2_algo"));

    return skf.generateSecret(spec).getEncoded();
  }
Пример #9
0
  /**
   * 转换密钥<br>
   *
   * @param password
   * @return
   * @throws Exception
   */
  private static Key toKey(String password) throws Exception {
    PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
    SecretKey secretKey = keyFactory.generateSecret(keySpec);

    return secretKey;
  }
Пример #10
0
  public static void main(String args[]) throws Exception {
    byte key[] = password.getBytes();
    DESKeySpec desKeySpec = new DESKeySpec(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

    // Create cipher mode
    Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    desCipher.init(Cipher.DECRYPT_MODE, secretKey);

    // Create stream
    FileInputStream fis = new FileInputStream("out.txt");
    BufferedInputStream bis = new BufferedInputStream(fis);
    CipherInputStream cis = new CipherInputStream(bis, desCipher);
    ObjectInputStream ois = new ObjectInputStream(cis);

    // Read
    String plaintext2 = ois.readUTF();
    ois.close();

    // Compare
    System.out.println(plaintext);
    System.out.println(plaintext2);
    System.out.println("Identical? " + (plaintext.equals(plaintext2)));
  }
Пример #11
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");
    }
  }
Пример #12
0
  /**
   * Get a hashed password ready for storage or comparison.
   *
   * @param password The password to hash
   * @param NaCl The salt to use in the hashing process
   * @return A string array with the password in the 0 position and the salt in the 1 position
   */
  private static String[] getSecurePassword(String password, String NaCl) {
    int iterations = 1000;
    char[] chars = password.toCharArray();
    System.out.println("-----------------------------------------");
    System.out.println(NaCl);
    byte[] salt = NaCl.getBytes();

    PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, 64 * 8);
    SecretKeyFactory skf;
    byte[] hash = null;
    try {
      skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
      hash = skf.generateSecret(spec).getEncoded();
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
      e.printStackTrace();
    }

    String[] ret = new String[0];
    try {
      ret = new String[] {(new String(hash, "UTF-8")), (new String(salt, "UTF-8"))};
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return ret;
  }
Пример #13
0
 public static String encrypt(String property) throws GeneralSecurityException {
   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encrypteAlgorithm);
   SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
   Cipher pbeCipher = Cipher.getInstance(encrypteAlgorithm);
   pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
   return base64Encode(pbeCipher.doFinal(property.getBytes()));
 }
Пример #14
0
  /**
   * 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);
  }
Пример #15
0
  private static void bcDES() throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    // Key convert
    DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
    SecretKeyFactory factory = SecretKeyFactory.getInstance("DES", "BC");
    SecretKey desKey = factory.generateSecret(desKeySpec);

    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, desKey);

    System.out.println("BC" + cipher.getProvider());

    byte[] result = cipher.doFinal("ABC".getBytes());
    String hexResult = Hex.encodeHexString(result);
    System.out.println(hexResult);

    cipher.init(Cipher.DECRYPT_MODE, desKey);
    result =
        cipher.doFinal(
            Hex.decodeHex(hexResult.toCharArray())
            // result
            );
    System.out.println(new String(result));
  }
Пример #16
0
  /**
   * Encode password using DES encryption with given challenge.
   *
   * @param challenge a random set of bytes.
   * @param password a password
   * @return DES hash of password and challenge
   */
  public ByteBuffer encodePassword(ByteBuffer challenge, String password) {
    if (challenge.length != 16)
      throw new RuntimeException("Challenge must be exactly 16 bytes long.");

    // VNC password consist of up to eight ASCII characters.
    byte[] key = {0, 0, 0, 0, 0, 0, 0, 0}; // Padding
    byte[] passwordAsciiBytes = password.getBytes(RfbConstants.US_ASCII_CHARSET);
    System.arraycopy(passwordAsciiBytes, 0, key, 0, Math.min(password.length(), 8));

    // Flip bytes (reverse bits) in key
    for (int i = 0; i < key.length; i++) {
      key[i] = flipByte(key[i]);
    }

    try {
      KeySpec desKeySpec = new DESKeySpec(key);
      SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
      SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
      Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
      cipher.init(Cipher.ENCRYPT_MODE, secretKey);

      ByteBuffer buf =
          new ByteBuffer(cipher.doFinal(challenge.data, challenge.offset, challenge.length));

      return buf;
    } catch (Exception e) {
      throw new RuntimeException("Cannot encode password.", e);
    }
  }
Пример #17
0
  public static byte[] decrypt(PrivateKey privKey, Message message) throws CryptoException {
    try {
      Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      rsaCipher.init(Cipher.DECRYPT_MODE, privKey);
      byte[] secretKeyBytes = rsaCipher.doFinal(message.sessionKey);

      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("AES");
      KeySpec ks = new SecretKeySpec(secretKeyBytes, "AES");
      SecretKey secretKey = keyFactory.generateSecret(ks);

      Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      aesCipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(message.iv));
      byte[] messageBytes = aesCipher.doFinal(message.ciphertext);

      return messageBytes;
    } catch (NoSuchAlgorithmException
        | NoSuchPaddingException
        | InvalidKeyException
        | IllegalBlockSizeException
        | BadPaddingException
        | InvalidKeySpecException
        | InvalidAlgorithmParameterException e) {
      throw new CryptoException(e);
    }
  }
  public static String encrypt(String originalText, String password) {
    String enc = "";
    try {
      // cara penggunaan JCE u/ melakukan enkripsi berdasarkan metode enkripsi PBE, yg dipilih
      // (tidak
      // mesti PBEWithMD5AndDES
      PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(METHOD);
      SecretKey secretKey = keyFactory.generateSecret(keySpec);
      PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterationCount);
      cipher = Cipher.getInstance(METHOD);
      cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);
      outputArray = originalText.getBytes(encoding);
      cryptedText = new ByteArrayOutputStream();
      CipherOutputStream out = new CipherOutputStream(cryptedText, cipher);
      out.write(outputArray);
      out.flush();
      out.close();
      return cryptedText.toString();

    } catch (IOException ex) {
      Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
      Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidAlgorithmParameterException ex) {
      Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
      Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
      Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
      Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "error";
  }
Пример #19
0
  /**
   * Decrypt an encrypted PKCS 8 format private key.
   *
   * <p>Based on ghstark's post on Aug 6, 2006 at
   * http://forums.sun.com/thread.jspa?threadID=758133&messageID=4330949
   *
   * @param encryptedPrivateKey The raw data of the private key
   * @param keyFile The file containing the private key
   */
  private KeySpec decryptPrivateKey(byte[] encryptedPrivateKey, String keyPassword)
      throws GeneralSecurityException {
    EncryptedPrivateKeyInfo epkInfo;
    try {
      epkInfo = new EncryptedPrivateKeyInfo(encryptedPrivateKey);
    } catch (IOException ex) {
      // Probably not an encrypted key.
      return null;
    }

    char[] keyPasswd = keyPassword.toCharArray();

    SecretKeyFactory skFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName());
    Key key = skFactory.generateSecret(new PBEKeySpec(keyPasswd));

    Cipher cipher = Cipher.getInstance(epkInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, key, epkInfo.getAlgParameters());

    try {
      return epkInfo.getKeySpec(cipher);
    } catch (InvalidKeySpecException ex) {
      getLogger().error("signapk: Password for private key may be bad.");
      throw ex;
    }
  }
Пример #20
0
  public static final void main(String[] args) throws Exception {

    // Generate a PBE key
    SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
    SecretKey skey = skFac.generateSecret(new PBEKeySpec("test123".toCharArray()));

    // Initialize the PBE cipher
    Cipher cipher = Cipher.getInstance(ALGO);
    cipher.init(Cipher.ENCRYPT_MODE, skey);

    // Permit access to the Cipher.spi field (a CipherSpi object)
    Field spi = Cipher.class.getDeclaredField("spi");
    spi.setAccessible(true);
    Object value = spi.get(cipher);

    // Permit access to the CipherSpi.engineGetKeySize method
    Method engineGetKeySize =
        PKCS12PBECipherCore$PBEWithSHA1AndDESede.class.getDeclaredMethod(
            "engineGetKeySize", Key.class);
    engineGetKeySize.setAccessible(true);

    // Check the key size
    int keySize = (int) engineGetKeySize.invoke(value, skey);
    if (keySize == KEYSIZE) {
      System.out.println(ALGO + ".engineGetKeySize returns " + keySize + " bits, as expected");
      System.out.println("OK");
    } else {
      throw new Exception("ERROR: " + ALGO + " key size is incorrect");
    }
  }
Пример #21
0
  private static int generateIterationCount(String passphrase, byte[] salt) {
    int TARGET_ITERATION_TIME = 50; // ms
    int MINIMUM_ITERATION_COUNT = 100; // default for low-end devices
    int BENCHMARK_ITERATION_COUNT = 10000; // baseline starting iteration count

    try {
      PBEKeySpec keyspec =
          new PBEKeySpec(passphrase.toCharArray(), salt, BENCHMARK_ITERATION_COUNT);
      SecretKeyFactory skf = SecretKeyFactory.getInstance("PBEWITHSHA1AND128BITAES-CBC-BC");

      long startTime = System.currentTimeMillis();
      skf.generateSecret(keyspec);
      long finishTime = System.currentTimeMillis();

      int scaledIterationTarget =
          (int)
              (((double) BENCHMARK_ITERATION_COUNT / (double) (finishTime - startTime))
                  * TARGET_ITERATION_TIME);

      if (scaledIterationTarget < MINIMUM_ITERATION_COUNT) return MINIMUM_ITERATION_COUNT;
      else return scaledIterationTarget;
    } catch (NoSuchAlgorithmException e) {
      Log.w("MasterSecretUtil", e);
      return MINIMUM_ITERATION_COUNT;
    } catch (InvalidKeySpecException e) {
      Log.w("MasterSecretUtil", e);
      return MINIMUM_ITERATION_COUNT;
    }
  }
Пример #22
0
  /**
   * Method TDESECB.
   *
   * @param plaintext byte[]
   * @param key byte[]
   * @param opmode int
   * @return byte[]
   */
  public static byte[] TDESECB(byte[] plaintext, byte[] key, int opmode) {

    byte[] ciphertext = null;

    try {
      // 2KTDEA key is encountered, expand to 192 bit
      byte[] _key;
      if (key.length == 16) {
        if (debug) {
          System.out.println("Expanding from 128 to 192");
        }
        byte[] ekey = new byte[24];
        System.arraycopy(key, 0, ekey, 0, key.length);
        System.arraycopy(key, 0, ekey, key.length, key.length / 2);
        _key = ekey;
      } else {
        _key = key;
      }

      if (debug) {
        System.out.println("Key: " + DataUtil.byteArrayToString(_key));
      }
      DESedeKeySpec ks = new DESedeKeySpec(_key);
      SecretKeyFactory kf = SecretKeyFactory.getInstance("DESede");
      SecretKey sk = kf.generateSecret(ks);
      Cipher c = Cipher.getInstance("DESede/ECB/NoPadding");
      c.init(opmode, sk);
      ciphertext = c.doFinal(plaintext);

    } catch (Throwable e) {
      e.printStackTrace();
    }

    return ciphertext;
  }
 /**
  * Loads the PBE secret key.
  *
  * @throws Exception if an error ocurrs when loading the PBE key.
  */
 private void loadPBESecretKey() throws Exception {
   // Create the PBE secret key
   cipherSpec = new PBEParameterSpec(salt, iterationCount);
   PBEKeySpec keySpec = new PBEKeySpec(keyStorePassword);
   SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEwithMD5andDES");
   cipherKey = factory.generateSecret(keySpec);
 }
Пример #24
0
  public Crypto(String passPhrase) throws Exception {

    set = new HashSet<Point>();
    random = new Random();
    for (int i = 0; i < 10; i++) {
      point = new Point(random.nextInt(1000), random.nextInt(2000));
      set.add(point);
    }
    last = random.nextInt(5000);
    try {
      // Create Key
      // byte key[] = passPhrase.getBytes();
      ois = new ObjectInputStream(new FileInputStream("keyfile"));
      DESKeySpec desKeySpec = new DESKeySpec((byte[]) ois.readObject());
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
      SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

      // Create Cipher
      eCipher = Cipher.getInstance("DES/CFB8/NoPadding");
      dCipher = Cipher.getInstance("DES/CFB8/NoPadding");

      // Create the ciphers
      eCipher.init(Cipher.ENCRYPT_MODE, secretKey);
      dCipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec((byte[]) ois.readObject()));

    } catch (javax.crypto.NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (java.security.NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (java.security.InvalidKeyException e) {
      e.printStackTrace();
    }
  }
Пример #25
0
  /**
   * 加密(使用DES算法)
   *
   * @param txt 需要加密的文本
   * @param key 密钥
   * @return 成功加密的文本
   * @throws InvalidKeySpecException
   * @throws InvalidKeyException
   * @throws NoSuchPaddingException
   * @throws IllegalBlockSizeException
   * @throws BadPaddingException
   */
  private static String enCrypto(String txt, String key)
      throws InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException,
          IllegalBlockSizeException, BadPaddingException {
    StringBuffer sb = new StringBuffer();
    DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
    SecretKeyFactory skeyFactory = null;
    Cipher cipher = null;
    try {
      skeyFactory = SecretKeyFactory.getInstance("DES");
      cipher = Cipher.getInstance("DES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    SecretKey deskey = skeyFactory != null ? skeyFactory.generateSecret(desKeySpec) : null;
    if (cipher != null) {
      cipher.init(Cipher.ENCRYPT_MODE, deskey);
    }
    byte[] cipherText = cipher != null ? cipher.doFinal(txt.getBytes()) : new byte[0];
    for (int n = 0; n < cipherText.length; n++) {
      String stmp = (java.lang.Integer.toHexString(cipherText[n] & 0XFF));

      if (stmp.length() == 1) {
        sb.append("0" + stmp);
      } else {
        sb.append(stmp);
      }
    }
    return sb.toString().toUpperCase();
  }
 private static byte[] encryptPassword(byte[] password, byte[] salt) {
   try {
     byte[] encryptedPassword = null;
     PBEKeySpec pbeKeySpec = new PBEKeySpec(getPassword(), salt, 1024, 256);
     SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(ENCRYPTION_ALGORITHM);
     SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
     PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 10);
     Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
     cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParameterSpec);
     encryptedPassword = cipher.doFinal(password);
     return encryptedPassword;
   } catch (NoSuchAlgorithmException e) {
     LogHelper.log(e);
   } catch (InvalidKeySpecException e) {
     LogHelper.log(e);
   } catch (InvalidKeyException e) {
     LogHelper.log(e);
   } catch (IllegalBlockSizeException e) {
     LogHelper.log(e);
   } catch (BadPaddingException e) {
     LogHelper.log(e);
   } catch (NoSuchPaddingException e) {
     LogHelper.log(e);
   } catch (InvalidAlgorithmParameterException e) {
     LogHelper.log(e);
   }
   return null;
 }
Пример #27
0
 protected SecretKey getKey() throws Exception {
   if (key == null) {
     SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ENCRYPTION_SCHEME);
     DESKeySpec keySpec = new DESKeySpec(stringKey.getBytes(UNICODE_FORMAT));
     key = keyFactory.generateSecret(keySpec);
   }
   return key;
 }
Пример #28
0
  String decrypt(String data) throws GeneralSecurityException, IOException {
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
    SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
    Cipher cipher = Cipher.getInstance(algorithm);
    cipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));

    return new String(cipher.doFinal(Base64.decode(data, Base64.NO_WRAP)), "UTF-8");
  }
 private static SecretKey loadKeyEncryptionKey() throws Exception {
   String fileName = "keyEncryptKey";
   String jceAlgorithmName = "DESede";
   DESedeKeySpec keySpec = new DESedeKeySpec(JavaUtils.getBytesFromFile(fileName));
   SecretKeyFactory skf = SecretKeyFactory.getInstance(jceAlgorithmName);
   SecretKey key = skf.generateSecret(keySpec);
   return key;
 }
Пример #30
0
  String encrypt(String data) throws GeneralSecurityException, UnsupportedEncodingException {
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
    SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
    Cipher cipher = Cipher.getInstance(algorithm);
    cipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));

    return Base64.encodeToString(cipher.doFinal(data.getBytes("UTF-8")), Base64.NO_WRAP);
  }