# BAREOS - Backup Archiving REcovery Open Sourced## Copyright (C) 2015-2021 Bareos GmbH & Co. KG## This program is Free Software; you can redistribute it and/or# modify it under the terms of version three of the GNU Affero General Public# License as published by the Free Software Foundation and included# in the file LICENSE.## This program 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# Affero General Public License for more details.## You should have received a copy of the GNU Affero General Public License# along with this program; if not, write to the Free Software# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA# 02110-1301, USA."""Bareos specific base64 implementation.Bacula and therefore Bareos specific implementation of a base64 decoder."""
[docs]classBareosBase64(object):"""Bareos specific base64 implementation."""base64_digits=list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")def__init__(self):"""Initialize the Base 64 conversion routines."""self.base64_map=dict(list(zip(self.base64_digits,list(range(0,64)))))
[docs]@staticmethoddeftwos_comp(val,bits):"""Compute the 2's compliment of int value val."""if(val&(1<<(bits-1)))!=0:val=val-(1<<bits)returnval
[docs]defbase64_to_int(self,base64):"""Convert a base 64 string to integer. Args: base64 (str): base 64 string. Returns: int: Integer value of the base64 string. """value=0first=0neg=Falseifbase64[0]=="-":neg=Truefirst=1foriinrange(first,len(base64)):value=value<<6try:value+=self.base64_map[base64[i]]exceptKeyError:print("KeyError:",i)return-valueifnegelsevalue
[docs]defint_to_base64(self,value):"""Convert an integer to base 64. Args: value (int): integeer value. Returns: str: base 64 representation of value. """result=""ifvalue<0:result="-"value=-valuewhilevalue:charnumber=value%0x3Fresult+=self.base64_digits[charnumber]value=value>>6returnresult
[docs]defstring_to_base64(self,string,compatible=False):"""Convert a string to base64. Args: string (str): string to be converted. compatible (bool): If True, generate Baculas broken version of base 64 strings. Returns: bytearray: base 64 representation of the given string. """buf=""reg=0rem=0char=0i=0whilei<len(string):ifrem<6:reg<<=8char=string[i]ifnotcompatible:ifchar>=128:char=self.twos_comp(char,8)reg|=chari+=1rem+=8save=regreg>>=rem-6buf+=self.base64_digits[reg&0x3F]reg=saverem-=6ifrem:mask=(1<<rem)-1ifcompatible:buf+=self.base64_digits[(reg&mask)<<(6-rem)]else:buf+=self.base64_digits[reg&mask]returnbytearray(buf,"utf-8")