// Encrypt encrypt something with mcrypt rijndael-256 PHP-style func Encrypt(key []byte, iv []byte, data []byte) ([]byte, error) { // keep track of the size of the input data length := C.int(len(data)) if length == 0 { return nil, errors.New("Invalid data size of 0") } // keep track of any errors that occur on encryption err := C.int(0) // encrypt the data encryptedData := C.encrypt(unsafe.Pointer(&key[0]), C.int(len(key)), unsafe.Pointer(&iv[0]), C.int(len(iv)), (*C.char)(unsafe.Pointer(&data[0])), (*C.int)(unsafe.Pointer(&length)), (*C.int)(unsafe.Pointer(&err))) // if err is not 0, there is an error if int(err) != 0 { return nil, errors.New(C.GoString(C.getError(err))) } // ensure that memory is freed on the encrypted data after it is converted to Go bytes defer C.free(unsafe.Pointer(encryptedData)) // return the Go bytes of the encrypted data return C.GoBytes(unsafe.Pointer(encryptedData), length), nil }
func (sc *SecureCell) Protect(data []byte, context []byte) ([]byte, []byte, error) { if (sc.mode < CELL_MODE_SEAL) || (sc.mode > CELL_MODE_CONTEXT_IMPRINT) { return nil, nil, errors.New("Invalid mode specified") } if nil == sc.key { return nil, nil, errors.New("Master key was not provided") } if nil == data { return nil, nil, errors.New("Data was not provided") } if CELL_MODE_CONTEXT_IMPRINT == sc.mode { if nil == context { return nil, nil, errors.New("Context is mandatory for context imprint mode") } } var ctx unsafe.Pointer var ctxLen C.size_t if nil != context { ctx = unsafe.Pointer(&context[0]) ctxLen = C.size_t(len(context)) } var encLen, addLen C.size_t if !bool(C.get_protect_size(unsafe.Pointer(&sc.key[0]), C.size_t(len(sc.key)), unsafe.Pointer(&data[0]), C.size_t(len(data)), ctx, ctxLen, C.int(sc.mode), &encLen, &addLen)) { return nil, nil, errors.New("Failed to get ouput size") } var addData []byte var add unsafe.Pointer encData := make([]byte, encLen, encLen) if addLen > 0 { addData = make([]byte, addLen, addLen) add = unsafe.Pointer(&addData[0]) } if !bool(C.encrypt(unsafe.Pointer(&sc.key[0]), C.size_t(len(sc.key)), unsafe.Pointer(&data[0]), C.size_t(len(data)), ctx, ctxLen, C.int(sc.mode), unsafe.Pointer(&encData[0]), encLen, add, addLen)) { return nil, nil, errors.New("Failed to protect data") } return encData, addData, nil }