コード例 #1
0
def decryptPassword(encryptedpassword, key):
    secretKey = Base64.decodeBase64(key)
    seckeySpec = SecretKeySpec(secretKey, "AES")
    if encryptedpassword is not None and encryptedpassword is not ' ':
        encData = Base64.decodeBase64(encryptedpassword)
        cipher.init(Cipher.DECRYPT_MODE, seckeySpec)
        decrypted = cipher.doFinal(encData)
        originalString = decrypted.tostring()
        return originalString
コード例 #2
0
 def authenticate_user_in_azure(tenant_id, user_name, pwd, client_id,
                                client_secret):
     post_params_json = {
         'resource': AZURE_AD_GRAPH_RESOURCE_ENDPOINT,
         'client_id': client_id,
         'client_secret': client_secret,
         'username': user_name,
         'password': pwd,
         'grant_type': 'password',
         'scope': 'openid'
     }
     post_params_url_encoded = urllib.urlencode(post_params_json)
     headers_json = {
         'Content-type': 'application/x-www-form-urlencoded',
         'Accept': 'application/json'
     }
     conn = httplib.HTTPSConnection(MICROSOFT_AUTHORITY_URL + ':443')
     relative_url = '/' + tenant_id + '/oauth2/token'
     conn.request('POST', relative_url, post_params_url_encoded,
                  headers_json)
     response = conn.getresponse()
     # print response.status, response.reason
     azure_response = response.read()
     conn.close()
     # print "Response Data: %s" % azure_response
     azure_response_json = json.loads(azure_response)
     if 'id_token' in azure_response_json:
         id_token = azure_response_json['id_token']
         id_token_array = String(id_token).split("\\.")
         id_token_payload = id_token_array[1]
         id_token_payload_str = String(
             Base64.decodeBase64(id_token_payload), 'UTF-8')
         return str(id_token_payload_str)
     else:
         return azure_response
コード例 #3
0
 def log_plot(self, plot, name=None, footer=None):
     if name == None:
         name = "Scripting plot"
     if not plot is None and hasattr(plot, 'pv'):
         if footer is None:
             if hasattr(plot, 'title'):
                 footer = plot.title
         try:
             self.logger.appendImageEntry(name,
                                          plot.pv.getPlot().getImage(),
                                          footer)
         except:
             print 'failed to send plot to notebook db'
     elif not plot is None and hasattr(plot, 'cache'):
         if footer is None:
             if hasattr(plot, 'title'):
                 footer = plot.title
         try:
             from org.apache.commons.codec.binary import Base64
             from java.lang import String
             self.logger.appendImageEntry(
                 name,
                 String(Base64.encodeBase64(plot.cache.getImageCache())),
                 footer)
         except:
             print 'failed to send plot to notebook db'
コード例 #4
0
ファイル: yazino.py プロジェクト: ShahakBH/jazzino-master
def retrieveBody(delivery):
    if delivery.properties.contentEncoding == "DEF":
        compressed = Base64.decodeBase64(String(delivery.body).getBytes("UTF-8"))
        inflated = ByteArrayOutputStream()
        inflatedOs = InflaterOutputStream(inflated)
        inflatedOs.write(compressed)
        inflatedOs.close()
        return inflated.toString("UTF-8")
    else:
        return String(delivery.body, "UTF-8")
コード例 #5
0
 def decodeMessage(wrapper, message):
     result = ""
     decoded = Base64.decodeBase64(message)
     try:
         Z = String(decoded, "UTF-8")
         result = Z.split(wrapper)[1]
     except Exception as ex:
         self._logger.log(Level.SEVERE, "Error decoding a Tango message", ex)
         self._logger.log(Level.SEVERE, traceback.format_exc())
     return result
コード例 #6
0
ファイル: tangomessage.py プロジェクト: sleuthkit/autopsy
 def decodeMessage(wrapper, message):
     result = ""
     decoded = Base64.decodeBase64(message)
     try:
         Z = String(decoded, "UTF-8")
         result = Z.split(wrapper)[1]
     except Exception as ex:
         # Error decoding a Tango message.
         pass
     return result
コード例 #7
0
ファイル: tangomessage.py プロジェクト: millmanorama/autopsy
 def decodeMessage(wrapper, message):
     result = ""
     decoded = Base64.decodeBase64(message)
     try:
         Z = String(decoded, "UTF-8")
         result = Z.split(wrapper)[1]
     except Exception as ex:
         # Error decoding a Tango message.
         pass
     return result
コード例 #8
0
ファイル: yazino.py プロジェクト: pticun/bet21
def retrieveBody(delivery):
    if delivery.properties.contentEncoding == "DEF":
        compressed = Base64.decodeBase64(
            String(delivery.body).getBytes("UTF-8"))
        inflated = ByteArrayOutputStream()
        inflatedOs = InflaterOutputStream(inflated)
        inflatedOs.write(compressed)
        inflatedOs.close()
        return inflated.toString("UTF-8")
    else:
        return String(delivery.body, "UTF-8")
コード例 #9
0
    def set_credentials(self, request):
        if self.username:
            username = self.username
            password = self.password
        elif self.params.getUsername():
            username = self.params.getUsername()
            password = self.params.getPassword()
        else:
            return

        encoding = Base64.encodeBase64String(String(username + ':' + password).getBytes())
        request.addHeader('Authorization', 'Basic ' + encoding)
コード例 #10
0
    def setCredentials(self, request):
        if self.username:
            username = self.username
            password = self.password
        elif self.params.getUsername():
            username = self.params.getUsername()
            password = self.params.getPassword()
        else:
            return

        encoding = Base64.encodeBase64String(String(username + ':' + password).getBytes('ISO-8859-1'))
        request.addHeader('Authorization', 'Basic ' + encoding)
コード例 #11
0
ファイル: tests_jython.py プロジェクト: fish2000/pylire
def test_JCD(im, silence=False):
    """ Testing: Joint Color Descriptor (JCD) """
    if not silence:
        print ""
        print "JCD:"
    jcd = JCD()
    jcd.extract(im)
    return (
        "n/a", #jcd.getStringRepresentation()
        Base64.encodeBase64String(
            jcd.getByteArrayRepresentation()),
        ParallelSolrIndexer.arrayToString(
            BitSampling.generateHashes(
                jcd.getDoubleHistogram())))
コード例 #12
0
ファイル: tests_jython.py プロジェクト: fish2000/pylire
def test_PHOG(im, silence=False):
    """ Testing: Pyramidal Histogram of Gradient (PHOG) Descriptor """
    if not silence:
        print ""
        print "PHOG:"
    phog = PHOG()
    phog.extract(im)
    return (
        "n/a", # phog.getStringRepresentation()
        Base64.encodeBase64String(
            phog.getByteArrayRepresentation()),
        ParallelSolrIndexer.arrayToString(
            BitSampling.generateHashes(
                phog.getDoubleHistogram())))
コード例 #13
0
ファイル: tests_jython.py プロジェクト: fish2000/pylire
def test_color_layout(im, silence=False):
    """ Testing: color layout """
    if not silence:
        print ""
        print "Color Layout:"
    colorlay = ColorLayout()
    colorlay.extract(im)
    return (
        colorlay.getStringRepresentation(),
        Base64.encodeBase64String(
            colorlay.getByteArrayRepresentation()),
        ParallelSolrIndexer.arrayToString(
            BitSampling.generateHashes(
                colorlay.getDoubleHistogram())))
コード例 #14
0
ファイル: tests_jython.py プロジェクト: fish2000/pylire
def test_edge_histogram(im, silence=False):
    """ Testing: edge histogram """
    if not silence:
        print ""
        print "Edge Histogram:"
    edgehist = EdgeHistogram()
    edgehist.extract(im)
    return (
        edgehist.getStringRepresentation(),
        Base64.encodeBase64String(
            edgehist.getByteArrayRepresentation()),
        ParallelSolrIndexer.arrayToString(
            BitSampling.generateHashes(
                edgehist.getDoubleHistogram())))
コード例 #15
0
ファイル: tests_jython.py プロジェクト: fish2000/pylire
def test_opponent_histogram(im, silence=False):
    """ Testing: opponent histogram """
    # sb.append(arrayToString(BitSampling.generateHashes(feature.getDoubleHistogram())));
    if not silence:
        print ""
        print "Opponent Histogram:"
    opphist = OpponentHistogram()
    opphist.extract(im)
    return (
        opphist.getStringRepresentation(),
        Base64.encodeBase64String(
            opphist.getByteArrayRepresentation()),
        ParallelSolrIndexer.arrayToString(
            BitSampling.generateHashes(
                opphist.getDoubleHistogram())))
コード例 #16
0
def encryptPassword(password):
    if password is not None and password is not ' ':
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec)
        encrypted = cipher.doFinal(password)
        encodeTxt = Base64.encodeBase64(encrypted)
        return encodeTxt.tostring()
コード例 #17
0
 def set_basic_credentials(self, request):
     credentials = self.get_credentials()
     encoding = Base64.encodeBase64String(
         String(credentials["username"] + ':' +
                credentials["password"]).getBytes())
     request.addHeader('Authorization', 'Basic ' + encoding)
コード例 #18
0
ファイル: powershellutils.py プロジェクト: deezeesms/dd-git
def encodeCommand(cmdlet):
#    return String(Base64().encode(cmdlet))
    utf16bytes = list(String(cmdlet).getBytes('UTF-16'))
    utf16bytes = utf16bytes[3:]
    utf16bytes.append(0)
    return String(Base64().encode(utf16bytes))
コード例 #19
0
ntpipelineapiSet = mbo.getMboSet("NTPIPELINEAPI")
if ntpipelineapiSet.isEmpty():
    service.error('ntpipeline', 'pipelineMap', None)  #Break
pipelineapi = ntpipelineapiSet.moveFirst()
uri = host + '/os/'
uri = uri + pipelineapi.getString("INTOBJECTNAME")
uri = uri + '?lean=1&oslc.where='  #MAXDOMAINID='
uri = uri + pipelineapi.getString("UNIQUECOLUMN") + '='
uri = uri + str(mbo.getInt("FOREIGNKEY"))
uri = uri + '&oslc.select=*'
clientid = "maxadmin"
clientsecurity = "maxadmin"

# get authentication header
auth = clientid + ":" + clientsecurity
encodedAuth = String(Base64.encodeBase64(String.getBytes(auth, 'ISO-8859-1')),
                     "UTF-8")
authHeader = str(encodedAuth)

# get http parameters
params = BasicHttpParams()
paramsBean = HttpProtocolParamBean(params)
paramsBean.setVersion(HttpVersion.HTTP_1_1)
paramsBean.setContentCharset("UTF-8")
paramsBean.setUseExpectContinue(True)

# get http body entities
formparams = ArrayList()
#formparams.add(BasicNameValuePair("username", username))
entity = UrlEncodedFormEntity(formparams, "UTF-8")
コード例 #20
0
from java.lang import System, String
from java.util import Properties
from java.math import BigInteger
from java.security import *
from javax.crypto import KeyGenerator, SecretKey, Cipher
from javax.crypto.spec import SecretKeySpec

from org.apache.log4j import Logger
from org.apache.commons.codec.binary import Base64

log = Logger.getLogger('password_encrypter')
kgen = KeyGenerator.getInstance("AES")
kgen.init(128)
skey = kgen.generateKey()
raw = skey.getEncoded()
rawkey = Base64.encodeBase64(raw).tostring()
skeySpec = SecretKeySpec(raw, "AES")
cipher = Cipher.getInstance("AES")


def encryptPassword(password):
    if password is not None and password is not ' ':
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec)
        encrypted = cipher.doFinal(password)
        encodeTxt = Base64.encodeBase64(encrypted)
        return encodeTxt.tostring()


def encryptAllPasswords(configfile):
    log.info("Encrypting Passwords in config file")
    if (configfile is not None and not ''):
コード例 #21
0
    azure_response = response.read()
    conn.close()
    print "Response Data: %s" % azure_response
    azure_response_json = json.loads(azure_response)
    if 'id_token' in azure_response_json:
        id_token = azure_response_json['id_token']
        id_token_array = String(id_token).split("\\.")
        id_token_payload = id_token_array[1]
        id_token_payload_str = String(Base64.decodeBase64(id_token_payload), 'UTF-8')
        return str(id_token_payload_str)
    else:
        return azure_response


print "Start Time: %s" % datetime.now()
pwd = String(Base64.decodeBase64('UHJhbWF0aUAxMjM='), 'UTF-8')
auth_response = authenticate_user_in_azure(AZURE_TENANT_ID, AZURE_USER_NAME, pwd, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET)
print "End Time: %s" % datetime.now()
print "Auth response: %s" % auth_response
azure_auth_response_json = json.loads(auth_response)
if 'upn' in azure_auth_response_json:
    name = azure_auth_response_json['upn']
    print "upn is present: %s" % name
elif 'error' in azure_auth_response_json:
    error = azure_auth_response_json['error']
    error_msg = azure_auth_response_json['error_description']
    print "Error is %s" % error
    print "Error Message is %s" % error_msg


# azureAuthConnector = AzureAuthConnector()
#
# Copyright 2019 XEBIALABS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

from java.io import ByteArrayInputStream
from org.apache.commons.codec.binary import Base64
from org.apache.poi.xssf.usermodel import XSSFWorkbook

from templateImportExcel.TemplateImportExcelClientUtil import Template_Import_Excel_Client_Util

logger.info("Executing templateImportExcel/import-rest.py")

targetFolderId = request.entity['data']['targetFolderId']
templateName = request.entity['data']['templateName']
workbook = XSSFWorkbook(
    ByteArrayInputStream(Base64.decodeBase64(
        request.entity['data']['result'])))
print "created workbook\n"
client = Template_Import_Excel_Client_Util.create_client(
    workbook, targetFolderId, templateName, templateApi, phaseApi, taskApi)
client.convertWorkbookToTemplate()

logger.info("Exiting import-rest.py")
コード例 #23
0
def executeSSOTest():
    reqInstant = dateFormat.format(GregorianCalendar(utctz).getTime())
    reqId = UUID.randomUUID().toString()
    authnRequest = props.get('shib.sp.authnreq') % (idpSSOEndpoint, reqId,
                                                    reqInstant, spId)

    webClient = WebClient()
    webClient.setUseInsecureSSL(True)
    listreq = ArrayList()
    listreq.add(
        NameValuePair(
            "SAMLRequest",
            String(Base64.encodeBase64(String(authnRequest).getBytes()),
                   'US-ASCII')))
    wrs = WebRequestSettings(URL(idpSSOEndpoint), HttpMethod.POST)
    wrs.setRequestParameters(listreq)

    if props.get('shib.idp.auth') == 'FORM':
        webClient.setRedirectEnabled(True)

        if debug: log("sending SSO request to: " + idpSSOEndpoint, stdout)
        wr = webClient.loadWebResponse(wrs)
        if debug: log("Response content: \n" + wr.getContentAsString(), stdout)

        if wr.getStatusCode() != 200:
            raise Exception('Invalid HTTP response code: ' +
                            str(wr.getStatusCode()))
        wrs.setHttpMethod(HttpMethod.POST)
        listauth = ArrayList()
        listauth.add(NameValuePair("j_username", props.get('shib.user.name')))
        listauth.add(NameValuePair("j_password", props.get('shib.user.pass')))
        wrs.setRequestParameters(listauth)
        wrs.setUrl(wr.getRequestUrl())
    else:
        # BASIC auth
        webClient.setRedirectEnabled(False)

        if debug: log("sending SSO request to: " + idpSSOEndpoint, stdout)
        wr = webClient.loadWebResponse(wrs)
        if debug: log("Response content: \n" + wr.getContentAsString(), stdout)

        if wr.getStatusCode() != 302:
            raise Exception('Invalid HTTP response code: ' +
                            str(wr.getStatusCode()))
        wrs.setHttpMethod(HttpMethod.GET)
        creds = DefaultCredentialsProvider()
        creds.addCredentials(props.get('shib.user.name'),
                             props.get('shib.user.pass'), idpHost, idpPort,
                             props.get('shib.user.realm'))
        wrs.setCredentialsProvider(creds)

        if debug:
            log(
                "sending BASIC auth to: " +
                wr.getResponseHeaderValue('Location'), stdout)
        wrs.setUrl(URL(wr.getResponseHeaderValue('Location')))

    if debug:
        log("sending login request to: " + str(wr.getRequestUrl()), stdout)
    wr = webClient.loadWebResponse(wrs)

    if debug:
        log("Request URL = " + wr.getRequestUrl().toString(), stdout)
        log(wr.getContentAsString(), stdout)

    if wr.getStatusCode() not in [200, 301, 302]:
        if debug: log("error response: " + response.getText(), stdout)
        raise Exception('Invalid HTTP response code: ' +
                        str(wr.getStatusCode()))
    return wr.getContentAsString()