/docs/MyDocs

To get this branch, use:
bzr branch http://darksoft.org/webbzr/docs/MyDocs

« back to all changes in this revision

Viewing changes to Development/languages/C/Samples/mcrypt/apoppwd.c

  • Committer: Suren A. Chilingaryan
  • Date: 2009-04-09 03:21:08 UTC
  • Revision ID: csa@dside.dyndns.org-20090409032108-w4edamdh4adrgdu3
import

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#include <stdio.h>
 
2
#include <stdlib.h>
 
3
#include <unistd.h>
 
4
#include <string.h>
 
5
#include <mcrypt.h>
 
6
#include "tmpkey.h"
 
7
 
 
8
main(int argc, char *argv[]) {
 
9
    int i,j;
 
10
 
 
11
    MCRYPT td;
 
12
    unsigned char *newpw;
 
13
    unsigned char *cknewpw;
 
14
    char *sout;
 
15
    unsigned ssize;
 
16
    unsigned IVsize;
 
17
    unsigned blocksize;
 
18
    unsigned char *IV;
 
19
    FILE *f;
 
20
 
 
21
    if (argc>1) newpw=strdup(argv[1]);
 
22
    else 
 
23
    {
 
24
        newpw = strdup(getpass("New password: "));
 
25
        cknewpw = getpass("Re-enter new password: ");
 
26
 
 
27
        if( strcmp( newpw, cknewpw )) 
 
28
        {
 
29
            fprintf( stderr, "Password values do not match\n" );
 
30
            exit(1);
 
31
        }
 
32
        for (i=0;i<strlen(cknewpw);i++)  cknewpw[i]=0;
 
33
    }
 
34
 
 
35
  td = mcrypt_module_open("twofish", NULL, "cfb", NULL);
 
36
  if (td==MCRYPT_FAILED) return 1;
 
37
  
 
38
  IVsize=mcrypt_enc_get_iv_size(td);
 
39
  IV = malloc(IVsize);
 
40
  if (!IV) {
 
41
    fprintf(stderr,"Can't allocate memory!\n");
 
42
    exit(1);
 
43
  }
 
44
  
 
45
  f=fopen("/dev/urandom","r");
 
46
  if (!f) f=fopen("/dev/random","r");
 
47
  if (!f) {
 
48
     for (i=0; i<IVsize; i++)
 
49
        IV[i]=rand();
 
50
  } else {
 
51
    fread(IV,IVsize,1,f);
 
52
    fclose(f);
 
53
  }
 
54
  i=mcrypt_generic_init( td, tmpkey, tmpkeysize, IV);
 
55
  if (i<0) {
 
56
     mcrypt_perror(i);
 
57
     return 1;
 
58
  }
 
59
 
 
60
  ssize=strlen(newpw);
 
61
  mcrypt_generic (td, newpw, ssize);
 
62
 
 
63
  sout=(char*)malloc(2*(1+IVsize+ssize)+1);
 
64
  if (!sout) {
 
65
    fprintf(stderr,"Can't allocate memory!\n");
 
66
    exit(1);
 
67
  }
 
68
  sprintf(sout,"%lx",IVsize);
 
69
  for(j=2,i=0;i<IVsize;i++,j+=2)
 
70
  {
 
71
    if (IV[i]<0x10) sprintf(sout+j,"0%x",IV[i]);
 
72
    else sprintf(sout+j,"%x",IV[i]);
 
73
  }
 
74
 
 
75
  for(i=0;i<ssize;i++,j+=2)
 
76
  {
 
77
    if (newpw[i]<0x10) sprintf(sout+j,"0%x",newpw[i]);
 
78
    else sprintf(sout+j,"%x",newpw[i]);
 
79
  }
 
80
  sout[j]=0;    
 
81
  printf("%s\n",sout);
 
82
 
 
83
  mcrypt_generic_end(td);
 
84
  free(sout);
 
85
  free(IV);
 
86
  return 0;
 
87
}