/** construct a key and iv (if necessary) suitable for use with a Cipher. */
    public static CipherParameters makePBEParameters(
        PBEKeySpec keySpec, int type, int hash, int keySize, int ivSize) {
      PBEParametersGenerator generator = makePBEGenerator(type, hash);
      byte[] key;
      CipherParameters param;

      if (type == PKCS12) {
        key = PBEParametersGenerator.PKCS12PasswordToBytes(keySpec.getPassword());
      } else {
        key = PBEParametersGenerator.PKCS5PasswordToBytes(keySpec.getPassword());
      }

      generator.init(key, keySpec.getSalt(), keySpec.getIterationCount());

      if (ivSize != 0) {
        param = generator.generateDerivedParameters(keySize, ivSize);
      } else {
        param = generator.generateDerivedParameters(keySize);
      }

      for (int i = 0; i != key.length; i++) {
        key[i] = 0;
      }

      return param;
    }
Exemple #2
0
    private static byte[] convertPassword(int type, PBEKeySpec keySpec) {
      byte[] key;

      if (type == PKCS12) {
        key = PBEParametersGenerator.PKCS12PasswordToBytes(keySpec.getPassword());
      } else if (type == PKCS5S2_UTF8 || type == PKCS5S1_UTF8) {
        key = PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(keySpec.getPassword());
      } else {
        key = PBEParametersGenerator.PKCS5PasswordToBytes(keySpec.getPassword());
      }
      return key;
    }
Exemple #3
0
 /**
  * Creates a PBE key from a given PBE key specification.
  *
  * @param key the given PBE key specification
  */
 PBEKey(PBEKeySpec keySpec, String keytype) throws InvalidKeySpecException {
   char[] passwd = keySpec.getPassword();
   if (passwd == null) {
     // Should allow an empty password.
     passwd = new char[0];
   }
   // Accept "\0" to signify "zero-length password with no terminator".
   if (!(passwd.length == 1 && passwd[0] == 0)) {
     for (int i = 0; i < passwd.length; i++) {
       if ((passwd[i] < '\u0020') || (passwd[i] > '\u007E')) {
         throw new InvalidKeySpecException("Password is not ASCII");
       }
     }
   }
   this.key = new byte[passwd.length];
   for (int i = 0; i < passwd.length; i++) this.key[i] = (byte) (passwd[i] & 0x7f);
   java.util.Arrays.fill(passwd, ' ');
   type = keytype;
 }