Internal function used in creating a SignMessage object from a byte string.

@param obj COSE_Sign encoded object.
@throws CoseException Errors generated by the COSE module
336313
@Override
    protected void DecodeFromCBORObject(CBORObject obj) throws CoseException {
        if (obj.size() != 4) throw new CoseException("Invalid SignMessage structure");
        
        if (obj.get(0).getType() == CBORType.ByteString) {
            rgbProtected = obj.get(0).GetByteString();
            if (obj.get(0).GetByteString().length == 0) {
                objProtected = CBORObject.NewMap();
            }
            else {
                objProtected = CBORObject.DecodeFromBytes(rgbProtected);
                if (objProtected.size() == 0) rgbProtected = new byte[0];
            }
        }
        else throw new CoseException("Invalid SignMessage structure");
        
        if (obj.get(1).getType() == CBORType.Map) {
            objUnprotected = obj.get(1);
        }
        else throw new CoseException("Invalid SignMessage structure");
        
        if (obj.get(2).getType() == CBORType.ByteString) rgbContent = obj.get(2).GetByteString();
        else if (!obj.get(2).isNull()) throw new CoseException("Invalid SignMessage structure");
        
        if (obj.get(3).getType() == CBORType.Array) {
            for (int i=0; i<obj.get(3).size(); i++) {
                Signer signer = new Signer();
                signer.DecodeFromCBORObject(obj.get(3).get(i));
                signerList.add(signer);
            }
        }
        else throw new CoseException("Invalid SignMessage structure");
    }
1369044
function _signerToAsn1(obj) {
  // SignerInfo
  var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
    // version
    asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
      asn1.integerToDer(obj.version).getBytes()),
    // issuerAndSerialNumber
    asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
      // name
      forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}),
      // serial
      asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
        forge.util.hexToBytes(obj.serialNumber))
    ]),
    // digestAlgorithm
    asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
      // algorithm
      asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
        asn1.oidToDer(obj.digestAlgorithm).getBytes()),
      // parameters (null)
      asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
    ])
  ]);

  // authenticatedAttributes (OPTIONAL)
  if(obj.authenticatedAttributesAsn1) {
    // add ASN.1 previously generated during signing
    rval.value.push(obj.authenticatedAttributesAsn1);
  }

  // digestEncryptionAlgorithm
  rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
    // algorithm
    asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
      asn1.oidToDer(obj.signatureAlgorithm).getBytes()),
    // parameters (null)
    asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  ]));

  // encryptedDigest
  rval.value.push(asn1.create(
    asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature));

  // unauthenticatedAttributes (OPTIONAL)
  if(obj.unauthenticatedAttributes.length > 0) {
    // [1] IMPLICIT
    var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []);
    for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) {
      var attr = obj.unauthenticatedAttributes[i];
      attrsAsn1.values.push(_attributeToAsn1(attr));
    }
    rval.value.push(attrsAsn1);
  }

  return rval;
}
136620
@Override
  public void processRequest(ProfileRequestContext<?, ?> context) throws ExternalAutenticationErrorCodeException {
    final String logId = this.getLogString(context);
    boolean isSignatureService = this.isSignatureServicePeer(context);    

    SignMessageContext signMessageContext = this.getSignMessageContext(context);
    if (signMessageContext == null) {

      // If the peer is a signature service and has only requested a sigmessage LoA we report an error.
      //
      if (isSignatureService) {
        AuthnContextClassContext authnContextClassContext = this.authnContextService.getAuthnContextClassContext(context);
        for (String loa : authnContextClassContext.getAuthnContextClassRefs()) {
          if (this.isSignMessageURI(loa)) {
            log.info("SP has requested '{}' but did not include SignMessage, removing ... [{}]", loa, logId);
            authnContextClassContext.deleteAuthnContextClassRef(loa);
          }
        }
        if (authnContextClassContext.isEmpty()) {
          final String msg = "No valid AuthnContext URI:s were specified in AuthnRequest";
          log.info("{} - can not proceed [{}]", msg, logId);
          throw new ExternalAutenticationErrorCodeException(AuthnEventIds.REQUEST_UNSUPPORTED, msg);
        }
      }
    }
    else {
      // If an ordinary SP included a SignMessage in the request, we simply ignore it.
      //
      if (!isSignatureService) {
        log.warn("Requesting SP is not a signature service, but included SignMessage extension, ignoring ... [{}]", logId);
        AuthenticationContext authnContext = this.getAuthenticationContext(context);
        authnContext.removeSubcontext(SignMessageContext.class);
      }
      // Else, make additional checks and decrypt.
      //
      else {

        // Decrypt the message
        //
        if (signMessageContext.getSignMessage().getEncryptedMessage() != null) {
          try {
            Message cleartextMessage = this.signatureSupportKeyService.decrypt(signMessageContext.getSignMessage());
            log.debug("SignMessage was successfully decrypted [{}]", logId);
            signMessageContext.setClearTextMessage(cleartextMessage);
          }
          catch (DecryptionException e) {
            final String msg = String.format("Failed to decrypt SignMessage - %s", e.getMessage());
            log.error("{} [{}]", msg, logId);
            throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.SIGN_MESSAGE_DECRYPTION_ERROR, msg);
          }
        }
        else {
          log.debug("SignMessage was not encrypted [{}]", logId);
        }

        if (!this.supportsMimeType(signMessageContext.getMimeType())) {
          log.warn("IdP does not support display of SignMessage with type '{}' [{}]", signMessageContext.getMimeType(), logId);
          signMessageContext.setDoDisplayMessage(false);

          if (signMessageContext.mustShow()) {
            throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.SIGN_MESSAGE_TYPE_NOT_SUPPORTED,
              "Unsupported SignMessage mime type");
          }
        }
        
        // Process (filter, validate, transform) the sign message.
        //
        if (this.signMessagePreProcessor != null && signMessageContext.getClearTextMessage() != null) {
          try {
            String messageToDisplay = this.signMessagePreProcessor.processSignMessage(signMessageContext.getClearTextMessage(), signMessageContext.getMimeType());
            signMessageContext.setMessageToDisplay(messageToDisplay);
          }
          catch (SignMessageContentException e) {
            log.error("Failed to process sign message: {} [{}]", e.getMessage(), logId);
            
            if (signMessageContext.mustShow()) {
              throw new ExternalAutenticationErrorCodeException(AuthnEventIds.REQUEST_UNSUPPORTED, e.getMessage());
            }
            else {
              signMessageContext.setDoDisplayMessage(false);
            }
          }
        }
        
        // Sanity check - If the clear text message is empty, we can not display anything.
        //
        if (signMessageContext.isDoDisplayMessage() && 
            (signMessageContext.getMessageToDisplay() == null || signMessageContext.getMessageToDisplay().matches("\\s*"))) {
          
          log.warn("Sign message is empty or contains only non-visible characters [{}]", logId);
          signMessageContext.setDoDisplayMessage(false);

          if (signMessageContext.mustShow()) {
            throw new ExternalAutenticationErrorCodeException(AuthnEventIds.REQUEST_UNSUPPORTED, "No sign message to show");
          }
        }
        
        // If the SignMessage element from the signature request includes a MustShow attribute with the value true, the
        // Signature Service MUST require that the provided sign message is displayed by the Identity Provider, by
        // including a sigmessage authentication context URI.
        //
        if (signMessageContext.mustShow()) {
          AuthnContextClassContext authnContextClassContext = this.authnContextService.getAuthnContextClassContext(context);
          for (String loa : authnContextClassContext.getAuthnContextClassRefs()) {
            if (!this.isSignMessageURI(loa)) {
              log.info("SP has requested the SignMessage must be displayed, removing '{}' ... [{}]", loa, logId);
              authnContextClassContext.deleteAuthnContextClassRef(loa);
            }
          }
          if (authnContextClassContext.isEmpty()) {
            final String msg = "No valid sigmessage AuthnContext URI:s were specified in AuthnRequest";
            log.info("{} - can not proceed [{}]", msg, logId);
            throw new ExternalAutenticationErrorCodeException(AuthnEventIds.REQUEST_UNSUPPORTED, msg);
          }
        }

        // Finally, check that the DisplayEntity matches our IdP entityID.
        //
        if (signMessageContext.getSignMessage().getDisplayEntity() != null) {
          if (!this.entityID.equals(signMessageContext.getSignMessage().getDisplayEntity())) {
            final String msg = String.format("DisplayEntity (%s) of SignMessage does not match IdP entityID (%s)",
              signMessageContext.getSignMessage().getDisplayEntity(), this.entityID);
            log.info("{} - can not proceed [{}]", msg, logId);
            throw new ExternalAutenticationErrorCodeException(AuthnEventIds.REQUEST_UNSUPPORTED, msg);
          }
        }

        signMessageContext.setDoDisplayMessage(true);
      }
    }

    // Time to check SADRequest ...
    //
    SignatureActivationDataContext sadContext = this.getSadContext(context);
    if (sadContext != null) {

      if (isSignatureService) {
        // If a SADRequest is passed, a SignMessage must also be present.
        //
        if (signMessageContext == null) {
          final String msg = "Request contained SADRequest but no SignMessage was received - not allowed";
          log.info("{} - can not proceed [{}]", msg, logId);
          throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.SWEID_BAD_REQUEST, msg);
        }
        else if (!signMessageContext.isDoDisplayMessage()) {
          // If we cannot display the SignMessage we can not issue a SAD ...
          final String msg = "SignMessage can not be displayed and SAD is requested";
          log.info("{} - can not proceed [{}]", msg, logId);
          throw new ExternalAutenticationErrorCodeException(ExtAuthnEventIds.SWEID_BAD_REQUEST, msg);
        }
        else {
          // Verify the SAD request ...
          //
          this.verifySadRequest(sadContext, context);
        }
      }
      else {
        log.warn("Requesting SP is not a signature service, but included SAPRequest extension in request, ignoring ... [{}]", logId);
        AuthenticationContext authnContext = this.getAuthenticationContext(context);
        authnContext.removeSubcontext(SignatureActivationDataContext.class);
      }
    }

  }
249379
def _signInfo(obj):
    
    lon = obj['lon']
    obj.update({
        'sign': const.LIST_SIGNS[int(lon / 30)],
        'signlon': lon % 30
    })
308840
function decodeBufferCommon(encodedBuffer, index, signed) {
  index = index === undefined ? 0 : index;

  let length = encodedLength(encodedBuffer, index);
  const bitLength = length * 7;
  let byteLength = Math.ceil(bitLength / 8);
  let result = bufs.alloc(byteLength);
  let outIndex = 0;

  while (length > 0) {
    bits.inject(result, outIndex, 7, encodedBuffer[index]);
    outIndex += 7;
    index++;
    length--;
  }

  let signBit;
  let signByte;

  if (signed) {
    // Sign-extend the last byte.
    let lastByte = result[byteLength - 1];
    const endBit = outIndex % 8;
    if (endBit !== 0) {
      const shift = 32 - endBit; // 32 because JS bit ops work on 32-bit ints.
      lastByte = result[byteLength - 1] = ((lastByte << shift) >> shift) & 0xff;
    }
    signBit = lastByte >> 7;
    signByte = signBit * 0xff;
  } else {
    signBit = 0;
    signByte = 0;
  }

  // Slice off any superfluous bytes, that is, ones that add no meaningful
  // bits (because the value would be the same if they were removed).
  while (
    byteLength > 1 &&
    result[byteLength - 1] === signByte &&
    (!signed || result[byteLength - 2] >> 7 === signBit)
  ) {
    byteLength--;
  }
  result = bufs.resize(result, byteLength);

  return { value: result, nextIndex: index };
}
938663
def signal_to_exception(signum, frame):
    
    if signum == signal.SIGALRM:
        raise SIGALRMException()
    if signum == signal.SIGHUP:
        raise SIGHUPException()
    if signum == signal.SIGUSR1:
        raise SIGUSR1Exception()
    if signum == signal.SIGUSR2:
        raise SIGUSR2Exception()
    raise SignalException(signum)
542438
def _prepare(self, serialized_obj):
        '''
        
        '''
        # generating a nonce
        nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE)
        # encrypting using the nonce
        encrypted = self.__safe.encrypt(serialized_obj, nonce)
        # sign the message
        signed = self.__signing_key.sign(encrypted)
        return signed
755118
@Override
    protected CBORObject EncodeCBORObject() throws CoseException {
        if (rgbSignature == null) throw new CoseException("sign function not called");
        if (rgbProtected == null) throw new CoseException("Internal Error");
        
        CBORObject obj = CBORObject.NewArray();
        obj.Add(rgbProtected);        
        obj.Add(objUnprotected);
        if (emitContent) obj.Add(rgbContent);
        else obj.Add(null);
        obj.Add(rgbSignature);
        
        return obj;
    }
881744
@Override
  public byte[] encode(final NetworkConnectionServiceMessage obj) {
    final Codec codec = connFactoryMap.get(obj.getConnectionFactoryId()).getCodec();
    Boolean isStreamingCodec = isStreamingCodecMap.get(codec);
    if (isStreamingCodec == null) {
      isStreamingCodec = codec instanceof StreamingCodec;
      isStreamingCodecMap.putIfAbsent(codec, isStreamingCodec);
    }

    try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
      try (final DataOutputStream daos = new DataOutputStream(baos)) {
        daos.writeUTF(obj.getConnectionFactoryId());
        daos.writeUTF(obj.getSrcId().toString());
        daos.writeUTF(obj.getDestId().toString());
        daos.writeInt(obj.getData().size());

        if (isStreamingCodec) {
          for (final Object rec : obj.getData()) {
            ((StreamingCodec) codec).encodeToStream(rec, daos);
          }
        } else {
          final Iterable dataList = obj.getData();
          for (final Object message : dataList) {
            final byte[] bytes = codec.encode(message);
            daos.writeInt(bytes.length);
            daos.write(bytes);
          }
        }
        return baos.toByteArray();
      }
    } catch (final IOException e) {
      throw new RuntimeException("IOException", e);
    }
  }
943706
final JsJmsMessage createInboundJmsMessage(JsMsgObject jmo, int messageType) {

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())SibTr.entry(tc, "createInboundJmsMessage " + messageType );

    JsJmsMessage jmsMessage = null;

    switch (messageType) {

      case JmsBodyType.BYTES_INT:
        jmsMessage = new JsJmsBytesMessageImpl(jmo);
        break;

      case JmsBodyType.MAP_INT:
        jmsMessage = new JsJmsMapMessageImpl(jmo);
        break;

      case JmsBodyType.OBJECT_INT:
        jmsMessage = new JsJmsObjectMessageImpl(jmo);
        break;

      case JmsBodyType.STREAM_INT:
        jmsMessage = new JsJmsStreamMessageImpl(jmo);
        break;

      case JmsBodyType.TEXT_INT:
        jmsMessage = new JsJmsTextMessageImpl(jmo);
        break;

      default:
        jmsMessage = new JsJmsMessageImpl(jmo);
    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())SibTr.exit(tc, "createInboundJmsMessage");
    return jmsMessage;
  }
57965
public static Signer updateDEREncodedObject(Signer signer, ASN1Encodable tbsObj)
        throws IOException
    {
        OutputStream sOut = signer.getOutputStream();
        DEROutputStream dOut = new DEROutputStream(sOut);

        dOut.writeObject(tbsObj);

        sOut.close();

        return signer;
    }
382557
async def sign_data(self, msg: bytes) -> bytes:
        

        def transform_cb(arr_ptr: POINTER(c_uint8), arr_len: c_uint32):
            return bytes(arr_ptr[:arr_len]),

        if not hasattr(Connection.sign_data, "cb"):
            self.logger.debug("vcx_connection_sign_data: Creating callback")
            Connection.sign_data.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32, POINTER(c_uint8), c_uint32), transform_cb)

        c_connection_handle = c_uint32(self.handle)
        c_msg_len = c_uint32(len(msg))

        result = await do_call('vcx_connection_sign_data',
                               c_connection_handle,
                               msg,
                               c_msg_len,
                               Connection.sign_data.cb)

        self.logger.debug("vcx_connection_sign_data completed")
        return result
593186
@Override
    public void visitCode(Code obj) {
        stack.resetForMethodEntry(this);
        Method m = getMethod();
        if (Values.CONSTRUCTOR.equals(m.getName())) {
            for (String parmSig : SignatureUtils.getParameterSignatures(m.getSignature())) {
                if (SignatureUtils.classToSignature(SLF4J_LOGGER).equals(parmSig) || SignatureUtils.classToSignature(LOG4J_LOGGER).equals(parmSig)
                        || SignatureUtils.classToSignature(LOG4J2_LOGGER).equals(parmSig) || SignatureUtils.classToSignature(COMMONS_LOGGER).equals(parmSig)) {
                    bugReporter.reportBug(new BugInstance(this, BugType.LO_SUSPECT_LOG_PARAMETER.name(), NORMAL_PRIORITY).addClass(this).addMethod(this));
                }
            }
        }

        isStaticInitializer = Values.STATIC_INITIALIZER.equals(m.getName());
        super.visitCode(obj);
    }
43513
@Override
    protected CBORObject EncodeCBORObject() throws CoseException {
        sign();
        
        CBORObject obj = CBORObject.NewArray();
        
        obj.Add(rgbProtected);
        obj.Add(objUnprotected);
        if (emitContent) obj.Add(rgbContent);
        else obj.Add(null);
        CBORObject signers = CBORObject.NewArray();
        obj.Add(signers);
        
        for (Signer r : signerList) {
            signers.Add(r.EncodeToCBORObject());
        }
        
        return obj;
    }
1086201
function _signerFromAsn1(obj) {
  // validate EnvelopedData content block and capture data
  var capture = {};
  var errors = [];
  if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) {
    var error = new Error('Cannot read PKCS#7 SignerInfo. ' +
      'ASN.1 object is not an PKCS#7 SignerInfo.');
    error.errors = errors;
    throw error;
  }

  var rval = {
    version: capture.version.charCodeAt(0),
    issuer: forge.pki.RDNAttributesAsArray(capture.issuer),
    serialNumber: forge.util.createBuffer(capture.serial).toHex(),
    digestAlgorithm: asn1.derToOid(capture.digestAlgorithm),
    signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm),
    signature: capture.signature,
    authenticatedAttributes: [],
    unauthenticatedAttributes: []
  };

  // TODO: convert attributes
  var authenticatedAttributes = capture.authenticatedAttributes || [];
  var unauthenticatedAttributes = capture.unauthenticatedAttributes || [];

  return rval;
}
848675
public static void registerSigner(
            final String signerType,
            final Class<? extends Signer> signerClass) {

        if (signerType == null) {
            throw new IllegalArgumentException("signerType cannot be null");
        }
        if (signerClass == null) {
            throw new IllegalArgumentException("signerClass cannot be null");
        }

        SIGNERS.put(signerType, signerClass);
    }
603766
def _sign_single(self, payload, signing_key):
        
        if not isinstance(payload, Mapping):
            raise TypeError('Expecting a mapping object, as only '
                            'JSON objects can be used as payloads.')

        token_segments = []

        signing_key = load_signing_key(signing_key, self.crypto_backend)

        header = self._make_header()
        header_b64 = base64url_encode(json_encode(header))
        payload_b64 = base64url_encode(json_encode(payload))
        signature_b64 = self._make_signature(header_b64, payload_b64, signing_key)

        token_segments = [header_b64, payload_b64, signature_b64]

        # combine the header, payload, and signature into a token and return it
        token = b'.'.join(token_segments)
        return token