Mostrando entradas con la etiqueta Angular. Mostrar todas las entradas
Mostrando entradas con la etiqueta Angular. Mostrar todas las entradas

jueves, 5 de septiembre de 2019

Understanding principles of security: Integrity

The principles of Security

The foundational principles of security are: confidentiality, integrity and availability. These principles known as the CIA triad is a guideline for information security for an organization.

Integrity

Integrity is accuracy, consistency, and trustworthiness of the data during its entire life cycle. Another term for integrity is quality. Data must be unaltered during transit and not changed by unauthorized entities. Methods used to ensure data integrity include hashing, data validation checks, data consistency checks, and access controls.

Hashes and Checksum

The process of hashing involves passing data through a cryptographic function, called a hash or digest function. This process yields a small - relative to the size of the original data- value that uniquely identifies the data. Depending on the algorithm used, the value's size is usually 128 or 160 bits. Checksum hashing can be used to verify integrity of the data during transfer.

Hashing is a one-way function that creates a fixed-length output (known as the hash, hashing value, fingerprint, message digest, and so on) from an input of any length. Common hash functions include MD5, SHA-1, SHA-256, and SHA-512. These hash functions use complex mathematical algorithms.

For example, Message Digest 5 (MD5) is a 128-bit hash algorithm. This means that no matter what the size of the input data, the output hash will always be 128 bits long. Hashing is not an encryption algorithm. Instead, hashing is used to produce a unique identifier of data without modifying the original data. The data could be a file, a hard drive, a network-traffic packet, or an email message.
The hashed value is used to detect when changes have been made to a resource. For example, when a hard drive is being imaged to create an exact duplicate, a hash is produced of the original drive before the duplication process.

Fig 1. Summary of hashing algorithms

A hash tells you nothing about the data, but it uniquely identifies it. The hashed value is simply there for comparison.

Fig 2. The hash function operates on fixed-size blocks of data

Writing a simple Hash Calculator with AngularJS, HTML5, C# and WCF.

I've written an app to demonstrate how to implement hash functions in a REST Service. The app communicates with a WCF REST service that uses the C# abstract class System.Security.Cryptography.HashAlgorithm to achieve encryption.

  1. The user enters the text to encrypt, selects the algorithm to use.
  2. The user submits the information to the service in order to get the hash code.
  3. The hash web service presents the hash code to the user.
Testing with different algorithms, we can see the length of the output.

Fig 3. Using the MD5 algorithm.
Fig 4. Using the SHA1 algorithm.
Fig 5. Using the SHA256 algorithm.
Fig 6. Using the SHA384 algorithm.
Fig 7. Using the SHA512 algorithm.
Fig 8. Changing the text, we can see a totally different output, but without no changes in the length.

Conclusion

Keeep in mind that hash functions do not encrypt the data. They use the data to make a fingerprint or snapshot of the data that is given to you as a code. That code is used to determine whether or not the data has been altered. If the data you receive has been altered, you will not get the same code number as the original data.


domingo, 3 de septiembre de 2017

Fetching JSON Data with Angular $http.get() function.

Angular has built-in support for communication with remote HTTP servers and includes some low-level methods of fetching and posting the data. Angular comes with the $http service which includes a few methods we can utilize with all verbs of the REST protocol.

We'll look at a example using the .$http.get() request. The $http.get() method accepts two parameters: URL and config object.

The first parameter URL is always required and the config is optional, the shortcut $http.get() method initiates a GET request to the server to retrieve data from the server. This example has the following files:

  • books.js: it contains the data in JSON format.
  • app.js: it contains the functional logic for the example
  • getexample.html: contains the front for the example

Fig.1. The source code for the JSON file

Fig 2. The source code for the app.js

In the previous example the controller defines a dependency to the $scope and the $http module. An HTTP GET request to the data “books.json” endpoint is carried out with the get method. It returns a $promise object with a success and error method.

Fig 3. The code for the web page

Fig 4. Running the example

If you open the web page up in your browser, you'll see a standard HTML button created, when you press the button the $http service makes an ajax call and set response to the scope's property books. Thus books can be used to draw a list in the HTML page.

jueves, 4 de febrero de 2016

Entiendo Angular: Un primer acercamiento

AngularJS es un framework open source escrito en JavaScript que sirve para implantar el patrón MVC del lado del cliente, lo que permite que puedan contruirse aplicaciones Web del tipo AJAX, por su poder expresivo se utiliza en la mayoría de proyectos SPA (Single Page Application).

Qué es SPA?

SPA (Single page Application) es una aplicación en la cual se tiene una página principal como contenedor y varias vistas contenidas dentro este contenedor que pueden refrescarse independientemente de la página principal evitando así hacer una petición de toda la página completa, lo que ayuda a hacer eficiente el ancho de banda sobretodo en aplicaciones móviles.

Las ventajas de Angular son:

  • Proporciona la capacidad de crear SPA de una manera clara y mantenible
  • Le proporciona una capacidad de data binding al HTML, lo que proporciona una experiencia responsiva al usuario.
  • El código hecho con Angular se puede probar mediante pruebas unitarias (Unit Testing)
  • Utiliza la inyección de dependencias para la separación de responsabilidades.
  • Proporciona componentes reutilizables ya que las vistas son páginas HTML y la lógica de procesamiento se lleva a cabo por los controllers (controladores) escritos en JavaScript.
  • Angular es compatible entre la mayoría de las plataformas (Android, IOS) y navegadores.
  • Puede combinarse con otras bibliotecas para JavaScript por ejemplo: Kendo UI y Jquery.

Hay dos conceptos básicos para empezar con Angular, uno es el $scope y el otro es la utilización de directives (directivas), para ejemplificar su uso, mostraré una página que despliega un lista de filósofos de cada país la cual es posible filtrar al escribir el nombre en un control INPUT.

¿Qué es el scope?

Una buena separación de aspectos no permite que la lógica de negocio se mezcle con la vista, así que todo el procesamiento se realiza mediante el controlador el cuál es el que enlaza los datos hacia la vista. Una parte integral para trabajar con angular es el llamado scope que en realidad es un alias para el ViewModel es decir el componente que permite que se comuniquen la vista y el controlador.

Aquí el código fuente del archivo MenuAngular.js el cuál contiene el JSON y la declaración del controller.

Aquí el código fuente de la página HTML:

¿Qué son las directives?

Son atributos HTML que llaman funciones pertenecientes al framework para extender de manera dinámica la funcionalidad del elemento HTML al cual pertenecen, esta es la manera básica de crear elementos HTML específicos para la aplicación, encapsular estructuras DOM complejas o manipular las hojas de estilo.

A continuación una breve descripción de las directivas que se utilizaron en el ejemplo:

  • ng-app: Esta directiva sirve para incluir e iniciar AngularJS y que se pueda utilizar en un página HTML. Generalmente esta directiva va en la etiqueta BODY o en HTML.
              <!doctype html>
    <html ng-app="App">
            
  • ng-controller: Esta directiva indica que controlador se va a utilizar en esa página o vista. Angular nos permite tener múltiples instancias de el mismo controlador en la aplicación, permitiéndonos reutilizar un montón de código.
        <body ng-controller="SimpleCtrl">      
            
  • ng-repeat: Con esta directiva se puede enumerar o iterar en una lista de objetos similar a recorrer un de un arreglo con la instrucción foreach de algunos lenguajes de programación. Adicionalmente a esta directiva le agrego la directiva filter:Name la cuál establece el filtro de búsqueda dentro del arreglo, en este caso el filtro es el valor de la variable enlazada con ng-model.
              <ul>
                        <li ng-repeat="menu in menus">{{menu.Name}}
                        <ul ng-repeat="submenu in menu.Children | filter:Name">
                            <li>{{ submenu.Name }}</li>
                        </ul>
                        </li>
                    </ul>
            
  • ng-model: Esta directiva sirva para enlazar el valor de una variable a un control HTML, generalmente se utiliza con los controles INPUT.
              <td><label for="inputSearch" class="control-label">Search:</label></td>
                    <td><input type="text" id="inputSearch" class="field-value" ng-model="Name"/></td>
            

Las siguientes imágenes muestran la página en su ejecución.
Fig 1 La página HTML en ejecución.

Fig 2 Ejemplo de una búsqueda con una coincidencia.

Fig 3 Una búsqueda con dos coincidencias.