]> pd.if.org Git - zpackage/blob - libtomcrypt/src/encauth/ocb/ocb_encrypt_authenticate_memory.c
1793a6489a175b7643d078bc36fdd1b325eddc09
[zpackage] / libtomcrypt / src / encauth / ocb / ocb_encrypt_authenticate_memory.c
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
2  *
3  * LibTomCrypt is a library that provides various cryptographic
4  * algorithms in a highly modular and flexible manner.
5  *
6  * The library is free for all purposes without any express
7  * guarantee it works.
8  */
9
10 /**
11   @file ocb_encrypt_authenticate_memory.c
12   OCB implementation, encrypt block of memory, by Tom St Denis
13 */
14 #include "tomcrypt.h"
15
16 #ifdef LTC_OCB_MODE
17
18 /**
19    Encrypt and generate an authentication code for a buffer of memory
20    @param cipher     The index of the cipher desired
21    @param key        The secret key
22    @param keylen     The length of the secret key (octets)
23    @param nonce      The session nonce (length of the block ciphers block size)
24    @param pt         The plaintext
25    @param ptlen      The length of the plaintext (octets)
26    @param ct         [out] The ciphertext
27    @param tag        [out] The authentication tag
28    @param taglen     [in/out] The max size and resulting size of the authentication tag
29    @return CRYPT_OK if successful
30 */
31 int ocb_encrypt_authenticate_memory(int cipher,
32     const unsigned char *key,    unsigned long keylen,
33     const unsigned char *nonce,
34     const unsigned char *pt,     unsigned long ptlen,
35           unsigned char *ct,
36           unsigned char *tag,    unsigned long *taglen)
37 {
38    int err;
39    ocb_state *ocb;
40
41    LTC_ARGCHK(key    != NULL);
42    LTC_ARGCHK(nonce  != NULL);
43    LTC_ARGCHK(pt     != NULL);
44    LTC_ARGCHK(ct     != NULL);
45    LTC_ARGCHK(tag    != NULL);
46    LTC_ARGCHK(taglen != NULL);
47
48    /* allocate ram */
49    ocb = XMALLOC(sizeof(ocb_state));
50    if (ocb == NULL) {
51       return CRYPT_MEM;
52    }
53
54    if ((err = ocb_init(ocb, cipher, key, keylen, nonce)) != CRYPT_OK) {
55       goto LBL_ERR;
56    }
57
58    while (ptlen > (unsigned long)ocb->block_len) {
59         if ((err = ocb_encrypt(ocb, pt, ct)) != CRYPT_OK) {
60            goto LBL_ERR;
61         }
62         ptlen   -= ocb->block_len;
63         pt      += ocb->block_len;
64         ct      += ocb->block_len;
65    }
66
67    err = ocb_done_encrypt(ocb, pt, ptlen, ct, tag, taglen);
68 LBL_ERR:
69 #ifdef LTC_CLEAN_STACK
70    zeromem(ocb, sizeof(ocb_state));
71 #endif
72
73    XFREE(ocb);
74
75    return err;
76 }
77
78 #endif
79
80 /* ref:         $Format:%D$ */
81 /* git commit:  $Format:%H$ */
82 /* commit time: $Format:%ai$ */