Thursday, 19 August 2021

Balanced Parentheses

 package demoTest;


import java.util.Stack;


public class test {

    // Function to check if the given expression is balanced or not

    public static boolean balParenthesis(String exp)

    {

        // base case: length of the expression must be even

        if (exp.length() % 2 == 1) {

            return false;

        }

 

        // take an empty stack of characters

        Stack<Character> stack = new Stack();

 

        // traverse the input expression

        for (char ch: exp.toCharArray())

        {

            // if the current character in the expression is an opening brace,

            // push the corresponding closing brace into the stack.

            if (ch == '(') {

                stack.push(')');

            }

            else if (ch == '{') {

                stack.push('}');

            }

            else if (ch == '[') {

                stack.push(']');

            }

 

            // return false if the popped character is not the same as the

            // current character

            else if (stack.isEmpty() || stack.pop() != ch) {

                return false;

            }

        }

 

        // the expression is balanced only when the stack is empty at this point

        return stack.empty();

    }

 

    public static void main(String[] args)

    {

        String exp = "{([)}[{}]";

 

        if (balParenthesis(exp)) {

            System.out.println("The expression is balanced");

        }

        else {

            System.out.println("The expression is not balanced");

        }

    }

}



Sort 0s, 1s, 2s

 package demoTest;


public class Array1 {

public static void main(String[] args) {

// TODO Auto-generated method stub

int arr[] = new int[] {1, 0, 2, 2, 0, 1, 2, 0, 0, 2, 1, 0, 2, 0, 1, 0, 0, 2, 0, 1};

 

int n = arr.length;

 

//output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]

int count0 = 0;

int count1 =0;

int count2 =0;

for(int i =0; i<n; i++) {

if(arr[i]== 0) {

count0 ++;

}

else if(arr[i]== 1) {

count1 ++;

}

}

int l1 = count0+ count1;

count2 = n - ( count0 + count1);

for(int i = 0; i< count0; i++) {

arr[i]=0;

}

for(int i = count0; i< l1; i++) {

arr[i]=1;

}

for(int i = l1; i< n; i++) {

arr[i]=2;

}

for(int i = 0; i< n; i++) {

System.out.print(arr[i] + " ");

}

}

}
























     


Wednesday, 18 August 2021

Java program to print all permutations of a given string

 // Java program to print all permutations of a

// given string.

public class Permutation {

public static void main(String[] args)

{

String str = "ABC";

int n = str.length();

Permutation permutation = new Permutation();

permutation.permute(str, 0, n - 1);

}


/**

* permutation function

* @param str string to calculate permutation for

* @param l starting index

* @param r end index

*/

private void permute(String str, int l, int r)

{

if (l == r)

System.out.println(str);

else {

for (int i = l; i <= r; i++) {

str = swap(str, l, i);

permute(str, l + 1, r);

str = swap(str, l, i);

}

}

}


/**

* Swap Characters at position

* @param a string value

* @param i position 1

* @param j position 2

* @return swapped string

*/

public String swap(String a, int i, int j)

{

char temp;

char[] charArray = a.toCharArray();

temp = charArray[i];

charArray[i] = charArray[j];

charArray[j] = temp;

return String.valueOf(charArray);

}

}




Monday, 16 August 2021

Convert MyArrayList to a arraylist

Find the number of subsets whose product of elements is less than or equal to a given integer K

Given an array arr[] of N elements. Find the number of subsets whose product of elements is less than or equal to a given integer K.

 

Example 1:

Input:
N = 4
arr[] = {2, 4, 5, 3}
K = 12
Output:
8
Explanation:
All possible subsets whose 
products are less than 12 are:
(2), (4), (5), (3), (2, 4), (2, 5), (2, 3), (4, 3)

# Python3 to find the count subset
# having product less than k
import bisect

def findSubset(arr, n, k):

# declare four vector for dividing
# array into two halves and storing
# product value of possible subsets
# for them
vect1, vect2, subset1, subset2 = [], [], [], []

# ignore element greater than k and
# divide array into 2 halves
for i in range(0, n):

# ignore element if greater than k
if arr[i] > k:
continue
if i <= n // 2:
vect1.append(arr[i])
else:
vect2.append(arr[i])

# generate all subsets for 1st half (vect1)
for i in range(0, (1 << len(vect1))):
value = 1
for j in range(0, len(vect1)):
if i & (1 << j):
value *= vect1[j]

# push only in case subset product
# is less than equal to k
if value <= k:
subset1.append(value)

# generate all subsets for 2nd half (vect2)
for i in range(0, (1 << len(vect2))):
value = 1
for j in range(0, len(vect2)):
if i & (1 << j):
value *= vect2[j]

# push only in case subset product
# is less than equal to k
if value <= k:
subset2.append(value)

# sort subset2
subset2.sort()

count = 0
for i in range(0, len(subset1)):
count += bisect.bisect(subset2, (k // subset1[i]))

# for null subset decrement the
# value of count
count -= 1

# return count
return count

# Driver Code
if __name__ == "__main__":

arr = [4, 2, 3, 6, 5]
n = len(arr)
k = 25
print(findSubset(arr, n, k))



Saturday, 14 August 2021

API Academy API Security Architect Certification exam answers

 Question 1 out of 25:

Evaluate the following statement. The UserInfo endpoint is an OAuth 2.0 protected resource that lives in the authorization server.

  • TRUE
  • FALSE

Question 2 out of 25:

Which of the following is part of JWT best practices?

  • Never letting the header alone drive verification
  • All options are correct
  • Setting a shorter timeout
  • Using claims to the fullest extent

Question 3 out of 25:

Which statement about OAuth 2.0 is correct? (Select all that apply)

  • OAuth 2.0 has a reputation to be complicated and difficult to implement, not only because of the various grant types but also because the specification itself is less prescriptive.
  • OAuth 2.0 authentication was designed to address vulnerabilities in OpenID Connect authorization protocol.
  • The OAuth 2.0 core framework has not really been evolving as contributors are not allowed to publish additional specifications.
  • Like other open-source frameworks of similar scale and magnitude, a long list of RFC specifications makes OAuth 2.0 potentially overwhelming.

Question 4 out of 25:

Match the authorization grant types supported by OAuth 2.0 with the correct statement:

Authorization code

The resource owner's credentials are never shared with the client application and the resource server. The access token is never shared with the resource owner. It is the most secure and most common grant type today.

Implicit

The client is issued an access token directly. No intermediate credentials (such as an authorization code) are issued. The authorization server does not authenticate the client.

Resource owner password credentials

This grant type should only be used when there is a high degree of trust between the resource owner and the client, such as if the resource owner is the sole owner or operator of the device. Given the nature of this grant type, the ability of a person to impersonate the resource owner is highly likely, making it incredibly easy for hackers to have complete access. Use this type only when other authorization grant types are not available.

Client credentials

This grant type is typically used when the client is acting on its own behalf or is requesting access based on a previously arranged authorization. Example use cases are typically for non-interactive applications such as a Command Line Interface, a daemon, or any service running in a backend server that doesn’t require any interaction with the end user. Many IoT devices also fall into this category. In all these examples, the client application would request and receive the access token without the user having any access to the protected resources.

Question 5 out of 25:

The industry standard authorization protocol that permits a user to grant an application access to a protected resource without exposing the user’s password credentials is called:

  • Access Token
  • OAuth 2.0
  • OpenID 2.0
  • OpenID Connect

Question 6 out of 25:

Evaluate the following statement. APIs give client-side developers (and potential hackers) much more finely-grained access into the backend than a typical website or application does.

  • TRUE
  • FALSE

Question 7 out of 25:

Evaluate the following definition.

This implementation can help address the threat of redirect hijacks. In this implementation, the client generates a hashed secret and hashing method and sends them to the authorization server on code request. The secret is then used by the authorization server to verify a subsequent token request. As it requires both the client and server to participate, it helps address vulnerabilities, particularly in mobile apps.

What implementation are we talking about?

  • URL redirect
  • Access and refresh tokens
  • A proof key for code exchange (PKCE)
  • Cross-Origin Resource Sharing (CORS)

Question 8 out of 25:

Evaluate the following statement. As long as your API is considered private and only used by your direct applications, you do not need to add extra security because no one will be aware of your API.

  • TRUE
  • FALSE

Question 9 out of 25:

  • When a token is stolen, it makes the system vulnerable to:
  • Certificate pinning
  • Cross-site scripting and denial of service attacks
  • Attackers phishing for credentials using a compromised or embedded browser
  • Man-in-the-middle and man-in-the-browser attacks

Question 10 out of 25:

Which statement about OpenID Connect is correct?

  • All options are correct
  • The OpenID Connect protocol is an extension of OAuth 2.0 that is filling in the authentication gaps within OAuth 2.0, such as better enabling SSO.
  • Within the Authorization flow, if “openid” is included as the scope, an additional ID Token is generated along with the Access Token.
  • The ID Token acts like an encrypted fingerprint that travels through the flow with the access token.

Question 11 out of 25:

Match the examples of threat models that correspond with the OAuth 2.0 components:

Attackers obtaining client secrets. Attackers phishing for credentials using compromised or embedded browser. Open redirection on the client side.

Client threats

Phishing by counterfeit authorization server. Interception of traffic to resource server.

Endpoint threats

Token theft. Disclosure of client credentials during token transmission. Obtaining client secrets from either the database or through guesswork.

Token threats

Question 12 out of 25:

Match the following statements:

The OAuth 2.0 protocol...

...excels at delegated authorization.

Scope, a mechanism in OAuth 2.0...

...is designed to limit an application's access to a resource such as user's data.

The client ID...

...is a public identifier for apps and is typically encoded in a multi-character hex string.

The authorization code...

...is not enough for the client application to fetch the requested resources from the resource server and is subsequently exchanged for an access token.

Question 13 out of 25:

Match the following statements:

TLS (Transport Layer Security) and SSL (Secure Sockets Layer)...

...are cryptographic protocols that help you keep the internet connection and transfer of data secure.

Rate limiting, Message validation, Encryption and signing and Access control...

...are standard security functions from the API gateway world that are important when it comes to protecting the APIs and mitigating API threats.

HTTP access control...

...provides an access authentication feature and allows servers to challenge clients and reject unauthorized access.

TLS trust attacks...

...can be divided into three categories - certificate authority vulnerabilities, human vulnerabilities and man in the middle issues.

Question 14 out of 25:

Evaluate the following statement. OAuth 2.0 alone as a framework is no longer sufficient, and this is why OpenID Connect has become more relevant than ever before, as it offers a standardized and prescriptive method for delegated authentication.

  • FALSE
  • TRUE

Question 15 out of 25:

One consideration to mitigate client threats is through Application Access Control. The principles of application access control are (select all that apply):

  • Establish credentials with a handshake or registration during client installation, instead of hosting the secrets in code.
  • Do NOT move the credentials to a server
  • Consistently implement monitoring and detection
  • Move the credentials to a server

Question 16 out of 25:

In a stateless token scenario, sort the following steps in the order they will be happening. After the client starts the OAuth 2.0 authorization process...

  1. The authorization server validates the client’s request and generates a JWT (which it encrypts and signs using a private key).
  2. The authorization server returns the JWT to the client.
  3. The client makes a request to the resource server with the JWT and the server must validate the token with its private key.
  4. The server's protected routes will check for a valid JWT in the Authorization header, and if it is present, the client will be allowed to access protected resources.

Question 17 out of 25:

Evaluate the following statement. With stateless tokens becoming more widely adopted, OAuth 2.0 is increasingly relying on security embedded within the token itself. While TLS provides an extra layer of security, token theft is still possible.

  • TRUE
  • FALSE

Question 18 out of 25:

POODLE, BEAST, CRIME, BREACH, and HEARTBLEED are:

  • Historical vulnerabilities related to TLS/SSL protocols
  • Authorization and authentication features
  • Cryptographic protocols that help you keep the internet connection and transfer of data secure
  • The most typical components in the API security domain

Question 19 out of 25:

Match the following token types with the correct statements:

ID Token

...contains claims about authentication status of an end user, and indicates the status of the authentication.

Access Token

....indicates the status of authorization. It can be used by a client to retrieve additional user information, but is not intended to carry information about the user.

Refresh Token

...is used to get a new access token once the previous token has expired.

JSON Web Token

...is a signed and/or encrypted, stateless and self-contained token format, carrying all the necessary information within their header, payload, and signature.

Question 20 out of 25:

Which of these characteristics is an advantage of JSON Web Tokens? (Select all that apply)

  • JWT is stateless.
  • JWT is stateful.
  • As a versatile token format, JWT's usage spans across the OAuth 2.0 and OpenID Connect workflow: It can be used as a format for ID tokens, access tokens, and refresh tokens.
  • JWT is programming language-agnostic.
  • JWT is checked against the token registry on the authorization server.

Question 21 out of 25:

Which statement about APIs is correct? (Select all that apply)

  • APIs DO NOT share any underlying technologies with traditional browser-centric web applications.
  • For APIs, we CANNOT rely on the same security methods and technologies that we use to secure the browser-centric web applications.
  • Well-designed APIs are, by nature, more transparent than websites and therefore more vulnerable.
  • APIs are fundamentally different from the traditional browser-centric web and therefore have a unique risk profile.

Question 22 out of 25:

Which statement about JSON Web Tokens is correct? (Select all that apply)

  • Higher verbosity is a characteristic that encourages usage of JWT tokens.
  • JWT is a token format, an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.
  • Every JSON Web Token comprises three elements - header, payload and signature.
  • JWT is NOT part of the Javascript Object Signing and Encryption framework.

Question 23 out of 25:

Evaluate the following definition.

It is an extension of OAuth 2.0 and works not only to eliminate OAuth 2.0 vulnerabilities, but also to fill authentication gaps within OAuth 2.0, such as better enabling SSO. Within the authorization flow, an additional ID token acts as an encrypted fingerprint that travels through the flow with the access token. At the API endpoint, it can be decoded to reveal user information for identity verification.

What is being described?

  • OpenID Connect protocol
  • TLS / SSL protocol
  • HTTP Access Control
  • Implicit grant type

Question 24 out of 25:

One of the threats to the authorization server involves redirection hijack. Which statement about redirection hijack is true?

  • A good consideration to address redirect hijack is to implement a proof key for code exchange (PKCE).
  • The redirection hijack happens once authorization has been granted with either an authorization code or implicit grant type. Instead of redirecting back to the client, the authorization server is fooled into redirecting to somewhere other than the client.
  • All options are correct
  • One way to mitigate the risk of redirection hijack is to whitelist the redirect URIs on the authorization server.

Question 25 out of 25:

In an OAuth 2.0 Authorization flow, where Joe is the resource owner who wants to use a third-party application to access his banking information, sort the following steps in the flow in the order they will be happening:

  • Joe logs into a third-party application and wishes to access his banking information from the application.
  • The third-party application sends an authorization request to the bank’s authorization server. It redirects Joe's browser to the login screen of the authorization server.
  • The authorization server asks Joe to authorize the third-party application's access to his banking information.
  • Joe grants or denies the third-party application's access to the banking information.

API PRODUCT MANAGER - Certification API Academy

 Question 1 out of 26:

Design-time for APIs is described as a business relationship between several entities that enable the building of an application with a technical specification that is acceptable to all parties. One entity is described as the technical contract creator, the second entity as the business contract, and the third entity as the one that accepts the terms of that contract. Which entities are involved in this relationship? Select all that apply. 

  • API Scrummaster
  • API Owner
  • API Consumer (developer)
  • API Plans

Question 2 out of 26:

Evaluate the following statement.

APIs benefit from a repeatable build and deployment process.

  • FALSE
  • TRUE

Question 3 out of 26:

Select all that apply.

The use of snippets when creating API usage examples...

 

  • Show request and response
  • Uses familiar programming language(s)
  • Demonstrate a small part of the API
  • Are located in close proximity to the information being demonstrated

Question 4 out of 26:

Evaluate the following statement.

Run-time costs will continue to lower regardless of the API consumption whereas design-time costs will rise given the amount of API consumption.

  • FALSE
  • TRUE

Question 5 out of 26:

Select the best answer. 

Which of the following is currently the biggest security threat to your APIs and resources that an effective API monitoring system can help mitigate?  

  • Distributed Denial of Service (DDoS)
  • Phishing
  • Man-in-the-Middle
  • SQL injection

Question 6 out of 26:

Select all that apply. 

Which of the following are benefits of Hybrid API Management?

  • Integration with individual IT assets
  • Fast time to market
  • Optimization for performance
  • Micro-services enablement

Question 7 out of 26:

Evaluate the following statement.

APIs rarely change after they are deployed - and if even an update is required for maintenance, the risk of breaking changes is fairly low.

  • TRUE
  • FALSE

Question 8 out of 26:

Select the best answer.

Which of the following is presently the most popular API definition format and is typically written in YAML or JSON? 

  • Blueprint
  • RAML
  • Open API
  • WADL


Question 9 out of 26:

Select the best answer.

Which of the following processes or concepts is NOT part of the DevOps model? 

  • Continuous Change
  • Continuous Delivery
  • Continuous Testing
  • Continuous Monitoring
  • Continuous Integration
  • Continuous Deployment

Question 10 out of 26:

Select the best answer to fill in the blank.

By integrating ____________ in both testing and operations, you'll be able to find issues before they reach production when deploying APIs.

  • Scalability
  • Availability
  • Automation
  • Evolvability

Question 11 out of 26:

Select the best answer.

This technique monitors and controls the usage of your APIs by end-users and protects valuable systems from exceeding system and application limitations. 

  • Traffic scaling
  • Throttling
  • Traffic filtering
  • Metering

Question 12 out of 26:

Select the best answer.

When designing a visual and writing style for your API documentation for human consumption, the end result should create

  • Desirability of the API product
  • Neither desirability nor credibility of the API product
  • Credibility of the API product
  • Both desirability and credibility of the API product

Question 13 out of 26:

Select all that apply.

Which of the following are significant components of an API product?

  • Visibility
  • Engagement
  • Analytics
  • Learning Aides
  • Interface
  • Usability Aides

Question 14 out of 26:

Select the best answer to fill in the blank. 

APIs should be _____________ if they provide a unique business value to prevent unauthorized use by competitors.

  • Secured
  • Copyrighted
  • Productized
  • JSON formatted

Question 15 out of 26:

Evaluate the following statement.

Documentation is the key to a great experience when consuming your API. It not only enables consumer satisfaction but also allows your API adoption to increase.

  • FALSE
  • TRUE

Question 16 out of 26:

Select all that apply.

What should your API monitoring strategy cover? 

  • SLA
  • Availability
  • Security
  • Benchmarking

Question 17 out of 26:

Evaluate the following statement. 

Private APIs may be distributed publicly but the interface itself is not public.

  • TRUE
  • FALSE

Question 18 out of 26:

Evaluate the following statement. 

APIs eventually need to be retired, replacing product as part of the overall lifecycle. 

  • TRUE
  • FALSE

Question 19 out of 26:

Select all that apply.

In order for your API deployment infrastructure to scale and evolve, you can

  • Use microservices to quicken API development
  • Automate change management for API policies
  • Eliminate traditional IT roles
  • Leverage existing assets in an API
  • Provide continuous monitoring

Question 20 out of 26:

Select all that apply.

Which of the following are key capabilities of an API Management platform? 

  • To unlock the value of customer data
  • The ability to integrate and create APIs
  • To accelerate mobile and loT development
  • The ability to secure the Open Enterprise
  • To decrease the variable cost ratio for API creation

Question 21 out of 26:

Select all that apply.

Besides checking for unreachable or non-responsive APIs, what other issues can API monitoring detect? 

  • Increased latency
  • Authentication and authorization errors
  • Non-200 response codes
  • Improperly formatted data
  • Metadata errors

Question 22 out of 26:

Select the level that best applies.

According to the API Documentation Maturity model, this level is best described as "Bespoke Documentation" in which its content can readily change based on user context. 

  • Level 3 Conceptual
  • Level 5 Predictive and Adaptive
  • Level 2 Examples
  • Level 4 Interactive
  • Level 1 Reference

Question 23 out of 26:

Select the best answer.

An API program must be able to attract external developers to help them build applications that consumers actually want to use. The key goal for business/product managers and interface designers should be to:

  • Increase the quantity of API usage.
  • None of the above
  • Increase the quality of API usage.
  • Increase the quantity and quality of API usage.

Question 24 out of 26:

Select the best answer.

Logs from API monitoring can be exported to this type of solution/application to detect analogous behaviour from external actors or analyze security threats.

  • Security, Orchestration, Automation, and Response (SOAR) platform
  • Case Management system
  • Security Information and Event Management (SIEM) platform
  • Incident Response (IR) system

Question 25 out of 26:

Which of the following products can provide live runtime capability, manage API traffic, and enforce API security? 

  • API Portal
  • Customer Management System
  • Central API Unit
  • API Gateway

Question 26 out of 26:

Match the following statements.

For high availability, so that every API request can be met with a response, you'll need