Section 49. Crypto Engine and Random Number Generator (RNG)ww1.microchip.com/downloads/en/DeviceDoc/60001246A.pdf · Section 49. Crypto Engine and Random Number Generator (RNG) Crypto
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Section 49. Crypto Engine and Random Number Generator (RNG)
Cryp
to E
ng
ine
an
d
Ran
do
m N
um
ber
Ge
ne
rator (R
NG
)
49
HIGHLIGHTS
This section of the manual contains the following major topics:
The Crypto Engine is intended to accelerate applications that need cryptographic functions. Byexecuting these functions in the hardware module, software overhead is reduced, and actionssuch as encryption, decryption, and authentication can execute much more quickly.
The Crypto Engine uses a descriptor-based DMA for efficient programming of the security asso-ciation data and packet pointers (allowing scatter/gather data fetching). An intelligent statemachine schedules the Crypto Engine based on the protocol selection and packet boundaries.The hardware engines can perform the encryption and authentication in sequence or in parallel.
Key features of the Crypto Engine include: priority
• Bulk ciphers and hash engines• Integrated DMA to off-load processing:
- Buffer descriptor-based- Security Association per Buffer Descriptor
• Some functions can execute in parallel
Bulk ciphers that are handled by the Crypto Engine include:
• AES:- 128-bit, 192-bit, and 256-bit key sizes- CBC, ECB, CTR, CFB, and OFB modes
• DES/TDES:- CBC, ECB, CFB, and OFB modes
Authentication engines that are available through the Crypto Engine include:
Note: This family reference manual section is meant to serve as a complement to devicedata sheets. Depending on the device variant, this manual section may not apply toall PIC32 devices.
Please consult the note at the beginning of the “Crypto Engine and RandomNumber Generator (RNG)” chapter in the current device data sheet to checkwhether this document supports the device you are using.
Device data sheets and family reference manual sections are available fordownload from the Microchip Worldwide Web site at: http://www.microchip.com
Section 49. Crypto Engine and Random Number Generator (RNG)C
ryp
to E
ng
ine
an
d
Ra
nd
om
Nu
mb
er
Ge
ne
rato
r (RN
G)
49
49.1.2 Random Number Generator (RNG) Features
The Random Number Generator (RNG) core implements a thermal noise-based, True RandomNumber Generator (TRNG) and a cryptographically secure Pseudo-Random NumberGenerator (PRNG).
The TRNG uses multiple ring oscillators and the inherent thermal noise of integrated circuits togenerate true random numbers that can initialize the PRNG.
The PRNG is a flexible LSFR, which is capable of manifesting a maximal length LFSR of up to64-bits.
The following are some of the key features of the RNG:
• TRNG:
- Up to 25 Mbps of random bits
- Multi-Ring Oscillator-based design
- Built in Bias Corrector
• PRNG:
- LSFR-based
- Up to 64-bit polynomial length
- Programmable polynomial
- TRNG can be seed value
Figure 49-2: Random Number Generator Block Diagram
This register indicates what triggered an interrupt from the Crypto Engine core. Possiblesources include DMA, an empty TX Buffer Descriptor, or a DMA packet completion.
This register controls which interrupts are enabled/disabled from the Crypto Engine core.
• CEPOLLCON: Crypto Engine Poll Control Register
This register controls how long the Buffer Descriptor Processor will wait before refetching adescriptor control word if the previous descriptor fetched was disabled.
• CEHDLEN: Crypto Engine Header Length Register
This register controls how much data in a packet should be unchanged before filling the data.
• CETRLLEN: Crypto Engine Trailer Length Register
This register controls how much data should be unchanged at the end of a packet.
• CEDTXSTAT: Crypto Engine DTX Debug Status Register
This read -only register indicates the status of the outgoing FIFO in the Crypto Engine.
• CEDRXSTAT: Crypto Engine DRX Debug Status Register
This read-only register indicates the status of the incoming FIFO in the Crypto Engine.
• RNGVER: Random Number Generator ID, Version, and Revision Register
This register read-only register contains version information for the RNG core.
• RNGCON: Random Number Generator Control Register
This register controls the RNG, enabling and disabling the TRNG and RNG, transferring theseed value from the TRNG to the PRNG, and enabling continuous pseudo-random numbergeneration.
• RNGPOLY1: Random Number Generator Polynomial Register 1
This register controls the Least Significant Byte 32-bits of the polynomial, which generates thepseudo-random bit.
• RNGPOLY2: Random Number Generator Polynomial Register 2
This register controls the Most Significant Byte 32-bits of the polynomial which generates thepseudo-random bit.
Section 49. Crypto Engine and Random Number Generator (RNG)C
ryp
to E
ng
ine
an
d
Ra
nd
om
Nu
mb
er
Ge
ne
rato
r (RN
G)
49
• RNGNUMGEN1: Random Number Generator Pseudo-Random Number Generator Register 1
This register contains the Least Significant Byte 32-bits of the current random number in thePRNG. It may be written to set an initial seed value for the PRNG.
• RNGNUMGEN2: Random Number Generator Pseudo-Random Number Generator Register 2
This register contains the Most Significant Byte 32-bits of the current random number in thePRNG. It may be written to set an initial seed value for the PRNG.
• RNGSEED1: True Random Number Generator Seed Register 1
This read-only register contains the Least Significant Byte 32-bits of the TRNG.
• RNGSEED2: True Random Number Generator Seed Register 2
This read-only register contains the Most Significant Byte 32-bits of the TRNG.
• RNGRCNT: True Random Number Generator Count Register
This read-only register indicates the number of valid bits in the TRNG registers,RNGSEEDx. To ensure randomness, developers should not use the RNGSEEDx registersuntil this register reaches the appropriate value for the number of bits desired.
Section 49. Crypto Engine and Random Number Generator (RNG)C
ryp
to E
ng
ine
an
d
Ra
nd
om
Nu
mb
er
Ge
ne
rato
r (RN
G)
49
Register 49-2: CECON: Crypto Engine Control Register
Bit Range
Bit31/23/15/7
Bit30/22/14/6
Bit29/21/13/5
Bit28/20/12/4
Bit27/19/11/3
Bit26/18/10/2
Bit25/17/9/1
Bit24/16/8/0
31:24U-0 U-0 U-0 U-0 U-0 U-0 U-0 U-0
— — — — — — — —
23:16U-0 U-0 U-0 U-0 U-0 U-0 U-0 U-0
— — — — — — — —
15:8U-0 U-0 U-0 U-0 U-0 U-0 U-0 U-0
— — — — — — — —
7:0R/W-0 R/W-0 R/W-0 U-0 U-0 R/W-0 R/W-0 R/W-0
SWAPOEN(1) SWRST SWAPEN — — BDPCHST BDPPLEN DMAEN
Legend:
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 31-8 Unimplemented: Read as ‘0’
bit 7 SWAPOEN: Output Data Swap Enable bit(1)
1 = Output data is byte swapped when read by dedicated DMA0 = Output data is not byte swapped when read by dedicated DMA
bit 6 SWRST: Software Reset bit
1 = Initiate a software Reset of the Crypto Engine0 = Normal operation
bit 5 SWAPEN: Input Data Swap Enable bit
1 = Input data is byte swapped when read by dedicated DMA0 = Input data is not byte swapped when read by dedicated DMA
bit 4-3 Unimplemented: Read as ‘0’
bit 2 BDPCHST: Buffer Descriptor Processor Fetch Enable bit
This bit should be enabled only after all DMA descriptor programming is completed.
1 = Buffer Descriptor Processor descriptor fetch is enabled0 = Buffer Descriptor Processor descriptor fetch is disabled
bit 1 BDPPLEN: Buffer Descriptor Processor Poll Enable bit
This bit should be enabled only after all DMA descriptor programming is completed.
1 = Poll for descriptor until valid bit is set0 = Do not poll
bit 0 DMAEN: DMA Enable bit
1 = Crypto Engine DMA is enabled0 = Crypto Engine DMA is disabled
Note 1: This bit is not available on all devices. Refer to the “Crypto Engine and RNG” chapter in the specific device data sheet to determine availability.
bit 25-24 ERRPHASE<1:0>: Internal Error Phase of DMA Status bits11 = Destination data10 = Source data01 = Security Association access00 = Buffer Descriptor access
bit 23-22 Unimplemented: Read as ‘0’
bit 21-18 BDSTATE<3:0>: Buffer Descriptor Processor State Status bitsThese bits contain a number, which indicates the current state of the Buffer Descriptor Processor:1111 = Reserved•••
0111 = Reserved 0110 = Security Association fetch0101 = Fetch Buffer Descriptor Processor is disabled0100 = Descriptor is done0011 = Data phase0010 = Buffer Descriptor Processor is loading0001 = Descriptor fetch request is pending0000 = Buffer Descriptor Processor is idle
bit 17 START: DMA Start Status bit1 = DMA start has occurred0 = DMA start has not occurred
bit 16 ACTIVE: Buffer Descriptor Processor Status bit1 = Buffer Descriptor Processor is active0 = Buffer Descriptor Processor is idle
bit 15-0 BDCTRL<15:0>: Descriptor Control Word Status bitsThese bits contain the current descriptor control word.
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 31-4 Unimplemented: Read as ‘0’
bit 3 AREIF: Access Response Error Interrupt bit(1)
1 = The Crypto Engine attempted to access an invalid memory location0 = No error has occurred
bit 2 PKTIF: DMA Packet Completion Interrupt Status bit(1)
1 = DMA packet was completed0 = DMA packet was not completed
bit 1 CBDIF: Buffer Descriptor Transmit Status bit(1)
1 = Last Buffer Descriptor transmit was processed0 = Last Buffer Descriptor transmit has not been processed
bit 0 PENDIF: Crypto Engine Interrupt Pending Status bit(1)
1 = Crypto Engine interrupt is pending (this value is the result of an OR of all interrupts in the Crypto Engine)0 = Crypto Engine interrupt is not pending
Note 1: Write a '1' to this bit to clear the interrupt.
R = Readable bit W = Writable bit U = Unimplemented bit, read as ‘0’
-n = Value at POR ‘1’ = Bit is set ‘0’ = Bit is cleared x = Bit is unknown
bit 31-16 Unimplemented: Read as ‘0’
bit 15-0 BDPPLCON<15:0>: Buffer Descriptor Processor Poll Control bits
These bits determine the number of cycles that the DMA transmit Buffer Descriptor Processor would waitbefore refetching the descriptor control word if the previous descriptor fetched was disabled.
Host software creates a linked list of Buffer Descriptors and the hardware updates them.Table 49-3 provides a list of the Crypto Engine Buffer Descriptors, followed by formatdescriptions (see Figure 49-3 through Figure 49-10).
Section 49. Crypto Engine and Random Number Generator (RNG)C
ryp
to E
ng
ine
an
d
Ra
nd
om
Nu
mb
er
Ge
ne
rato
r (RN
G)
49
Figure 49-3: Format of BD_CTRL
Figure 49-4: Format of BD_SADDR
Bit Range
Bit31/23/15/7
Bit30/22/14/6
Bit29/21/13/5
Bit28/20/12/4
Bit27/19/11/3
Bit26/18/10/2
Bit25/17/9/1
Bit24/16/8/0
31-24 DESC_EN — CRY_MODE<2:0> — — —
23-16 —SA_
FETCH_EN— — LAST_BD LIFM
PKT_INT_EN
CBD_INT_EN
15-8 BD_BUFLEN<15:8>
7-0 BD_BUFLEN<7:0>
bit 31 DESC_EN: Descriptor Enable1 = The descriptor is owned by hardware. After processing the BD, hardware resets this bit to ‘0’.0 = The descriptor is owned by software
bit 22 SA_FETCH_EN: Fetch Security Association From External Memory1 = Fetch SA from the SA pointer. This bit needs to be set to ‘1’ for every new packet.0 = User current fetched SA or the internal SA
bit 21-20 Unimplemented: Must be written as ‘0’
bit 19 LAST_BD: Last Buffer DescriptorsAfter the last BD, the BD_PTR goes to the base address in the CSR.
bit 18 LIFM: Last In FrameIn case of Receive Packets (from H/W-> Host), this field is filled by the Hardware to indicate whether the packet goes across multiple buffer descriptors. In case of transmit packets (from Host -> H/W), this field indicates whether this BD is the last in the frame.
bit 17 PKT_INT_EN: Packet Interrupt EnableGenerate an interrupt after processing the current buffer descriptor, if it is the end of the packet.
bit 16 CBD_INT_EN: CBD Interrupt EnableGenerate an interrupt after processing the current buffer descriptor.
bit 15-0 BD_BUFLEN<15:0>: Buffer Descriptor LengthThis field contains the length of the buffer and is updated with the actual length filled by the receiver.
Bit Range
Bit31/23/15/7
Bit30/22/14/6
Bit29/21/13/5
Bit28/20/12/4
Bit27/19/11/3
Bit26/18/10/2
Bit25/17/9/1
Bit24/16/8/0
31-24 BD_SAADDR<31:24>
23-16 BD_SAADDR<23:16>
15-8 BD_SAADDR<15:8>
7-0 BD_SAADDR<7:0>
bit 31-0 BD_SAADDR: Security Association IP Session AddressThe sessions’ Security Association pointer has the keys and IV values.
bit 31-0 BD_SCRADDR: Buffer Source AddressThe source address of the buffer that needs to be passed through the PE-CRDMA for encryption or authentication.
Bit Range
Bit31/23/15/7
Bit30/22/14/6
Bit29/21/13/5
Bit28/20/12/4
Bit27/19/11/3
Bit26/18/10/2
Bit25/17/9/1
Bit24/16/8/0
31-24 BD_DSTADDR<31:24>
23-16 BD_DSTADDR<23:16>
15-8 BD_DSTADDR<15:8>
7-0 BD_DSTADDR<7:0>
bit 31-0 BD_DSTADDR: Buffer Destination AddressThe destination address of the buffer that needs to be passed through the PE-CRDMA for encryption or authentication.
Bit Range
Bit31/23/15/7
Bit30/22/14/6
Bit29/21/13/5
Bit28/20/12/4
Bit27/19/11/3
Bit26/18/10/2
Bit25/17/9/1
Bit24/16/8/0
31-24 BD_NXTADDR<31:24>
23-16 BD_NXTADDR<23:16>
15-8 BD_NXTADDR<15:8>
7-0 BD_NXTADDR<7:0>
bit 31-0 BD_NXTADDR: Next Buffer Descriptor Pointer Address Has Next Buffer DescriptorThe next buffer can be a next segment of the previous buffer or a new packet.
Bit Range
Bit31/23/15/7
Bit30/22/14/6
Bit29/21/13/5
Bit28/20/12/4
Bit27/19/11/3
Bit26/18/10/2
Bit25/17/9/1
Bit24/16/8/0
31-24 BD_UPDADDR<31:24>
23-16 BD_UPDADDR<23:16>
15-8 BD_UPDADDR<15:8>
7-0 BD_UPDADDR<7:0>
bit 31-0 BD_UPDADDR: UPD Address LocationThe update address has the location where the CRDMA results are posted. The updated results are the ICV values, key output values as needed.
Section 49. Crypto Engine and Random Number Generator (RNG)C
ryp
to E
ng
ine
an
d
Ra
nd
om
Nu
mb
er
Ge
ne
rato
r (RN
G)
49
Figure 49-9: Format of BD_MSG_LEN
Figure 49-10: Format of BD_ENC_OFF
Example 49-1: Buffer Descriptor C Structures
Bit Range
Bit31/23/15/7
Bit30/22/14/6
Bit29/21/13/5
Bit28/20/12/4
Bit27/19/11/3
Bit26/18/10/2
Bit25/17/9/1
Bit24/16/8/0
31-24 MSG_LENGTH<31:24>
23-16 MSG_LENGTH<23:16>
15-8 MSG_LENGTH<15:8>
7-0 MSG_LENGTH<7:0>
bit 31-0 MSG_LENGTH: Total Message LengthTotal message length for the hash and HMAC algorithms in bytes. Total number of Crypto bytes in case of GCM algorithm (LEN-C).
Bit Range
Bit31/23/15/7
Bit30/22/14/6
Bit29/21/13/5
Bit28/20/12/4
Bit27/19/11/3
Bit26/18/10/2
Bit25/17/9/1
Bit24/16/8/0
31-24 ENCR_OFFSET<31:24>
23-16 ENCR_OFFSET<23:16>
15-8 ENCR_OFFSET<15:8>
7-0 ENCR_OFFSET<7:0>
bit 31-0 ENCR_OFFSET: Encryption OffsetEncryption offset for the multi-task test cases (both encryption and authentication). The number of AAD bytes in the case of GCM algorithm (LEN-A).
typedef struct bdCtrl { unsigned int BUFLEN : 16; unsigned int CBD_INT_EN : 1; unsigned int PKT_INT_EN : 1; unsigned int LIFM : 1; unsigned int LAST_BD: 1; unsigned int : 2; unsigned int SA_FETCH_EN : 1; unsigned int : 4; unsigned int CRY_MODE: 3; unsigned int : 1; unsigned int DESC_EN : 1; } bdCtrl;
typedef struct bufferDescriptor { bdCtrl BD_CTRL; unsigned int SA_ADDR; unsigned int SRCADDR; unsigned int DSTADDR; unsigned int NXTPTR; unsigned int UPDPTR; unsigned int MSGLEN; unsigned int ENCOFF; } bufferDescriptor;
Table 49-4 shows the Security Association structure.
The Crypto Engine uses the Security Association to determine the settings for processing aBuffer Descriptor Processor. The Security Association contains:
• Which algorithm to use
• Whether to use engines in parallel (for both authentication and encryption/decryption)
• The size of the key
• Authentication key
• Encryption/decryption key
• Authentication Initialization Vector (IV)
• Encryption IV
Table 49-4: Crypto Engine Security Association Structure
Section 49. Crypto Engine and Random Number Generator (RNG)C
ryp
to E
ng
ine
an
d
Ra
nd
om
Nu
mb
er
Ge
ne
rato
r (RN
G)
49
Figure 49-11: Format of SA_CTRL
Bit Range
Bit31/23/15/7
Bit30/22/14/6
Bit29/21/13/5
Bit28/20/12/4
Bit27/19/11/3
Bit26/18/10/2
Bit25/17/9/1
Bit24/16/8/0
31-24 — — VERIFY — NO_RX OR_EN ICVONLY IRFLAG
23-16 LNC LOADIV FB FLAGS — — — ALGO<6>
15-8 ALGO<5:0> ENC KEYSIZE<1>
7-0 KEYSIZE<0> MULTITASK<2:0> CRYPTOALGO<3:0>
bit 31-30 Reserved: Do not use
bit 29 VERIFY: NIST Procedure Verification Setting1 = NIST procedures are to be used0 = Do not use NIST procedures
bit 28 Reserved: Do not use
bit 27 NO_RX: Receive DMA Control Setting1 = Only calculate ICV for authentication calculations0 = Normal processing
bit 26 OR_EN: OR Register Bits Enable Setting1 = OR the register bits with the internal value of the CSR register0 = Normal processing
bit 25 ICVONLY: Incomplete Check Value Only FlagThis affects the SHA-1 algorithm only. It has no effect on the AES algorithm.1 = Only three words of the HMAC result are available0 = All results from the HMAC result are available
bit 24 IRFLAG: Immediate Result of Hash SettingThis bit is set when the immediate result for hashing is requested.1 = Save the immediate result for hashing0 = Do not save the immediate result
bit 23 LNC: Load New Keys Setting1 = Load a new set of keys for encryption and authentication0 = Do not load new keys
bit 22 LOADIV: Load IV Setting1 = Load the IV from this Security Association0 = Use the next IV
bit 21 FB: First Block SettingThis bit indicates that this is the first block of data to feed the IV value.1 = Indicates this is the first block of data0 = Indicates this is not the first block of data
bit 20 FLAGS: Incoming/Outgoing Flow Setting1 = Security Association is associated with an outgoing flow0 = Security Association is associated with an incoming flow
bit 19-17 Reserved: Do not use
bit 16-10 ALGO<6:0>: Type of Algorithm to Use1xxxxxx = HMAC 1x1xxxxx = SHA-256xx1xxxx = SHA1xxx1xxx = MD5xxxx1xx = AESxxxxx1x = TDESxxxxxx1 = DES
bit 9 ENC: Type of Encryption Setting1 = Encryption0 = Decryption
bit 8-7 KEYSIZE<1:0>: Size of Keys in SA_AUTHKEYx or SA_ENCKEYx(1)
11 = Reserved; do not use10 = 256 bits01 = 192 bits00 = 128 bits
bit 6-4 MULTITASK<2:0>: How to Combine Parallel Operations in the Crypto Engine111 = Parallel pass (decrypt and authenticate incoming data in parallel)101 = Pipe pass (encrypt the incoming data, and then perform authentication on the encrypted data)011 = Reserved010 = Reserved001 = Reserved000 = Encryption or authentication or decryption (no pass)
Note 1: This setting does not alter the size of SA_AUTHKEYx or SA_ENCKEYx in the Security Association, only the number of bits of SA_AUTHKEYx and SA_ENCKEYx that are used.
typedef struct saCtrl { unsigned int CRYPTOALGO : 4; unsigned int MULTITASK : 3; unsigned int KEYSIZE : 2; unsigned int ENCTYPE : 1; unsigned int ALGO : 7; unsigned int : 3; unsigned int FLAGS : 1; unsigned int FB : 1; unsigned int LOADIV : 1; unsigned int LNC : 1; unsigned int IRFLAG : 1; unsigned int ICVONLY : 1; unsigned int OR_EN : 1; unsigned int NO_RX : 1; unsigned int : 1; unsigned int VERIFY : 1; unsigned int : 2; } saCtrl;
typedef struct securityAssociation { saCtrl SA_CTRL; unsigned int SA_AUTHKEY[8]; unsigned int SA_ENCKEY[8]; unsigned int SA_AUTHIV[8]; unsigned int SA_ENCIV[4]; } securityAssociation;
Section 49. Crypto Engine and Random Number Generator (RNG)C
ryp
to E
ng
ine
an
d
Ra
nd
om
Nu
mb
er
Ge
ne
rato
r (RN
G)
49
49.5 CRYPTO ENGINE OPERATION
49.5.1 Cryptographic Security Engines
To reduce the processing requirements of the PIC32 family, the Crypto Engine includes fourdifferent cryptographic security engines. These security engines perform the types ofencryptions, decryptions, and mathematical computations that are most commonly used for avariety of security applications. They accelerate the computation of public or private key pairnegotiations, message hash authentication, and bulk data encryption/decryption. These enginesmay be used in parallel, or daisy-chained to provide additional security.
The four engines implemented are:
• Triple Data Encryption Standard (TDES)
• Advanced Encryption Standard (AES)
• Secure Hash Algorithm (SHA-1 and SHA-256)
• Message Digest 5 (MD5)
49.5.1.1 TRIPLE DATA ENCRYPTION STANDARD (TDES)
The Data Encryption Standard (DES) is an encryption algorithm developed in the early 1970s. Itis a block cipher, encrypting data in 64-bit blocks. For each 64-bit block sent through the engine,a 64-bit block is returned.
The key length used by DES is 56-bits long. It is usually represented as a 64-bit number;however, per the DES standard, every eighth bit of the key is used for parity checking of the key,and then discarded. That is, positions 8, 16, 24, 32, 40, 48, 56, and 64 are removed from the64-bit key, leaving only the 56-bit key.
Padding must be added to ensure the size of the incoming data to be processed is a multiple of8 bytes. This padding is exclusive of any header or trailer data that is skipped over and shouldconsist of zeros.
Triple DES (TDES) uses the algorithm three times on the same block of data, rather than onlyonce, and can use key lengths of 56, 112, or 168 bits. Like DES, TDES is a symmetric algorithm,meaning the same algorithm and key are used for both encryption and decryption of data.
49.5.1.2 ADVANCED ENCRYPTION STANDARD (AES)
The Advanced Encryption Standard (AES) engine implements the Advanced EncryptionStandard (originally known as Rijndael), as described in the NIST Federal InformationProcessing Standard Publication 197. Like DES, it is a block cipher, and the same key is used toboth encrypt and decrypt data. It operates on 128-bit blocks regardless of the key size.
The key length used by AES can be 128, 192, or 256 bits, and determines the number oftransformation rounds used to convert the input to the output. The key length also determinesthe effective bit rate for algorithm execution.
Padding must be added to ensure the size of the incoming data to be processed is a multiple of16 bytes (128 bits). This padding is exclusive of any header/trailer data that is skipped over andshould consist of zeros.
49.5.1.3 SECURE HASH ALGORITHM (SHA-1 AND SHA-256)
Secure Hash Algorithm (SHA) is a cryptographic hash function designed by the United StatesNational Security Agency (NSA). It is a one-way message digest function, taking an unlimitedamount of input data, and producing a digest of 160 bits (for SHA-1) or 256 bits (for SHA-256).
Both versions operate on 512-bit blocks. Padding is required to make the input data a multiple of64 bytes. The most significant bit of the padding must be a ‘1’, followed by as many zeros asneeded to make the length 64 bits short of a multiple of 512 bits (64 bytes). The final 64 bits area binary representation of the length of the message before padding. This ensures that differentmessages will not look the same after padding.
Message Digest 5 (MD5) is similar to SHA, in that it is a cryptographic hash function. It wasdesigned by Ron Rivest in 1991 to replace an earlier hash function, MD4. MD5 takes an unlimitedamount of input data, and produces a 128-bit hash value.
MD5 operates on 512-bit blocks. Padding is required to make the input data a multiple of 64bytes. The most significant bit of the padding must be a 1, followed by as many zeros as neededto make the length 64 bits short of a multiple of 512 bits (64 bytes). The final 64 bits are a binaryrepresentation of the length of the message before padding. This ensures that differentmessages will not look the same after padding.
49.5.1.5 MODES OF OPERATION
The TDES and AES block cipher engines offer up to six modes of operation, which enables therepeated and secure use of the cipher under a single key. The six modes are:
The modes in use are decided by the Security Association structure when the data is processed.
49.5.2 Running the Crypto Engine
The Crypto Engine is configured via a set of Buffer Descriptors, which instruct the engine, for aparticular block of data, how to process it and which Security Association to use with it. OneSecurity Association can be associated with multiple Buffer Descriptors, thus saving memory.
Figure 49-16 illustrates the relationship between one Security Association, multiple BufferDescriptors, and the data to be processed.
Figure 49-16: Relationship of Security Association, Buffer Descriptor and Pending Processed Data
Section 49. Crypto Engine and Random Number Generator (RNG)C
ryp
to E
ng
ine
an
d
Ra
nd
om
Nu
mb
er
Ge
ne
rato
r (RN
G)
49
49.5.2.1 DATA BLOCK HEADER AND TRAILER
For some applications, each data block may have header and/or trailer information that shouldnot be processed by the Crypto Engine, but should be passed through without alteration. TheCEHDLEN and CETRLLEN registers determine the length of the header and trailer. Setting eachregister reserves up to 255 bytes.
49.5.2.2 CREATING THE SECURITY ASSOCIATION
The Security Association describes to the Crypto Engine how to run the engine for the givenblock, and what security keys and Initialization Vectors (IV) to use. At a minimum, the SecurityAssociation must contain the following information:
• The algorithm to use (HMAC, SHA256, SHA1, MD5, AES, TDES, DES)
• Whether to load the Initialization Vector (IV)
• The direction of flow (incoming or outgoing)
• Encryption or decryption
• Key size
• Multi-task options
• Mode of operation (only applies to certain algorithms)
An example for creating and setting up a Security Association is shown in Example 49-3.
Example 49-3: Setting Up a Security Association securityAssociation enc_sa __attribute__((aligned (8))); securityAssociation dec_sa __attribute__((aligned (8)));
49.5.2.3 SECURITY ASSOCIATION ENCRYPTION KEY AND IV DATA ALIGNMENT
When copying the key and initialization vectors into the security association, the position of eachvector is important to generate the correct results.
Figure 49-17 through Figure 49-21 illustrate how the alignment of each is to be affected for all ofthe available hardware encryption algorithms. Note that all of the Keys and IVs in the SecurityAssociation must be in Big-Endian order.
Figure 49-17: Key and IV Layout in Security Association for AES (128-bit Key)
Figure 49-18: Key and IV Layout in Security Association for AES (192-bit Key)
Figure 49-19: Key and IV Layout in Security Association for AES (256-bit Key)
Section 49. Crypto Engine and Random Number Generator (RNG)C
ryp
to E
ng
ine
an
d
Ra
nd
om
Nu
mb
er
Ge
ne
rato
r (RN
G)
49
Figure 49-20: Key and IV Layout in Security Association for Triple-DES
Figure 49-21: Key and IV Layout in Security Association for DES
49.5.2.4 CREATING THE BUFFER DESCRIPTOR
For each block of data that needs to be processed, the Buffer Descriptor tells the Crypto Enginehow to process the data. At a minimum, the Buffer Descriptor must include the followinginformation:
• The address of the Security Association (BD_SA_ADDR)
• The address of the source data to process (BD_SRCADDR)
• The address of the destination data after processing (BD_DSTADDR)
• The address of the next Buffer Descriptor (BD_NXTPTR)
• The address of the place to store updates for hash algorithms (BD_UPDADDR)
• The total message length in bytes (MSG_LENGTH)
An example of creating and setting up a series of Buffer Descriptors is shown in Example 49-4.
Section 49. Crypto Engine and Random Number Generator (RNG)C
ryp
to E
ng
ine
an
d
Ra
nd
om
Nu
mb
er
Ge
ne
rato
r (RN
G)
49
49.5.3 Crypto Engine Operation Guidelines
The following guidelines are used to ensure proper configuration and operation of the CryptoEngine.
• Data Alignment
- Security Association structures shall be aligned on a 8-byte boundary. This can be done with an alignment attribute for the variable, see Example 49-3.
- Buffer Descriptor structures shall be aligned on a 8-byte boundary. This can be done with an alignment attribute for the variable, see Example 49-4.
- The source and destination addresses used in the Buffer Descriptor shall be aligned on a 32-bit boundary.
• Data Lengths
- The Buffer Length field of each Buffer Descriptor shall be an integral multiple of the word size of the Crypto algorithm used. Data blocks should be expanded to meet the required size and filled with zeros to avoid corruption. The word sizes for each algorithm are listed in Table 49-5.
Table 49-5: Encryption Algorithm Word Sizes
- The total length of the data across multiple buffer descriptors shall be an integral multi-ple of the word size of the Crypto algorithm used. The word sizes for each algorithm are listed in Table 49-5.
- For the hashing algorithms (MD5, SHA1, SHA256) the packet length shall be a minimum of 64 bytes
- If the input data length does not match the above guidelines, it should be zero-padded to make it the correct length
• Algorithms, Initialization Vectors (IV)
- IV size is restricted to 96 bits for AES GCM
- The fourth word (LSB 32-bit) of Encryption IV for AES GCM shall be 1
- When encryption is used in parallel with authentication, HMAC shall be used
- HMAC shall be used in combination with one of the authentication engines (MD5/SHA1/SHA256)
Note: To avoid cache coherency problems on devices with L1 cache, all BufferDescriptors and Security Associations must be accessed from KSEG1 or KSEG3(uncached) segments only.
The PIC32 device can generate interrupts reflecting the events that occur during the CryptoEngine's operation. Each of the Crypto Engine interrupt events has a corresponding interruptenable bit in the CEINTEN register, which must be set for an interrupt to be generated. However,regardless of the value of the CEINTEN register, the status of all interrupt events is directlyreadable via the CEINTSRC register. Therefore, the software has visibility of an event generatinga potential interrupt by polling the register and not having an interrupt propagate out of themodule.
To clear an interrupt, the software must write a '1' to both the particular interrupt and the PENDIFbits in the CEINTSRC register.
Following is a description of the interrupt events generated by the Crypto Engine:
• Access Response error interrupt, signaled by the AREIF bit (CEINTSRC<3>) and enabled using the AREIE bit (CEINTEN<3>). This event occurs when the Crypto Engine DMA encounters a bus error during a memory access and is caused by an addressing error. For example, if the Crypto Engine attempts to access reserved memory, or memory that has been protected from access by the Crypto Engine, this interrupt will be generated. Recov-ering from this error requires a soft reset of the Crypto Engine using the SWRST bit (CECON<6>).
• DMA Packet Completion interrupt, signaled by the PKTIF bit (CEINTSRC<2>) and enabled using the PKTIE bit (CEINTEN<2>). This event occurs when the Crypto Engine has completed transferring memory.
• Buffer Descriptor Processing interrupt, signaled by the CBDIF bit (CEINTSRC<1>) and enabled using the CBDIE bit (CEINTEN<1>). This event occurs when the Crypto Engine has completed processing a Buffer Descriptor.
• Pending interrupt, signaled by the PENDIF bit (CEINTSRC<0>) and enabled using the PENDIE bit (CEINTEN<0>). This is a global interrupt, combining the values of the other interrupt sources. This bit must be enabled in addition to the other interrupt sources in order to generate interrupts from the Crypto Engine.
All interrupts belonging to the Crypto Engine map to the Crypto Engine interrupt vector.
The corresponding Crypto Engine interrupt flag is CRPTIF (IFS3<11>). This interrupt flag mustbe cleared in software once the cause generating the interrupt is processed.
The Crypto Engine is enabled as a source of interrupts via the respective Crypto Engine interruptenable bit, CRPTIE (IEC3<11>).
The interrupt priority-level bits and interrupt sub-priority-level bits must also be configured:
• CRPTIP<2:0> (IPC26<28:26>)
• CRPTIS<1:0> (IPC26<25:24>)
The interrupt service routine that is to be used when a Crypto Engine interrupt is generated isconfigured via the VOFF107<17:1> bits (OFF107<17:1>).
49.6.1 Interrupt Configuration
The Crypto Engine has multiple internal interrupt flags (AREIF, PKTIF, CBDIF, PENDIF) andcorresponding enable interrupt control bits (AREIE, PKTIE, CBDIE, PENDIE). However, for theInterrupt Controller, there is one dedicated interrupt flag bit for the Crypto Engine: CRPTIF(IFS3<11>) and the corresponding interrupt enable/mask bit, CRPTIE (IEC3<11>).
The Crypto Engine has its own priority and sub-priority levels independent of other peripherals.The CRPTIF bit will be set without regard to the state of the corresponding enable bit, CRPTIE.The CRPTIF bit can be polled by software if desired.
Note: Refer to Section 8. “Interrupts” (DS60001108) in the “PIC32 Family ReferenceManual” for detailed descriptions of the IFSx, IECx, IPCx, and OFFx registerinterrupt bits.
Note: All of the interrupt conditions for the Crypto Engine share one interrupt vector.
Section 49. Crypto Engine and Random Number Generator (RNG)C
ryp
to E
ng
ine
an
d
Ra
nd
om
Nu
mb
er
Ge
ne
rato
r (RN
G)
49
The CRPTIE bit is used to define the behavior of the Interrupt Controller when the correspondingCRPTIF bit is set. When the corresponding CRPTIE bit is clear, the Interrupt Controller does notgenerate a CPU interrupt for the event. If the CRPTIE bit is set, the Interrupt Controller willgenerate an interrupt to the CPU when the CRPTIF bit is set (subject to the priority andsub-priority as follows).
It is the responsibility of the user's software routine that services a particular interrupt to clear theinterrupt flag bit before the service routine is complete.
The priority of the Crypto Engine interrupt can be set using the IPC26 register of the InterruptController. This priority defines the priority group to which the interrupt source will be assigned.The priority groups range from a value of 7 (the highest priority) to a value of 0, which does notgenerate an interrupt. An interrupt being serviced will be preempted by an interrupt in a higherpriority group.
The sub-priority bits allow setting the priority of an interrupt source within a priority group. Thevalues for the sub-priority range from 3 (the highest priority) to 0 (the lowest priority). An interruptwith the same priority group, but having a higher sub-priority value, will not pre-empt a lowersub-priority interrupt that is in progress. Rather, if two interrupts in the same priority group arepending, the one with the higher sub-priority value will be serviced first.
The priority group and sub-priority bits allow more than one interrupt source to share the samepriority and sub-priority. If simultaneous interrupts occur in this configuration, the natural order ofthe interrupt sources within a priority/sub-priority group pair determine the interrupt generated.
The natural priority is based on the vector numbers of the interrupt sources. The lower the vectornumber, the higher the natural priority of the interrupt. Any interrupts that were overridden bynatural order will then generate their respective interrupts based on priority, sub-priority andnatural order after the interrupt flag for the current interrupt is cleared.
After an enabled interrupt is generated, the CPU will jump to the vector assigned to that interrupt.The vector number for the interrupt is the same as the natural order number. The CPU will thenbegin executing code at the vector address. The user's code at this vector address shouldperform any application-specific operations and clear the CRPTIF interrupt flags (as well as thecorresponding event in the CEINTSRC register if a software clearable interrupt) and then exit.
Refer to the vector address table details in Section 8. “Interrupts” (DS60001108) in the “PIC32Family Reference Manual” for more information.
Example 49-6: Crypto Engine Initialization with Interrupts Enabled Code/* Start the engine */CEBDPADDR = KVA_TO_PA(&enc_bd);CEINTEN = 0x07;CECON = 0x07;
The Random Number Generator (RNG) core implements a thermal noise-based True RandomNumber Generator (TRNG) and a cryptographically secure Pseudo-Random Number Generator(PRNG).
The TRNG uses multiple ring oscillators and the inherent thermal noise of integrated circuits togenerate true random numbers that can initialize the PRNG.
The PRNG is a flexible Linear Shift Feedback Register (LSFR), which is capable of manifestinga maximal length LFSR of up to 64 bits.
49.7.1 TRNG Usage
Enabling the TRNG for operation is done using the TRNGEN bit (RNGCON<8>). Setting this bitstarts the TRNG generating numbers.
The random numbers are read through the RNGSEED1 and RNGSEED2 registers. Thisprovides up to a 64-bit wide number for use. The number of valid bits in the registers are indicatedin the RNGCNT register. It is recommended to wait until the value in that register equals orexceeds the number of bits desired before reading the value.
49.7.2 PRNG Usage
Before starting the PRNG, it is necessary to set up the initial seed value, set the length of thepolynomial, and the polynomial equation.
The initial seed value is set by writing to the RNGNUMGEN1 and RNGNUMGEN2 registers,which are also the registers where the random value are read.
The initial seed value can also be loaded from the TRNG by writing a '1' to the LOAD bit(RNGCON<12>). This action transfers the current value in the RNGSEEDx registers to thecorresponding RNGNUMGENx registers.
The polynomial length for the LSFR is set by writing the length (in bits) to the PLEN<7:0> bits(RNGCON<7:0>). Since the polynomial can be a maximum of 64 bits, the maximum value forthis register would be 64. However, the actual length needed will depend on the needs of theapplication and the degree of pseudo-randomness needed.
The polynomial equation itself is set via the RNGPOLYx registers. Setting a bit in these registersturns on the corresponding tap for the generation of the random numbers.
Enabling the PRNG for operation is done by writing a '1' to the PRNGEN bit (RNGCON<9>).
The following example sets the PRNG for a 42-bit maximal-length polynomial with the equation,x42 + x41 + x20 + x19 + 1, initializes the random number with a set value, and turns on the PRNG.
Example 49-7: PRNG Configuration
Once the PRNG has been turned on, it is necessary to wait PLEN cycles before reading theRNGNUMGENx registers. Reading the RNGNUMGENx registers will trigger the generation ofthe next random number, which will take PLEN clock cycles to complete. Optionally, a newrandom number can be generated every PLEN clock cycles by setting the CONT bit(RNGCON<10>).
Section 49. Crypto Engine and Random Number Generator (RNG)C
ryp
to E
ng
ine
an
d
Ra
nd
om
Nu
mb
er
Ge
ne
rato
r (RN
G)
49
49.8 RANDOM NUMBER GENERATOR INTERRUPTS
The RNG does not generate interrupts in PIC32 devices.
49.9 EFFECTS OF VARIOUS RESETS
49.9.1 Device Reset
All Crypto Engine and RNG registers are forced to their reset states upon a device Reset. Forthe Crypto Engine, and any on-going data transfers are aborted. For the RNG, the TRNG andPRNG halt their operations.
49.9.2 Power-on Reset
All Crypto Engine and RNG registers are forced to their reset states upon a Power-on Reset.
49.9.3 NMI Reset
All Crypto Engine and RNG registers are forced to their reset states if the NMI countdown lapsesand a full reset is issued.
49.10 OPERATION IN POWER-SAVING MODES
49.10.1 Crypto Engine Operation in Sleep Mode
When the PIC32 device enters Sleep mode, the system clock is disabled. No Crypto Enginetransfers can occur in this mode. All clocks are stopped, so no further Crypto Engine activity cantake place. Software is responsible for determining if a Crypto Engine operation is in progressand whether to prevent going to Sleep mode until such actions are finished.
49.10.2 Crypto Engine Operation in Idle Mode
When the device enters Idle mode, the system and peripheral bus clock sources remainfunctional. The Crypto Engine will continue to operate in Idle mode, can continue operations, andcan generate interrupts that will wake the CPU.
49.10.3 Random Number Generator Operation in Sleep Mode
When the PIC32 device enters Sleep mode, the system clock is disabled. The PRNG haltsgenerating random numbers if the CONT bit was set. The state of the RNG registers ispreserved, so random numbers can continue from their stopping point when Sleep mode wasentered. The TRNG may continue generating random numbers, since it is dependent on ringoscillators that do not depend on the system clock. However, the random numbers may not beclocked into the RNGSEEDx registers.
49.10.4 Random Number Generator Operation in Idle Mode
When the device enters Idle mode, the system and peripheral bus clock sources remainfunctional. The PRNG will continue to generate random numbers if the CONT bit was set. TheTRNG will continue generating random numbers. The RNG cannot generate interrupts, andtherefore it cannot wake the CPU.
This section lists application notes that are related to this section of the manual. Theseapplication notes may not be written specifically for the PIC32 device family, but the concepts arepertinent and could be used with modification and possible limitations. The current applicationnotes related to the Crypto Engine and Random Number Generator (RNG) are:
Title Application Note #
No related application notes at this time. N/A
Note: Please visit the Microchip web site (www.microchip.com) for additional applicationnotes and code examples for the PIC32 family of devices.
Note the following details of the code protection feature on Microchip devices:
• Microchip products meet the specification contained in their particular Microchip Data Sheet.
• Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the intended manner and under normal conditions.
• There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data Sheets. Most likely, the person doing so is engaged in theft of intellectual property.
• Microchip is willing to work with the customer who is concerned about the integrity of their code.
• Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not mean that we are guaranteeing the product as “unbreakable.”
Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of ourproducts. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such actsallow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.
Information contained in this publication regarding deviceapplications and the like is provided only for your convenienceand may be superseded by updates. It is your responsibility toensure that your application meets with your specifications.MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS ORIMPLIED, WRITTEN OR ORAL, STATUTORY OROTHERWISE, RELATED TO THE INFORMATION,INCLUDING BUT NOT LIMITED TO ITS CONDITION,QUALITY, PERFORMANCE, MERCHANTABILITY ORFITNESS FOR PURPOSE. Microchip disclaims all liabilityarising from this information and its use. Use of Microchipdevices in life support and/or safety applications is entirely atthe buyer’s risk, and the buyer agrees to defend, indemnify andhold harmless Microchip from any and all damages, claims,suits, or expenses resulting from such use. No licenses areconveyed, implicitly or otherwise, under any Microchipintellectual property rights.
2013-2015 Microchip Technology Inc.
QUALITY MANAGEMENT SYSTEM CERTIFIED BY DNV
== ISO/TS 16949 ==
Trademarks
The Microchip name and logo, the Microchip logo, dsPIC, FlashFlex, flexPWR, JukeBlox, KEELOQ, KEELOQ logo, Kleer, LANCheck, MediaLB, MOST, MOST logo, MPLAB, OptoLyzer, PIC, PICSTART, PIC32 logo, RightTouch, SpyNIC, SST, SST Logo, SuperFlash and UNI/O are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.
The Embedded Control Solutions Company and mTouch are registered trademarks of Microchip Technology Incorporated in the U.S.A.
Analog-for-the-Digital Age, BodyCom, chipKIT, chipKIT logo, CodeGuard, dsPICDEM, dsPICDEM.net, ECAN, In-Circuit Serial Programming, ICSP, Inter-Chip Connectivity, KleerNet, KleerNet logo, MiWi, MPASM, MPF, MPLAB Certified logo, MPLIB, MPLINK, MultiTRAK, NetDetach, Omniscient Code Generation, PICDEM, PICDEM.net, PICkit, PICtail, RightTouch logo, REAL ICE, SQI, Serial Quad I/O, Total Endurance, TSHARC, USBCheck, VariSense, ViewSpan, WiperLock, Wireless DNA, and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.
SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.
Silicon Storage Technology is a registered trademark of Microchip Technology Inc. in other countries.
GestIC is a registered trademarks of Microchip Technology Germany II GmbH & Co. KG, a subsidiary of Microchip Technology Inc., in other countries.
All other trademarks mentioned herein are property of their respective companies.
Microchip received ISO/TS-16949:2009 certification for its worldwide headquarters, design and wafer fabrication facilities in Chandler and Tempe, Arizona; Gresham, Oregon and design centers in California and India. The Company’s quality system processes and procedures are for its PIC® MCUs and dsPIC® DSCs, KEELOQ® code hopping devices, Serial EEPROMs, microperipherals, nonvolatile memory and analog products. In addition, Microchip’s quality system for the design and manufacture of development systems is ISO 9001:2000 certified.
DS60001246B-page 49-48 2013-2015 Microchip Technology Inc.
AMERICASCorporate Office2355 West Chandler Blvd.Chandler, AZ 85224-6199Tel: 480-792-7200 Fax: 480-792-7277Technical Support: http://www.microchip.com/supportWeb Address: www.microchip.com
AtlantaDuluth, GA Tel: 678-957-9614 Fax: 678-957-1455
Austin, TXTel: 512-257-3370
BostonWestborough, MA Tel: 774-760-0087 Fax: 774-760-0088
ChicagoItasca, IL Tel: 630-285-0071 Fax: 630-285-0075