Zephir Returned values by functions can only be assigned to variant variables - zephir

So, i want to make an PHP extension by Zephir that can encrypt and encode a source code, but i have an error which is :
Error Message:
[ERROR] Returned values by functions can only be assigned to variant variables in
/home/ubuntu/ta/utils/utils/Cryptix.zep on line 15
Script zephir handling the __exec_command event returned with error code 1
Here is the Code:
Cryptix.zep
namespace Utils;
class Cryptix
{
/**
*
*
* #param string type
* #param string file
*
*/
public function encryptFile(type, file)
{
string code = file_get_contents(file, true);
string enc_code = "<?php Utils::decode('"+type+"', '"+openssl_enc(type, code)+"'); ?>";
file_put_contents(file + ".original", code);
file_put_contents(file, enc_code);
}
public function openssl_enc(string method, string data)
{
string firstkey = "Lk5Uz3slx3BrAghS1aaW5AYgWZRV0tIX5eI0yPchFz4=";
string secondkey = "EZ44mFi3TlAey1b2w4Y7lVDuqO+SRxGXsa7nctnr/JmMrA2vN6EJhrvdVZbxaQs5jpSe34X3ejFK/o9+Y5c83w==";
string first_key = base64_decode(firstkey);
string second_key = base64_decode(secondkey);
string iv_length = openssl_cipher_iv_length(method);
string iv = openssl_random_pseudo_bytes(iv_length);
string first_encrypted = openssl_encrypt(data, method, first_key, OPENSSL_RAW_DATA, iv);
string second_encrypted = hash_hmac("sha3-512", first_encrypted, second_key, true);
string output = base64_encode(iv + second_encrypted + first_encrypted);
return output;
}
}
what should i do to fix this error? thank you so much for your help.

Related

Getting the last message on a Gmail message thread in Katalon Studio

I'm using this plugin for Katalon Studio to access the last unread message from my testing Gmail account.
My email util class is like:
public final class SMDEmailUtils {
public static final String MainInboxFolder = "INBOX";
public static final String SpamFolder = "[Gmail]/Spam";
public static String GetMainEmail() {
if (!GeneralWebUIUtils.GlobalVariableExists('emailID'))
return "dev#example.com";
return GlobalVariable.emailID.toString();
}
public static String ExtractSignUpLink() {
final String folderName = this.GetNewMessageFolderName(30, FailureHandling.STOP_ON_FAILURE);
return this.ProcessHTML(this.GetNewMessage(folderName), "//a[.//div[#class = 'sign-mail-btn-text']]/#href");
}
public static String GetNewMessageFolderName(int timeOut,
FailureHandling failureHandling = FailureHandling.STOP_ON_FAILURE) {
final long startTime = System.currentTimeMillis()
final Map<String, Integer> folderMessageCountDict = [
(this.MainInboxFolder) : this.GetMessageCount(this.MainInboxFolder),
(this.SpamFolder) : this.GetMessageCount(this.SpamFolder),
];
while (System.currentTimeMillis() < startTime + 1000 * timeOut) {
final String folderName = folderMessageCountDict.findResult({String folderName, int initialMessageCount ->
if (initialMessageCount < this.GetMessageCount(folderName))
return folderName;
return null;
})
if (folderName != null)
return folderName;
// TODO: we shouldn't have to do some hard-coded suspension of the runtime. We need to close the store somehow
Thread.sleep(1000 * 2);
}
throw new StepFailedException("Failed to find a folder with a new message in it after ${(System.currentTimeMillis() - startTime) / 1000} seconds");
}
public static int GetMessageCount(String folderName) {
return Gmail.getEmailsCount(this.GetMainEmail(), GlobalVariable.emailPassword, folderName);
}
public static String GetNewMessage(String folderName) {
return Gmail.readLatestEMailBodyContent(this.GetMainEmail(), GlobalVariable.emailPassword, folderName);
}
/**
* **NOTE**: forked from https://stackoverflow.com/a/2269464/2027839 , and then refactored
*
* Processes HTML, using XPath
*
* #param html
* #param xpath
* #return the result
*/
public static String ProcessHTML(String html, String xpath) {
final String properHTML = this.ToProperHTML(html);
final Element document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(new ByteArrayInputStream( properHTML.bytes ))
.documentElement;
return XPathFactory.newInstance()
.newXPath()
.evaluate( xpath, document );
}
private static String ToProperHTML(String html) {
// SOURCE: https://stackoverflow.com/a/19125599/2027839
String properHTML = html.replaceAll( "(&(?!amp;))", "&" );
if (properHTML.contains('<!DOCTYPE html'))
return properHTML;
return """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head></head>
<body>
${properHTML}
</body>
</html>
""";
}
}
My use case of that is the following:
a test member lead, whose email forwards to my testing email ([myTestingEmailName]+[memberLeadName]#gmail.com), gets a link to an agreement to sign
on successful signature, the physician, whose email also forwards to my testing email ([myTestingEmailName]+[physicianName]#gmail.com), gets a link to an agreement to sign
Step 1 works, the link gets extracted successfully via SMDEmailUtils.ExtractSignUpLink() .
However, when it is the physician's turn to sign, that same line of code doesn't work. It's giving me the link from the first email message (the one meant for the recipient in step 1, that was already signed).
I check out my inbox manually, and see this:
The AUT sent both email messages on the same thread, but the plugin can only handle the first message on the thread!
How do I handle this?

JWT signature different from expected [duplicate]

I wrote a method that takes a JWT as a request and checks if the signature is valid.
This is the unit test:
#Test
public void isValid() {
final JwtValidator jwtValidator = JwtValidator.getInstance();
final boolean valid = jwtValidator.isValid("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c");
Assert.isTrue(valid);
}
and this is the code:
#SneakyThrows
public boolean isValid(String extractedToken) {
final String[] tokenParts = extractedToken.split(Pattern.quote("."));
String header = tokenParts[0];
String payload = tokenParts[1];
String signature = tokenParts[2];
final byte[] calcHmacSha256 = HMAC.calcHmacSha256("your-256-bit-secret".getBytes(), (header+"."+payload).getBytes());
final String s = Base64.getEncoder().encodeToString(calcHmacSha256);
System.out.println("'" + signature + "'.equals('"+s+"')");
return signature.equals(s);
}
The log prints two strings that differ only for 2 chars, so I feel like I'm close "but not quite" to make it work:
'SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'.equals('SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV/adQssw5c=')
There are of course hard coded values because the implementation isn't complete, but I'm using the example values in https://jwt.io/ for ease of use right now.
Thanks!
EDIT 1:
public class JwtValidatorTest {
#Test
public void isValid() {
byte[] header64 = Base64.getEncoder().encode("{\"alg\":\"HS256\",\"typ\":\"JWT\"}".getBytes());
byte[] payload64 = Base64.getEncoder().encode("{\"sub\":\"1234567890\",\"name\":\"John Doe\",\"iat\":1516239022}".getBytes());
final byte[] calcHmacSha256 = HMAC.calcHmacSha256("your-256-bit-secret".getBytes(), (header64+"."+payload64).getBytes());
final String signature64 = Base64.getEncoder().encodeToString(calcHmacSha256);
final String input = header64 + "." + payload64 + "." + signature64;
final JwtValidator jwtValidator = JwtValidator.getInstance();
final boolean valid = jwtValidator.isValid(input);
Assert.isTrue(valid);
}
}
The difference is just caused by the different encoding used here. You used Base64 encoding, but the original signature is Base64Url encoded. Base64Url encoding is, according to RFC7519, the standard encoding for JWT:
Each part contains a base64url-encoded value
Base64Url encoding has no padding (=) on the end and the characters + and / are replaced with -and _.
This code should solve the problem:
final String s = Base64.getUrlEncoder().withoutPadding().encodeToString(calcHmacSha256);

Invalid procedure call or argument in vbscript while calling com member function

I have a c# dll registered in regasm.exe and I am trying to call it on my classic asp application below is my code part:
I am sending a dictionary object as parameter to the function
Dim parameters
Set parameters=Server.CreateObject("Scripting.Dictionary")
For Each Item1 In Request.Form
fieldName = Item1
fieldValue = Request.Form(Item1)
parameters.Add fieldName, fieldValue
Next
Here is where I am calling the function
Set CudExternal=Server.Createobject("CudExternal.Security")
Set signature = CudExternal.sign(parameters)
When I try to call the function I am getting this error.
Below is my dll code:
public class Security
{
private const String SECRET_KEY = "dd6b7d26fb0c4db7891b28718a1a468";
public string sign(IDictionary<string, string> paramsArray)
{
return sign(buildDataToSign(paramsArray), SECRET_KEY);
}
private string sign(String data, String secretKey)
{
UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] keyByte = encoding.GetBytes(secretKey);
HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);
byte[] messageBytes = encoding.GetBytes(data);
return Convert.ToBase64String(hmacsha256.ComputeHash(messageBytes));
}
private string buildDataToSign(IDictionary<string, string> paramsArray)
{
String[] signedFieldNames = paramsArray["signed_field_names"].Split(',');
IList<string> dataToSign = new List<string>();
foreach (String signedFieldName in signedFieldNames)
{
dataToSign.Add(signedFieldName + "=" + paramsArray[signedFieldName]);
}
return commaSeparate(dataToSign);
}
private string commaSeparate(IList<string> dataToSign)
{
return String.Join(",", dataToSign);
}
public string outputr(string data)
{
return data;
}
}
How can I Resolve??...Thanks in Advance.

returning a value using REST

I am getting errors when I am trying to return values using REST. The error is:
A HTTP GET method, public - should not consume any entity.
This is my class:
public class StockManagement {
ArrayList<String> items = new ArrayList<>();
ArrayList<Integer> stockLevel = new ArrayList<>();
#GET
#Produces("application/xml")
public String addItem(String item) {
if(items.contains(item)) { // returns true is item is exists else false
String r = "Item is already in list";
String result = "#Produces(\"application/xml\")" + r;
return "<StockManagementService>"+ "<div>" + result + "</div>" +"</StockManagementService>";
}
else {
String r = "Item has been added successfully";
String result = "#Produces(\"application/xml\")" + r;
items.add(item); // add item to inventory
stockLevel.add(0); // set the number of stock for the item in inventory
return "<StockManagementService>" +"<div>" + result + "</div>" +"</StockManagementService>";
}
}
#GET
#Produces("application/xml")
public String setStock(String item, int stockLevels) {
if(!items.contains(item)) {
String r = "Item is not in the inventory";
String result = "#Produces(\"application/xml\")" + r;
return "<StockManagementService>" + result + "</StockManagementService>";
}
else {
int index = items.indexOf(item);
stockLevel.set(index, stockLevels);
String r = "Set stock has been complete successfully";
String result = "#Produces(\"application/xml\")" + r;
return "<StockManagementService>" + result + "</StockManagementService>";
}
}
#GET
#Produces("application/xml")
public String addStock(String item, int numItem) {
if(!items.contains(item)) {
String r = "Error, Cannot add item";
String result = "#Produces(\"application/xml\")" + r;
return "<StockManagementService>" + result + "</StockManagementService>";
}
else {
int index = items.indexOf(item);
String r = "Successfully added stock";
String result = "#Produces(\"application/xml\")" + r;
return "<StockManagementService>" + result + "</StockManagementService>";
}
}
#GET
#Produces("application/xml")
public String removeStock(String item, int numItem) {
if(items.contains(item)) {
int index = items.indexOf(item);
int val = stockLevel.get(index);
val = val - numItem;
stockLevel.set(index, val);
String r = "Successfully removed item.";
String result = "#Produces(\"application/xml\")" + r;
return "<StockManagementService>" + result + "</StockManagementService>";
}
else {
String r = "Item is not in the inventory";
String result = "#Produces(\"application/xml\")" + r;
return "<StockManagementService>" + result + "</StockManagementService>";
}
}
This is the error shown on eclipse terminal:
SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
WARNING: A HTTP GET method, public java.lang.String com.crunchify.restjersey.StockManagement.setStock(java.lang.String,int), should not consume any entity.
WARNING: A HTTP GET method, public java.lang.String com.crunchify.restjersey.StockManagement.addStock(java.lang.String,int), should not consume any entity.
WARNING: A HTTP GET method, public java.lang.String com.crunchify.restjersey.StockManagement.removeStock(java.lang.String,int), should not consume any entity.
WARNING: A HTTP GET method, public java.lang.String com.crunchify.restjersey.StockManagement.addItem(java.lang.String), should not consume any entity.
SEVERE: Consuming media type conflict. The resource methods public java.lang.String com.crunchify.restjersey.StockManagement.addStock(java.lang.String,int) and public java.lang.String com.crunchify.restjersey.StockManagement.setStock(java.lang.String,int) can consume the same media type
SEVERE: Consuming media type conflict. The resource methods public java.lang.String com.crunchify.restjersey.StockManagement.removeStock(java.lang.String,int) and public java.lang.String com.crunchify.restjersey.StockManagement.setStock(java.lang.String,int) can consume the same media type
SEVERE: Consuming media type conflict. The resource methods public java.lang.String com.crunchify.restjersey.StockManagement.addItem(java.lang.String) and public java.lang.String com.crunchify.restjersey.StockManagement.setStock(java.lang.String,int) can consume the same media type
I cannot figure out what this error means, obviously it has to be the way I am returning, any help would be appreciated.
Thanks.
No promises, but I think the WARNING is trying to remind you that, in HTTP, GET doesn't take a message body. So String item should probably be encoded into the URI itself, which might mean a #QueryParam or #PathParam annotation.
SEVERE is trying to tell you that there are multiple methods that are all trying to be mapped to the same route. That is to say, they are all mapped to the same URI with the same method and the same application type, so how is the routing logic supposed to choose between them.
That might mean that you need to specify different paths for each, or that you should have only one annotated method that has the logic to choose which implementation to use.

Creating a Signed URL for Google Cloud Storage

We have an ERP application running on GCP .
For downloading data spanning more than three months or so ,we're uploading a file on GCS. Now i want to create a signed url so that to give limited access to the end users .
I have been trying this. But i get this error :
Signature does not match. Please check your Google secret key.
Can anyone tell how to go about this?
private static final int EXPIRATION_TIME = 5;
private static final String BASE_URL = "https://storage.googleapis.com";
private static final String httpVerb = "GET";
/*
* private static final String BUCKET = "my_bucket"; private static final String
* FOLDER = "folder";
*/
private final AppIdentityService identityService = AppIdentityServiceFactory.getAppIdentityService();
public String getSignedUrl(String bucket, final String fileName, String contentTpe) throws Exception {
final long expiration = expiration();
final String unsigned = stringToSign(bucket, expiration, fileName, contentTpe);
final String signature = sign(unsigned);
return new StringBuilder(BASE_URL).append("/").append(bucket).append("/").append(fileName)
.append("?GoogleAccessId=").append(clientId()).append("&Expires=").append(expiration)
.append("&Signature=").append(URLEncoder.encode(signature, "UTF-8")).toString();
}
private static long expiration() {
final long unitMil = 1000l;
final Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, EXPIRATION_TIME);
final long expiration = calendar.getTimeInMillis() / unitMil;
return expiration;
}
private String stringToSign(String bucket, final long expiration, String filename, String contentType) {
final String contentMD5 = "";
final String canonicalizedExtensionHeaders = "";
final String canonicalizedResource = "/" + bucket + "/" + filename;
final String stringToSign = httpVerb + "\n"+ contentMD5 + "\n" + contentType + "\n" + expiration + "\n"
+ canonicalizedExtensionHeaders + canonicalizedResource;
return stringToSign;
}
protected String sign(final String stringToSign) throws UnsupportedEncodingException {
final SigningResult signingResult = identityService.signForApp(stringToSign.getBytes());
final String encodedSignature = new String(Base64.encodeBase64(signingResult.getSignature()), "UTF-8");
return encodedSignature;
}
protected String clientId() {
return identityService.getServiceAccountName();
}
URL signing code is a bit tricky because by its nature it can be difficult to know what you've gotten wrong, other than just seeing that it's wrong. There are a few general tips that make it easier:
First, if possible, consider using URL signing functions in the google-cloud libraries. For example, the Java google-cloud library provides a Storage.signURL method, and you can use it like this:
URL signedUrl = storage.signUrl(
BlobInfo.newBuilder(bucketName, blobName).build(),
2, TimeUnit.DAYS);
Second, if you look at the error message, you'll notice that there's a <StringToSign> section. This section contains the exact string that GCS would calculate a signature for. Make sure that the string you're signing matches this string exactly. If it doesn't, that's your problem.
In your code's particular case, I didn't find the problem, but it might be that you're including a content-type line when signing the string, but GET requests don't provide a Content-Type header. It's just an idea, though, since I don't see your invocation of getSignedUrl.