summaryrefslogtreecommitdiff
path: root/crypt/crypt.go
blob: 40b51497220951855c7438ab663a3eefe5ed0ad5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright 2015-2016 Luke Shumaker <lukeshu@sbcglobal.net>.
//
// This is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This software is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this manual; if not, see
// <http://www.gnu.org/licenses/>.

// Package crypt provides an interface to the POSIX CRYPT option
// group.
//
// Actually, it doesn't yet support encrypt() or setkey()
package crypt

import "unsafe"

/*
#cgo LDFLAGS: -lcrypt
#define _GNU_SOURCE // for crypt_r(3) in crypt.h
#include <stdlib.h> // for free(3)
#include <crypt.h>  // for crypt_r(3)
#include <string.h> // for strdup(3) and memset(3)
char *c_crypt(const char *key, const char *salt)
{
  struct crypt_data data;
  data.initialized = 0;
  char *hash = crypt_r(key, salt, &data);
  if (hash)
    hash = strdup(hash);
  memset(&data, 0, sizeof(data));
  return hash;
}
*/
import "C"

func Crypt(key string, salt string) string {
	ckey := C.CString(key)
	defer C.free(unsafe.Pointer(ckey))
	csalt := C.CString(salt)
	defer C.free(unsafe.Pointer(csalt))
	chash := C.c_crypt(ckey, csalt)
	defer C.free(unsafe.Pointer(chash))
	hash := C.GoString(chash)
	return hash
}

func SaltOk(salt string) bool {
	if len(salt) < 2 {
		return false
	}
	hash := Crypt("", salt)
	if len(hash) < 2 {
		return false
	}
	return salt[0] == hash[0] && salt[1] == hash[1]
}

const SaltAlphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./"