1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3 * LibTomCrypt is a library that provides various cryptographic
4 * algorithms in a highly modular and flexible manner.
6 * The library is free for all purposes without any express
12 Source donated by Elliptic Semiconductor Inc (www.ellipticsemi.com) to the LibTom Projects
17 static int _tweak_crypt(const unsigned char *P, unsigned char *C, unsigned char *T, symmetric_xts *xts)
22 /* tweak encrypt block i */
24 for (x = 0; x < 16; x += sizeof(LTC_FAST_TYPE)) {
25 *(LTC_FAST_TYPE_PTR_CAST(&C[x])) = *(LTC_FAST_TYPE_PTR_CAST(&P[x])) ^ *(LTC_FAST_TYPE_PTR_CAST(&T[x]));
28 for (x = 0; x < 16; x++) {
33 if ((err = cipher_descriptor[xts->cipher].ecb_encrypt(C, C, &xts->key1)) != CRYPT_OK) {
38 for (x = 0; x < 16; x += sizeof(LTC_FAST_TYPE)) {
39 *(LTC_FAST_TYPE_PTR_CAST(&C[x])) ^= *(LTC_FAST_TYPE_PTR_CAST(&T[x]));
42 for (x = 0; x < 16; x++) {
54 @param pt [in] Plaintext
55 @param ptlen Length of plaintext (and ciphertext)
56 @param ct [out] Ciphertext
57 @param tweak [in] The 128--bit encryption tweak (e.g. sector number)
58 @param xts The XTS structure
59 Returns CRYPT_OK upon success
61 int xts_encrypt(const unsigned char *pt, unsigned long ptlen, unsigned char *ct, unsigned char *tweak,
64 unsigned char PP[16], CC[16], T[16];
65 unsigned long i, m, mo, lim;
69 LTC_ARGCHK(pt != NULL);
70 LTC_ARGCHK(ct != NULL);
71 LTC_ARGCHK(tweak != NULL);
72 LTC_ARGCHK(xts != NULL);
75 if ((err = cipher_is_valid(xts->cipher)) != CRYPT_OK) {
79 /* get number of blocks */
83 /* must have at least one full block */
85 return CRYPT_INVALID_ARG;
94 if (cipher_descriptor[xts->cipher].accel_xts_encrypt && lim > 0) {
96 /* use accelerated encryption for whole blocks */
97 if ((err = cipher_descriptor[xts->cipher].accel_xts_encrypt(pt, ct, lim, tweak, &xts->key1, &xts->key2)) !=
104 /* tweak is encrypted on output */
105 XMEMCPY(T, tweak, sizeof(T));
108 /* encrypt the tweak */
109 if ((err = cipher_descriptor[xts->cipher].ecb_encrypt(tweak, T, &xts->key2)) != CRYPT_OK) {
113 for (i = 0; i < lim; i++) {
114 if ((err = _tweak_crypt(pt, ct, T, xts)) != CRYPT_OK) {
122 /* if ptlen not divide 16 then */
124 /* CC = tweak encrypt block m-1 */
125 if ((err = _tweak_crypt(pt, CC, T, xts)) != CRYPT_OK) {
129 /* Cm = first ptlen % 16 bytes of CC */
130 for (i = 0; i < mo; i++) {
135 for (; i < 16; i++) {
139 /* Cm-1 = Tweak encrypt PP */
140 if ((err = _tweak_crypt(PP, ct, T, xts)) != CRYPT_OK) {
145 /* Decrypt the tweak back */
146 if ((err = cipher_descriptor[xts->cipher].ecb_decrypt(T, tweak, &xts->key2)) != CRYPT_OK) {
155 /* ref: $Format:%D$ */
156 /* git commit: $Format:%H$ */
157 /* commit time: $Format:%ai$ */