Ejemplo n.º 1
0
  private void cambiarBtnActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_cambiarBtnActionPerformed
    char[] claveActualChar = claveActualTF.getPassword();
    char[] claveNuevaChar = claveNuevaTF.getPassword();

    String claveActual = new String(claveActualChar);
    String claveNueva = new String(claveNuevaChar);

    try {
      jp.cambiarClave("Administrador", claveActual, claveNueva);
      JOptionPane.showMessageDialog(
          rootPane, "Contraseña cambiada exitosamente.", "Mensaje", JOptionPane.OK_OPTION);
      this.setVisible(false);
    } catch (NoSuchAlgorithmException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (NoSuchPaddingException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (IOException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (ClassNotFoundException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (InvalidKeyException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (IllegalBlockSizeException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (BadPaddingException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (ClaveNoValidaException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    } catch (IllegalArgumentException ex) {
      JOptionPane.showMessageDialog(rootPane, ex.getMessage(), "Error", JOptionPane.OK_OPTION);
    }
  } // GEN-LAST:event_cambiarBtnActionPerformed
Ejemplo n.º 2
0
 public static String decrypt4AES(String content, String key) {
   try {
     byte[] decryptFrom = Base64.decodeBase64(content);
     IvParameterSpec zeroIv = new IvParameterSpec(key.getBytes("utf-8"));
     SecretKeySpec key1 = new SecretKeySpec(key.getBytes("utf-8"), "AES");
     Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
     cipher.init(Cipher.DECRYPT_MODE, key1, zeroIv);
     byte decryptedData[] = cipher.doFinal(decryptFrom);
     return new String(decryptedData); // 加密
   } 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();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
  public void downloadFile(
      String fileUrl, File directory, String rString, File directoryFolder, String cifrado) {
    try {
      directorio = directoryFolder;
      URL url = new URL(fileUrl);
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
      // urlConnection.setRequestMethod("GET");
      // urlConnection.setDoOutput(true);
      urlConnection.connect();
      InputStream inputStream = urlConnection.getInputStream();
      if (cifrado.equals("AES")) {
        aesCypher(rString, inputStream, directory);
      } else {
        rsaCypher(rString, inputStream, directory);
      }

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 4
0
 private byte[] encrypt(byte[] content, byte[] keyBytes) {
   byte[] encryptedText = null;
   if (!isInited) {
     init();
   }
   /**
    * 类 SecretKeySpec 可以使用此类来根据一个字节数组构造一个 SecretKey, 而无须通过一个(基于 provider 的)SecretKeyFactory。
    * 此类仅对能表示为一个字节数组并且没有任何与之相关联的钥参数的原始密钥有用 构造方法根据给定的字节数组构造一个密钥。 此构造方法不检查给定的字节数组是否指定了一个算法的密钥。
    */
   Key key = new SecretKeySpec(keyBytes, "AES");
   try {
     // 用密钥初始化此 cipher。
     cipher.init(Cipher.ENCRYPT_MODE, key);
   } catch (InvalidKeyException e) {
     e.printStackTrace();
   }
   try {
     // 按单部分操作加密或解密数据,或者结束一个多部分操作。(不知道神马意思)
     encryptedText = cipher.doFinal(content);
   } catch (IllegalBlockSizeException e) {
     e.printStackTrace();
   } catch (BadPaddingException e) {
     e.printStackTrace();
   }
   return encryptedText;
 }
Ejemplo n.º 5
0
  /**
   * @param src
   * @return source data
   * @throws NoSuchPaddingException
   * @throws NoSuchAlgorithmException
   * @throws InvalidAlgorithmParameterException
   * @throws InvalidKeyException
   */
  public byte[] decrypt(String baseKey, String src)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
          InvalidAlgorithmParameterException {

    byte[] key = SHA256(baseKey);

    if (secureKey == null) {
      secureKey = new SecretKeySpec(key, "AES");
    }

    if (decryptor == null) {
      decryptor = Cipher.getInstance("AES/CBC/PKCS5Padding");
      decryptor.init(Cipher.DECRYPT_MODE, secureKey, new IvParameterSpec(IV.getBytes()));
    }

    byte[] dec = Base64.decode(src, 0);
    byte[] ret = null;

    try {
      ret = decryptor.doFinal(dec);
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }

    return ret;
  }
Ejemplo n.º 6
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;
  }
Ejemplo n.º 7
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;
  }
Ejemplo n.º 8
0
  private static String encrypt(String baseKey, byte[] src)
      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
          InvalidAlgorithmParameterException {

    byte[] key = SHA256(baseKey);

    if (secureKey == null) {
      secureKey = new SecretKeySpec(key, "AES");
    }

    if (encryptor == null) {
      encryptor = Cipher.getInstance("AES/CBC/PKCS5Padding");
      encryptor.init(Cipher.ENCRYPT_MODE, secureKey, new IvParameterSpec(IV.getBytes()));
    }

    byte[] encrypted = null;

    try {
      encrypted = encryptor.doFinal(src);
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }
    return Base64.encodeToString(encrypted, Base64.NO_WRAP);
  }
Ejemplo n.º 9
0
  /**
   * @param strKey key
   * @param strIvKey 矢量key
   * @param strContent 要解密的内容
   * @return 加密后的字符串,失败返回null
   */
  public static String encode(String strKey, String strIvKey, String strContent) {

    IvParameterSpec zeroIv = new IvParameterSpec(strIvKey.getBytes());
    SecretKeySpec key = new SecretKeySpec(strKey.getBytes(), "AES");
    Cipher cipher;
    byte[] encryptedData = null;

    try {
      cipher = Cipher.getInstance(TRANSFORMATION);
      cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
      encryptedData = cipher.doFinal(strContent.getBytes(CHARSET));
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
      e.printStackTrace();
      Log.e(TAG, "无效的矢量key");
    } catch (InvalidKeyException e) {
      e.printStackTrace();
      Log.e(TAG, "无效的key");
    } catch (BadPaddingException e) {
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    if (encryptedData == null) {
      return null;
    }
    return Base64Util.encode(encryptedData);
  }
Ejemplo n.º 10
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;
  }
Ejemplo n.º 11
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;
 }
Ejemplo n.º 12
0
  /**
   * 使用口令加密私钥(Base64编码)
   *
   * @return
   */
  public String encryptPrivateKey(String passphrase) {
    byte[] seeds = null;
    byte[] raw = mMyPrivKey.getEncoded();
    byte[] encrypted = null;

    Cipher cipher;
    try {
      seeds = getRawKey(passphrase.getBytes());
      SecretKeySpec skeySpec = new SecretKeySpec(seeds, PASS_ALGO);
      cipher = Cipher.getInstance(PASS_ALGO);
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
      encrypted = cipher.doFinal(raw);
    } 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();
    }

    String result = Base64.encodeToString(encrypted, Base64.DEFAULT);
    return result;
  }
Ejemplo n.º 13
0
 private static byte[] encrypt(String content, String password)
     throws InvalidAlgorithmParameterException {
   try {
     byte[] keyStr = getKey(password);
     SecretKeySpec key = new SecretKeySpec(keyStr, "AES");
     //            Cipher cipher = Cipher.getInstance(algorithmStr);//algorithmStr
     byte[] ivbuf = new byte[16];
     for (int i = 0; i < ivbuf.length; i++) {
       ivbuf[i] = 0;
     }
     IvParameterSpec iv = new IvParameterSpec(ivbuf);
     Cipher cipher = Cipher.getInstance(algorithmStr);
     byte[] byteContent = content.getBytes("utf-8");
     cipher.init(Cipher.ENCRYPT_MODE, key, iv); //   ʼ
     byte[] result = cipher.doFinal(pad16Byte(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;
 }
Ejemplo n.º 14
0
  protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType)
      throws InvalidKeyException {
    byte[] encoded = null;
    try {
      encoded = engineDoFinal(wrappedKey, 0, wrappedKey.length);
    } catch (BadPaddingException e) {
      throw new InvalidKeyException(e.getMessage());
    } catch (IllegalBlockSizeException e2) {
      throw new InvalidKeyException(e2.getMessage());
    }

    if (wrappedKeyType == Cipher.SECRET_KEY) {
      return new SecretKeySpec(encoded, wrappedKeyAlgorithm);
    } else {
      try {
        KeyFactory kf =
            KeyFactory.getInstance(wrappedKeyAlgorithm, BouncyCastleProvider.PROVIDER_NAME);

        if (wrappedKeyType == Cipher.PUBLIC_KEY) {
          return kf.generatePublic(new X509EncodedKeySpec(encoded));
        } else if (wrappedKeyType == Cipher.PRIVATE_KEY) {
          return kf.generatePrivate(new PKCS8EncodedKeySpec(encoded));
        }
      } catch (NoSuchProviderException e) {
        throw new InvalidKeyException("Unknown key type " + e.getMessage());
      } catch (NoSuchAlgorithmException e) {
        throw new InvalidKeyException("Unknown key type " + e.getMessage());
      } catch (InvalidKeySpecException e2) {
        throw new InvalidKeyException("Unknown key type " + e2.getMessage());
      }

      throw new InvalidKeyException("Unknown key type " + wrappedKeyType);
    }
  }
Ejemplo n.º 15
0
  private static byte[] decrypt(byte[] content, String password)
      throws InvalidAlgorithmParameterException {
    try {
      //            System.out.println("before decode.content.length = " + content.length);
      content = pad16Byte(content);
      byte[] keyStr = getKey(password);
      SecretKeySpec key = new SecretKeySpec(keyStr, "AES");
      byte[] ivbuf = new byte[16];
      for (int i = 0; i < ivbuf.length; i++) {
        ivbuf[i] = 0;
      }
      IvParameterSpec iv = new IvParameterSpec(ivbuf);

      Cipher cipher = Cipher.getInstance(algorithmStr);
      cipher.init(Cipher.DECRYPT_MODE, key, iv); //   ʼ
      //            System.out.println("after decode.content.length = " + content.length);
      byte[] result = cipher.doFinal(content);
      return 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;
  }
Ejemplo n.º 16
0
 public String desencripta(byte[] message) throws EncriptaException {
   try {
     final MessageDigest md = MessageDigest.getInstance("md5");
     final byte[] digestOfPassword = md.digest(clave.getBytes("utf-8"));
     final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
     for (int j = 0, k = 16; j < 8; ) {
       keyBytes[k++] = keyBytes[j++];
     }
     final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
     final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
     final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
     decipher.init(Cipher.DECRYPT_MODE, key, iv);
     final byte[] plainText = decipher.doFinal(message);
     return new String(plainText, "UTF-8");
   } catch (NoSuchAlgorithmException ex) {
     throw new EncriptaException(ex.getMessage());
   } catch (UnsupportedEncodingException ex) {
     throw new EncriptaException(ex.getMessage());
   } catch (NoSuchPaddingException ex) {
     throw new EncriptaException(ex.getMessage());
   } catch (InvalidKeyException ex) {
     throw new EncriptaException(ex.getMessage());
   } catch (InvalidAlgorithmParameterException ex) {
     throw new EncriptaException(ex.getMessage());
   } catch (IllegalBlockSizeException ex) {
     throw new EncriptaException(ex.getMessage());
   } catch (BadPaddingException ex) {
     throw new EncriptaException(ex.getMessage());
   }
 }
Ejemplo n.º 17
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    try {
      RSACryptoProvider rsa = new RSACryptoProvider();
      byte[] data = rsa.Encrypt("Michael");
      System.out.println(new String(data));
      System.out.println(rsa.Decrypt(data));

    } catch (InvalidKeyException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (BadPaddingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvalidKeySpecException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Ejemplo n.º 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;
 }
Ejemplo n.º 19
0
 /**
  * Do the encryption
  *
  * @param plaintext
  * @param inputLen
  * @param key
  * @param iv
  * @return
  */
 private static byte[] seafileEncrypt(
     @NonNull byte[] plaintext, int inputLen, @NonNull SecretKey key, @NonNull byte[] iv) {
   try {
     Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
     IvParameterSpec ivParams = new IvParameterSpec(iv);
     cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
     return cipher.doFinal(plaintext, 0, inputLen);
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
     Log.e(TAG, "NoSuchAlgorithmException " + e.getMessage());
     return null;
   } catch (InvalidKeyException e) {
     e.printStackTrace();
     Log.e(TAG, "InvalidKeyException " + e.getMessage());
     return null;
   } catch (InvalidAlgorithmParameterException e) {
     e.printStackTrace();
     Log.e(TAG, "InvalidAlgorithmParameterException " + e.getMessage());
     return null;
   } catch (NoSuchPaddingException e) {
     e.printStackTrace();
     Log.e(TAG, "NoSuchPaddingException " + e.getMessage());
     return null;
   } catch (IllegalBlockSizeException e) {
     e.printStackTrace();
     Log.e(TAG, "IllegalBlockSizeException " + e.getMessage());
     return null;
   } catch (BadPaddingException e) {
     e.printStackTrace();
     Log.e(TAG, "seafileEncrypt BadPaddingException " + e.getMessage());
     return null;
   }
 }
  @Override
  protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen)
      throws IllegalBlockSizeException, BadPaddingException {
    if (input != null) {
      engineUpdate(input, inputOffset, inputLen);
    }

    if (inputTooLarge) {
      throw new IllegalBlockSizeException("input must be under " + buffer.length + " bytes");
    }

    final byte[] tmpBuf;
    if (bufferOffset != buffer.length) {
      if (padding == NativeCrypto.RSA_NO_PADDING) {
        tmpBuf = new byte[buffer.length];
        System.arraycopy(buffer, 0, tmpBuf, buffer.length - bufferOffset, bufferOffset);
      } else {
        tmpBuf = Arrays.copyOf(buffer, bufferOffset);
      }
    } else {
      tmpBuf = buffer;
    }

    byte[] output = new byte[buffer.length];
    int resultSize;
    if (encrypting) {
      if (usingPrivateKey) {
        resultSize =
            NativeCrypto.RSA_private_encrypt(
                tmpBuf.length, tmpBuf, output, key.getPkeyContext(), padding);
      } else {
        resultSize =
            NativeCrypto.RSA_public_encrypt(
                tmpBuf.length, tmpBuf, output, key.getPkeyContext(), padding);
      }
    } else {
      try {
        if (usingPrivateKey) {
          resultSize =
              NativeCrypto.RSA_private_decrypt(
                  tmpBuf.length, tmpBuf, output, key.getPkeyContext(), padding);
        } else {
          resultSize =
              NativeCrypto.RSA_public_decrypt(
                  tmpBuf.length, tmpBuf, output, key.getPkeyContext(), padding);
        }
      } catch (SignatureException e) {
        IllegalBlockSizeException newE = new IllegalBlockSizeException();
        newE.initCause(e);
        throw newE;
      }
    }
    if (!encrypting && resultSize != output.length) {
      output = Arrays.copyOf(output, resultSize);
    }

    bufferOffset = 0;
    return output;
  }
Ejemplo n.º 21
0
  protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType)
      throws InvalidKeyException, NoSuchAlgorithmException {
    byte[] encoded;
    try {
      if (wrapEngine == null) {
        encoded = engineDoFinal(wrappedKey, 0, wrappedKey.length);
      } else {
        encoded = wrapEngine.unwrap(wrappedKey, 0, wrappedKey.length);
      }
    } catch (InvalidCipherTextException e) {
      throw new InvalidKeyException(e.getMessage());
    } catch (BadPaddingException e) {
      throw new InvalidKeyException(e.getMessage());
    } catch (IllegalBlockSizeException e2) {
      throw new InvalidKeyException(e2.getMessage());
    }

    if (wrappedKeyType == Cipher.SECRET_KEY) {
      return new SecretKeySpec(encoded, wrappedKeyAlgorithm);
    } else if (wrappedKeyAlgorithm.equals("") && wrappedKeyType == Cipher.PRIVATE_KEY) {
      /*
       * The caller doesn't know the algorithm as it is part of
       * the encrypted data.
       */
      try {
        PrivateKeyInfo in = PrivateKeyInfo.getInstance(encoded);

        PrivateKey privKey = BouncyCastleProvider.getPrivateKey(in);

        if (privKey != null) {
          return privKey;
        } else {
          throw new InvalidKeyException(
              "algorithm " + in.getPrivateKeyAlgorithm().getAlgorithm() + " not supported");
        }
      } catch (Exception e) {
        throw new InvalidKeyException("Invalid key encoding.");
      }
    } else {
      try {
        KeyFactory kf =
            KeyFactory.getInstance(wrappedKeyAlgorithm, BouncyCastleProvider.PROVIDER_NAME);

        if (wrappedKeyType == Cipher.PUBLIC_KEY) {
          return kf.generatePublic(new X509EncodedKeySpec(encoded));
        } else if (wrappedKeyType == Cipher.PRIVATE_KEY) {
          return kf.generatePrivate(new PKCS8EncodedKeySpec(encoded));
        }
      } catch (NoSuchProviderException e) {
        throw new InvalidKeyException("Unknown key type " + e.getMessage());
      } catch (InvalidKeySpecException e2) {
        throw new InvalidKeyException("Unknown key type " + e2.getMessage());
      }

      throw new InvalidKeyException("Unknown key type " + wrappedKeyType);
    }
  }
 public void deleteFSSFProfileDomainByUNameIdx(
     CFSecurityAuthorization Authorization,
     long argTenantId,
     long argFSSFProfileId,
     String argName) {
   final String S_ProcName = "deleteFSSFProfileDomainByUNameIdx";
   String rqst =
       CFFreeSwitchXMsgSchemaMessageFormatter.formatRqstXmlPreamble()
           + "\n"
           + "\t"
           + CFFreeSwitchXMsgFSSFProfileDomainMessageFormatter
               .formatFSSFProfileDomainRqstDeleteByUNameIdx(
                   "\n\t\t\t", argTenantId, argFSSFProfileId, argName)
           + "\n"
           + CFFreeSwitchXMsgSchemaMessageFormatter.formatRqstXmlPostamble();
   try {
     schema.getCFTipClientHandler().issueAppRequest(rqst);
   } catch (BadPaddingException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Caught BadPaddingException - " + e.getMessage(), e);
   } catch (IllegalBlockSizeException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Caught IllegalBlockSizeException - " + e.getMessage(), e);
   } catch (InvalidKeyException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Caught InvalidKeyException - " + e.getMessage(), e);
   } catch (NoSuchAlgorithmException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Caught NoSuchAlgorithmException - " + e.getMessage(), e);
   } catch (InvalidAlgorithmParameterException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(),
             S_ProcName,
             "Caught InvalidAlgorithmParameterException - " + e.getMessage(),
             e);
   } catch (NoSuchPaddingException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Caught NoSuchPaddingException - " + e.getMessage(), e);
   }
   ICFTipResponseHandler responseHandler = schema.getCFTipClientHandler().getResponseHandler();
   CFLibRuntimeException exceptionRaised = responseHandler.getExceptionRaised();
   if (exceptionRaised != null) {
     throw exceptionRaised;
   }
   boolean deleted = responseHandler.getDeleted();
   if (!deleted) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Server did not respond with a Deleted message");
   }
 }
Ejemplo n.º 23
0
 /**
  * 加密字节数组
  *
  * @param arrB 需加密的字节数组
  * @return 加密后的字节数组
  * @throws Exception
  */
 public byte[] encrypt(byte[] arrB) {
   try {
     return encryptCipher.doFinal(arrB);
   } catch (IllegalBlockSizeException e) {
     e.printStackTrace();
   } catch (BadPaddingException e) {
     e.printStackTrace();
   }
   return arrB;
 }
Ejemplo n.º 24
0
 private static byte[] func_75885_a(int p_75885_0_, Key p_75885_1_, byte p_75885_2_[]) {
   try {
     return func_75886_a(p_75885_0_, p_75885_1_.getAlgorithm(), p_75885_1_).doFinal(p_75885_2_);
   } catch (IllegalBlockSizeException illegalblocksizeexception) {
     illegalblocksizeexception.printStackTrace();
   } catch (BadPaddingException badpaddingexception) {
     badpaddingexception.printStackTrace();
   }
   System.err.println("Cipher data failed!");
   return null;
 }
 @Override
 protected byte[] engineWrap(Key key) throws IllegalBlockSizeException, InvalidKeyException {
   try {
     byte[] encoded = key.getEncoded();
     return engineDoFinal(encoded, 0, encoded.length);
   } catch (BadPaddingException e) {
     IllegalBlockSizeException newE = new IllegalBlockSizeException();
     newE.initCause(e);
     throw newE;
   }
 }
Ejemplo n.º 26
0
  public static byte[] passwordEncrypt(char[] password, byte[] plaintext) {
    byte[] salt = new byte[8];
    Random random = new Random();
    random.nextBytes(salt);

    PBEKeySpec keySpec = new PBEKeySpec(password);
    SecretKeyFactory keyFactory = null;
    try {
      keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    SecretKey key = null;
    try {
      key = keyFactory.generateSecret(keySpec);
    } catch (InvalidKeySpecException e) {
      e.printStackTrace();
    }
    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATIONS);
    Cipher cipher = null;
    try {
      cipher = Cipher.getInstance("PBEWithMD5AndDES");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();
    }
    try {
      cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
    } catch (InvalidKeyException e) {
      e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
      e.printStackTrace();
    }

    byte[] ciphertext = new byte[0];
    try {
      ciphertext = cipher.doFinal(plaintext);
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (BadPaddingException e) {
      e.printStackTrace();
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
      baos.write(salt);
      baos.write(ciphertext);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return baos.toByteArray();
  }
Ejemplo n.º 27
0
  private static byte[] func_75885_a(int par0, Key par1Key, byte[] par2ArrayOfByte) {
    try {
      return func_75886_a(par0, par1Key.getAlgorithm(), par1Key).doFinal(par2ArrayOfByte);
    } catch (IllegalBlockSizeException var4) {
      var4.printStackTrace();
    } catch (BadPaddingException var5) {
      var5.printStackTrace();
    }

    System.err.println("Cipher data failed!");
    return null;
  }
Ejemplo n.º 28
0
  public String[] encrypt(String value) throws Exception {
    try {
      KeyGenerator kgen = KeyGenerator.getInstance("AES");
      SecureRandom sran = new SecureRandom();

      kgen.init(128, sran);

      SecretKey skey = kgen.generateKey();
      byte[] raw = skey.getEncoded();

      String key = asHex(raw);

      Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");

      IvParameterSpec ivSpec = createCtrIvForAES(1, sran);

      cipher.init(Cipher.ENCRYPT_MODE, skey, ivSpec);

      byte[] encrypted = cipher.doFinal(padWithZeros(value.getBytes()));

      String vector = asHex(cipher.getIV());

      String encryptedValue = asHex(encrypted);

      return new String[] {encryptedValue, key, vector};

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

      throw new Exception("Encrypt error!", e);
    } catch (NoSuchPaddingException e) {
      e.printStackTrace();

      throw new Exception("Encrypt error!", e);
    } catch (InvalidKeyException e) {
      e.printStackTrace();

      throw new Exception("Encrypt error!", e);
    } catch (IllegalBlockSizeException e) {
      e.printStackTrace();

      throw new Exception("Encrypt error!", e);
    } catch (BadPaddingException e) {
      e.printStackTrace();

      throw new Exception("Encrypt error!", e);
    } catch (InvalidAlgorithmParameterException e) {
      e.printStackTrace();

      throw new Exception("Encrypt error!", e);
    }
  }
 public void deleteRealProject(
     CFSecurityAuthorization Authorization, CFInternetRealProjectBuff Buff) {
   final String S_ProcName = "deleteRealProject";
   String rqst =
       CFAccXMsgSchemaMessageFormatter.formatRqstXmlPreamble()
           + "\n"
           + "\t"
           + CFAccXMsgRealProjectMessageFormatter.formatRealProjectRqstDelete("\n\t\t\t", Buff)
           + "\n"
           + CFAccXMsgSchemaMessageFormatter.formatRqstXmlPostamble();
   try {
     schema.getCFTipClientHandler().issueAppRequest(rqst);
   } catch (BadPaddingException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Caught BadPaddingException - " + e.getMessage(), e);
   } catch (IllegalBlockSizeException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Caught IllegalBlockSizeException - " + e.getMessage(), e);
   } catch (InvalidKeyException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Caught InvalidKeyException - " + e.getMessage(), e);
   } catch (NoSuchAlgorithmException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Caught NoSuchAlgorithmException - " + e.getMessage(), e);
   } catch (InvalidAlgorithmParameterException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(),
             S_ProcName,
             "Caught InvalidAlgorithmParameterException - " + e.getMessage(),
             e);
   } catch (NoSuchPaddingException e) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Caught NoSuchPaddingException - " + e.getMessage(), e);
   }
   ICFTipResponseHandler responseHandler = schema.getCFTipClientHandler().getResponseHandler();
   CFLibRuntimeException exceptionRaised = responseHandler.getExceptionRaised();
   if (exceptionRaised != null) {
     throw exceptionRaised;
   }
   boolean deleted = responseHandler.getDeleted();
   if (!deleted) {
     throw CFLib.getDefaultExceptionFactory()
         .newRuntimeException(
             getClass(), S_ProcName, "Server did not respond with a Deleted message");
   }
 }
Ejemplo n.º 30
0
 /**
  * 对 datasource 数组进行解密.
  *
  * @param datasource 要解密的数据
  * @return 返回加密后的 byte[]
  */
 public byte[] createDecryptor(byte[] datasource) {
   try {
     cipher.init(Cipher.DECRYPT_MODE, deskey);
     decryptorData = cipher.doFinal(datasource);
   } catch (java.security.InvalidKeyException ex) {
     ex.printStackTrace();
   } catch (javax.crypto.BadPaddingException ex) {
     ex.printStackTrace();
   } catch (javax.crypto.IllegalBlockSizeException ex) {
     ex.printStackTrace();
   }
   return decryptorData;
 }