# PIV

The [National Institute of Standards and Technology](http://www.nist.gov/), U.S. Department of Commerce has defined a smart card application. Although not a “national ID card”, it is expected to be used widely in the U.S.federal government and its contractors. Cards with this application are commonly referred to as PIV cards.

NIST Spical Publication 800-73-3 (See below) and related documents define PIV. Part 2 of 800-73-3 defines theADPU commands accepted by the PIV application on the card. The standard does not define all the commands needed to administer a card, leaving this up to the card vendors and card administration software vendors.

The non-administrative commands are standardized, and so any vendor’s card with thePIVapplication\
should inter operate with any vendor’s client software.

**References**

* PIVOverview: [http://csrc.ncsl.nist.gov/piv-program/](http://csrc.ncsl.nist.gov/piv-program/)
* PIV, PIV Interoperable and PIV Compatible: [http://www.idmanagement.gov/documents/PIV\_IO\_NonFed\_Issuers\_May2009.pdf](http://www.idmanagement.gov/documents/PIV_IO_NonFed_Issuers_May2009.pdf). Recommendations on how PIV cards can used outside of the U.S. Goverenment.
* NISTSpecial Publications – 800-73-3: [http://csrc.nist.gov/publications/PubsSPs.html](http://csrc.nist.gov/publications/PubsSPs.html)
* PIVApproved Cards, Readers, Middleware etc: [http://fips201ep.cio.gov/apl.php](http://fips201ep.cio.gov/apl.php)

## Interface Summary

The Abstract PIV smartcard interface is summarized in the following snippet:

```javascript
interface AbstractPiv{
    allDataFilters():Array<string>;
    allCertFilters():Array<string>;
    allKeyRefs():Array<string>;
    allAlgoRefsForAuthentication(callback:(error:CoreExceptions.RestException, data:any) => void):void;
    allAlgoRefsForSigning(callback:(error:CoreExceptions.RestException, data:any) => void):void;
    printedInformation(callback:(error:CoreExceptions.RestException, data:any) => void):void;
    facialImage(callback:(error:CoreExceptions.RestException, data:any) => void):void;
    allCerts({ filters:string[], parseCerts: boolean }, callback:(error:CoreExceptions.RestException, data:any) => void):void;
    authenticationCertificate( { parseCerts: boolean }, callback:(error:CoreExceptions.RestException, data:any) => void):void;
    signingCertificate({ parseCerts: boolean }, callback:(error:CoreExceptions.RestException, data:any) => void):void;
    verifyPin(body:any,callback:(error:CoreExceptions.RestException, data:any) => void):void;
     signData(body:any,callback:(error:CoreExceptions.RestException, data:any) => void):void;
    authenticate(body:any,callback:(error:CoreExceptions.RestException, data:any) => void):void;
}
```

## Retrieve a connected card reader

In order to start with any use case, we need to select a card reader. The targeted reader will be passed as a parameter to the subsequent methods provided. This is part of the core Trust1Connector functionality. More information about core service functionality can be found on the following page: [Core Services](../../core/core-services).

For demonstration purpose we'll add a simple console output callback, which we'll use throughout the documentation.

```javascript
function callback(err,data) {
    if(err){console.log("Error:",JSON.stringify(err, null, '  '));}
    else {console.log(JSON.stringify(data, null, '  '));}
```

Just as an example, we instantiate a new gcl (local client) and ask for all connected smart card readers:

```javascript
GCLLib.GCLClient.initialize(config, function(err, gclClient) {
    // gclClient ready to use
    gclClient.core().readers(callback);
});
```

This will returns us all connected readers:

```javascript
{
  "data": [
    {
      "card": {
        "atr": "3B7D96000080318065B0831117E583009000",
        "description": [
          "Gemalto IDPrime PIV Card2.0 (eID)"
        ]
      },
      "id": "2e49386c82131cc1",
      "name": "Gemalto Ezio Shield",
      "pinpad": true
    }
  ],
  "success": true
}
```

In the example you'll notice that we are using a dual interface uTrust reader, and a card has been inserted.

The reader id '2e49386c82131cc1' can be used as parameter in the next steps in order to select a smartcard reader for the functionality we want to execute.

### Printed information <a href="#authentication-certificate" id="authentication-certificate"></a>

All FIPS 201 mandatory information printed on the card is duplicated on the chip in this data object.

The printed information data is protected by the PIN, so a pin must be provided when reading the printed information or it will be prompted on the reader in case of a pinpad reader. The following call can be done in order to retrieve the PIV printed information on the card:

#### With a pinpad

```javascript
var data = {};
gclClient.piv(reader_id).printedInformation(data, callback);
```

#### Without a pinpad

```javascript
var data = {
    "pin": "...."
};
gclClient.piv(reader_id).printedInformation(data, callback);
```

Example response:

```javascript
{
  "data": {      
      "name": "NAME",
      "employee_affiliation": "affliliation",
      "expiration_date": "2017DEC01",
      "agency_card_serial_number": "123456",
      "issuer_identification": "Issuer",
      "organization_affiliation_line_1": "line1",
      "organization_affiliation_line_2": "line2"
  },
  "success": true
}
```

### Facial Image

The facial image data object supports visual authentication by a guard, and may also be used for automated facial authentication in operator-attended PIV issuance, reissuance, and verification data reset processes. The facial image data is protected by the PIN, so a pin must be provided when reading the facial image or it will be prompted on the reader in case of a pinpad reader.

#### With a pinpad

```javascript
var data = {};
gclClient.piv(reader_id).facialImage(data, callback);
```

#### Without a pinpad

```javascript
var data = {
    "pin": "...."
};
gclClient.piv(reader_id).facialImage(data, callback);
```

Example response

```javascript
{
  "data": {
      "image": "..."
  },
  "success": true
}
```

## Certificates

Exposes all the certificates publicly available on the smart card. The following certificates can be found on the card:

* Signing certificate
* Authentication certificate

T1C-JS will return the **raw base64** certificate, optionally it can also return an **object** representing the certificate as parsed by [PKI.js](https://pkijs.org/). To enable parsing, `parseCerts` must be set to `true`.

### Certificate Chain

#### Authentication Certificate

Contains the 'authentication certificate' stored on the smart card. The 'authentication certificate' contains the public key corresponding to the private RSA authentication key. The 'authentication certificate' is needed for pin validation, authentication and singing.\
The service can be called:

```javascript
gclClient.piv(reader_id).authenticationCertificate({ parseCerts: true }, callback);
```

Response:

```javascript
{
  "data": {
    "base64": "MIIFjjCCA3agAwI...rTBDdrlEWVaLrY+M+xeIctrC0WnP7u4xg==",
    "parsed": { // parsed certificate object }
  },
  "success": true
}
```

#### Signing Certificate

Contains the 'non-repudiation certificate' stored on the smart card. The 'non-repudiation certificate' contains the public key corresponding the private RSA non-repudiation key.\
The service can be called:

```javascript
gclClient.piv(reader_id).signingCertificate({ parseCerts: true }, callback);
```

Response:

```javascript
{
  "data": {
    "base64": "MIIFjjCCA3agAwI...rTBDdrlEWVaLrY+M+xeIctrC0WnP7u4xg==",
    "parsed": { // parsed certificate object }
  },
  "success": true
}
```

## Data Filter

### Available Data Filters

#### Filter Certificates

All certificates on the smart card can be dumped at once, or using a filter. In order to read all certificates at once:

```javascript
var filter = [];
gclClient.piv(reader_id).allCerts({ filters: filter, parseCerts: true }, callback);
```

Response:

```javascript
{
  "data": {
    "printed_information": {
      "name": "NAME",
      "employee_affiliation": "affliliation",
      "expiration_date": "2017DEC01",
      "agency_card_serial_number": "123456",
      "issuer_identification": "Issuer",
      "organization_affiliation_line_1": "line1",
      "organization_affiliation_line_2": "line2"
    },
    "facial_image": {
      "image": "..."
    }
    "authentication_certificate": {
      "base64": "MIIFjjCCA3agAwI...rTBDdrlEWVaLrY+M+xeIctrC0WnP7u4xg==",
      "parsed": { // parsed certificate object }
    },
    "signing_certificate": {
      "base64": "MIIFjjCCA3agAwI...rTBDdrlEWVaLrY+M+xeIctrC0WnP7u4xg==",
      "parsed": { // parsed certificate object }
    }
  },
  "success": true
}
```

The filter can be used to ask a list of custom data containers. For example, we want to read only the 'root-certificate' and the 'authentication\_certificate':

```javascript
var filter = ['authentication-certificate','signing_certificate'];
gclClient.piv(reader_id).allCerts({ filters: filter, parseCerts: boolean }, callback);
```

Response:

```javascript
{
  "data": {
    "authentication_certificate": {
      "base64": "MIIFjjCCA3agAwI...rTBDdrlEWVaLrY+M+xeIctrC0WnP7u4xg==",
      "parsed": { // parsed certificate object }
    },
    "signing_certificate": {
      "base64": "MIIFjjCCA3agAwI...rTBDdrlEWVaLrY+M+xeIctrC0WnP7u4xg==",
      "parsed": { // parsed certificate object }
    },
  },
  "success": true
}
```

## Verify PIN

#### Without a pinpad

When the web or native application is responsible for showing the password input, the following request is used to verify a card holder PIN:

```javascript
var data = {
      "pin":"..."
}
gclClient.piv(reader_id).verifyPin(data, callback);
```

Response:

```javascript
{
  "success": true
}
```

#### With a pinpad

When the pin entry is done on the pin-pad, the following request is used to verify a card holder PIN:

```javascript
var data = {}
gclClient.piv(reader_id).verifyPin(data, callback);
```

Response:

```javascript
{
    "success": true
}
```

## Sign Data

Data can be signed using the PIV smartcard. To do so, the T1C-GCL facilitates in:

* Retrieving the certificate chain (root, intermediate and non-repudiation certificate)
* Perform a sign operation (private key stays on the smart card)
* Return the signed hash

To get the certificates necessary for signature validation in your back-end:

```javascript
gclClient.piv(reader_id).allCertificates({ parseCerts: false },callback);
```

Response:

```javascript
{
  "authentication_certificate": {
    "base64": "MIIFjjCCA3agAwI...rTBDdrlEWVaLrY+M+xeIctrC0WnP7u4xg=="
  },
  "signing_certificate": {
    "base64": "MIIFjjCCA3agAwI...rTBDdrlEWVaLrY+M+xeIctrC0WnP7u4xg=="
  },
}
```

Depending on the connected smart card reader. A sign can be executed in 2 modes:

* Using a connected card reader with 'pin-pad' capabilities (keypad and display available)
* Using a connected card reader without 'pin-pad' capabilities (no keypad nor display available)

Security consideration: In order to sign a hash, security considerations **prefer** using a 'pin-pad'.

### Signing algorithm references supported by the card

In order to verify which algorithm can be used for a 'sign' operation, you can call the following method:

```javascript
gclClient.piv(reader_id).allAlgoRefsForSigning(callback);
```

Example response:

```javascript
{
  "data": [
    "SHA1"
  ],
  "success": true
}
```

### Sign Hash

#### Without a pinpad

When the web or native application is responsible for showing the password input, the following request is used to sign a given hash:

```javascript
var data = {
      "pin":"...",
      "algorithm_reference":"sha1",
      "data":"I2e+u/sgy7fYgh+DWA0p2jzXQ7E="
}
gclClient.piv(reader_id).signData(data, callback);
```

Response is a base64 encoded signed hash:

```javascript
{
  "success": true,
  "data": "W7wqvWA8m9SBALZPxN0qUCZfB1O/WLaM/silenLzSXXmeR+0nzB7hXC/Lc/fMru82m/AAqCuGTYMPKcIpQG6MtZ/SGVpZUA/71jv3D9CatmGYGZc52cpcb7cqOVT7EmhrMtwo/jyUbi/Dy5c8G05owkbgx6QxnLEuTLkfoqsW9Q="
}
```

#### With a pinpad

When the pin entry is done on the pin-pad, the following request is used to sign a given hash:

```javascript
var data = {
    "algorithm_reference":"sha1",
    "data":"I2e+u/sgy7fYgh+DWA0p2jzXQ7E="
}
gclClient.piv(reader_id).signData(data, callback);
```

Response is a base64 encoded signed hash:

```javascript
{
    "success": true,
    "data": "W7wqvWA8m9SBALZPxN0qUCZfB1O/WLaM/silenLzSXXmeR+0nzB7hXC/Lc/fMru82m/AAqCuGTYMPKcIpQG6MtZ/SGVpZUA/71jv3D9CatmGYGZc52cpcb7cqOVT7EmhrMtwo/jyUbi/Dy5c8G05owkbgx6QxnLEuTLkfoqsW9Q="
}
```

The 'algorithm\_reference' property can contain the following values: sha1, sha256 and sha512.

The core services lists connected readers, and if they have pin-pad capability. You can find more information in the Core Service documentation on how to verify card reader capabilities.

### Calculate Hash

In order to calculate a hash from the data to sign, you need to know the algorithm you will use in order to sign.\
You might have noticed the `algorithm_reference` property provided in the `sign` request.\
The `algorithm_reference` can be one of the values: sha1, sha256 and sha512.\
For example, we want the following text to be signed using:

```
This is sample text to demonstrate siging with PIV smartcard
```

You can use the following online tool to calculate the SHA1: [http://www.sha1-online.com](http://www.sha1-online.com)

Hexadecimal result:

```
OTY4ODM2ODg3ODg3YWViYzdlZDBiMDgwMjQxZGQ5N2M4N2ZlMWRhZQ==
```

Notice that the length of the SHA1 is always the same.\
Now we need to convert the hexadecimal string to a base64-encoded string, another online tool can be used for this example: [hex to base64 converter](http://tomeko.net/online_tools/hex_to_base64.php?lang=en)

Base64-encoded result:

```
OTY4ODM2ODg3ODg3YWViYzdlZDBiMDgwMjQxZGQ5N2M4N2ZlMWRhZQ==
```

Now we can sign the data:

```javascript
var data = {
      "pin":"...",
      "algorithm_reference":"sha1",
      "data":"OTY4ODM2ODg3ODg3YWViYzdlZDBiMDgwMjQxZGQ5N2M4N2ZlMWRhZQ=="
}
gclClient.piv(reader_id).signData(data, callback);
```

Result:

```javascript
{
  "data": "C7SG5eix1+lzMcZXgL0bCL+rLxKhd8ngrSj6mvlgooWH7CloEU13Rj8QiQHdhHnZgAi4Q0fCMIqAc4dn9uW9OP+MRitimRpYZcaDsGrUehPi/JpOD1e+ko7xKZ67ijUU4KTmG4HXc114oJ7xxx3CGL7TNFfvuEphLbbZa+9IZSSnYDOOENJqhggqqu7paSbLJrxC2zaeMxODKb5WSexHnZH6NnLPl2OmvPTYtxiTUMrLbFRsDRAziF6/VQkgM8/xOm+1/9Expv5DSLRY8RQ+wha6/nMlJjx50JszYIj2aBQKp4AOxPVdPewVGEWF4NF9ffrPLrOA2v2d7t5M4q7yxA==",
  "success": true
}
```

## Authentication

The T1C-GCL is able to authenticate a card holder based on a challenge. The challenge can be:

* provided by an external service
*   provided by the smart card &#x20;

    An authentication can be interpreted as a signature use case, the challenge is signed data, that can be validated in a back-end process.

### Authentication algorithm references supported by the card

In order to verify which algorithm can be used for a 'sign' operation, you can call the following method:

```javascript
gclClient.piv(reader_id).allAlgoRefsForAuthentication(callback);
```

Example response:

```javascript
{
  "data": [
    "SHA1",
    "SHA256",
    "SHA512"
  ],
  "success": true
}
```

### External Challenge

#### Without a pinpad

An external challenge is provided in the data property of the following example:

```javascript
var data = {
  "pin": "...",
  "algorithm_reference": "sha1",
  "data":"I2e+u/sgy7fYgh+DWA0p2jzXQ7E="
}
gclClient.piv(reader_id).authenticate(data, callback);
```

Response:

```javascript
{
  "success": true,
  "data": "W7wqvWA8m9SBALZPxN0qUCZfB1O/WLaM/silenLzSXXmeR+0nzB7hXC/Lc/fMru82m/AAqCuGTYMPKcIpQG6MtZ/SGVpZUA/71jv3D9CatmGYGZc52cpcb7cqOVT7EmhrMtwo/jyUbi/Dy5c8G05owkbgx6QxnLEuTLkfoqsW9Q="
}
```

#### Without a pinpad

An external challenge is provided in the data property of the following example:

```javascript
var data = {
    "algorithm_reference": "sha1",
    "data":"I2e+u/sgy7fYgh+DWA0p2jzXQ7E="
}
gclClient.piv(reader_id).authenticate(data, callback);
```

Response:

```javascript
{
    "success": true,
    "data": "W7wqvWA8m9SBALZPxN0qUCZfB1O/WLaM/silenLzSXXmeR+0nzB7hXC/Lc/fMru82m/AAqCuGTYMPKcIpQG6MtZ/SGVpZUA/71jv3D9CatmGYGZc52cpcb7cqOVT7EmhrMtwo/jyUbi/Dy5c8G05owkbgx6QxnLEuTLkfoqsW9Q="
}
```

The 'algorithm\_reference' property can contain the following values: sha1, sha256 and sha512.

### Generated Challenge

A server generated challenge can be provided to the JavaScript library.\
In order to do so, an additional contract must be provided with the 'OCV API' (Open Certificate Validation API).

```
The calculated digest of the hash is prefixed with:
DigestInfo ::= SEQUENCE {
      digestAlgorithm AlgorithmIdentifier,
      digest OCTET STRING
  }
Make sure this has been taken into consideration in order to validate the signature in a backend process.
```

## Error Handling

### Error Object

The functions specified are asynchronous and always need a callback function.\
The callback function will reply with a data object in case of success, or with an error object in case of an error. An example callback:

```javascript
function callback(err,data) {
    if(err){
        console.log("Error:",JSON.stringify(err, null, '  '));
    }
    else {
        console.log(JSON.stringify(data, null, '  '));
    }
}
```

The error object returned:

```javascript
{
  success: false,
  description: "some error description",
  code: "some error code"
}
```

For the error codes and description, see [Status codes](../../core/status-codes).
