// reset the states to the pre-initialized values
 private void reset() {
   initialized = false;
   bytesBuffered = 0;
   padBufferLen = 0;
   if (session != null) {
     session = token.releaseSession(session);
   }
 }
  private void initialize() throws PKCS11Exception {
    if (session == null) {
      session = token.getOpSession();
    }
    CK_MECHANISM mechParams =
        (blockMode == MODE_CTR
            ? new CK_MECHANISM(mechanism, new CK_AES_CTR_PARAMS(iv))
            : new CK_MECHANISM(mechanism, iv));

    try {
      if (encrypt) {
        token.p11.C_EncryptInit(session.id(), mechParams, p11Key.keyID);
      } else {
        token.p11.C_DecryptInit(session.id(), mechParams, p11Key.keyID);
      }
    } catch (PKCS11Exception ex) {
      // release session when initialization failed
      session = token.releaseSession(session);
      throw ex;
    }
    bytesBuffered = 0;
    padBufferLen = 0;
    initialized = true;
  }