Encryption vs Digital Signature

In Encryption we use receivers public key to encrypt the message whereas when we digitally sign we use senders private to encrypt the hashed text(which is nothing again message we would like to send)

Encryption
Encryption is the act of converting plain text to cipher text. Cipher text is basically text that has been scrambled into non-readable format using an algorithm – called a cipher.

Public key encryption uses public/private key pairs. If you want me to send you an encrypted message, you send me your public key, which I import into my encryption software. I encrypt the message with your public key. When you receive the message, you decrypt it with your private key. Even though your public key can be freely distributed and used to encrypt messages addressed to you, these encrypted messages can only be decrypted with your own private key. This private key must always be kept secret. Data encrypted with the public key can only be decrypted with its corresponding private key. This is what happens in Brower Server Communication

Digital Signature
Message signing, on the other hand, uses the sender’s private key to sign the message, and his public key is used to read the signature. Message signing helps ensure data integrity, message authentication, and non-repudiation. For example, if John wants to digitally sign a message to Bob, he uses his private key to sign the message, and sends it (along with his public key if it hasn’t already been sent) to Bob. John’s public key is the only key that can verify the message signature.

In RSA crypto, when you generate a key pair, it’s completely arbitrary which one you choose to be the public key, and which is the private key. If you encrypt with one, you can decrypt with the other – it works in both directions. It is fairly simple to see how you can encrypt a message with the receiver’s public key so that the receiver can decrypt it with their private key.

A signature is proof that the signer has a private key that matches some public key. To do this, it would be enough to encrypt the message with that sender’s private key and include the encrypted version alongside the plaintext version. To verify the sender, decrypt the encrypted version, and check that it is the same as the plaintext.

Of course, this means that your message is not secret. Anyone can decrypt it because the public key is well known. But when they do so, they have proved that the creator of the ciphertext has the corresponding private key.

However, this means doubling the size of your transmission – plaintext, and ciphertext together (assuming you want people who aren’t interested in verifying the signature, to read the message). So instead, typically a signature is created by creating a hash of the plaintext. Fake hashes can never be created, so cryptographic hash algorithms such as SHA-2 are used.

  • To generate a signature, make a hash from the plaintext, encrypt it with your private key, include it alongside the plaintext.
  • To verify a signature, make a hash from the plaintext, decrypt the signature with the sender’s public key, check that both hashes are the same.

Encryption and Decryption
Encrytion and Decryption could use same key as in symmetric algorithm or could use different one. Below are the steps for Asymmetric encrytion.

  1. Alice wants to send a message to Bob which no one should be able to read.
    1. Alice encrypts the message with Bob’s public key and sends it over.
    2. Bob receives the message and decrypts it using his private Key.
    Note that if A wants to send a message to B, A needs to use the Public key of B (which is publicly available to anyone) and neither public nor private key of A comes into the picture here.
    

So if you want to send a message to me you should know and use my public key which I provide to you and only I will be able to decrypt the message since I am the only one who has access to the corresponding private key.

Digitally Signing Message

  1. Alice wants to send a message to Bob again. The problem of encrypting the data is solved using the above method.
  2. But what if I am sitting between Alice and Bob, introducing myself as ‘Alice’ to Bob and sending my own message to Bob instead of forwarding the one sent by Alice. Even though I can not decrypt and read the original message sent by Alice(that requires access to Bob’s private key) I am hijacking the entire conversation between them.
  3. Is there a way Bob can confirm that the messages he is receiving are actually sent by Alice?
  4. Alice signs the message with her private key and sends it over. (In practice, what is signed is a hash of the message, e.g. SHA-256 or SHA-512.)
    Bob receives it and verifies it using Alice’s public key. Since Alice’s public key successfully verified the message, Bob can conclude that the message has been signed by Alice.

What is JWT?
JSON Web Tokens (JWT) is a security mechanism to transfer information between two parties by using JSON-format tokens that are self-signed. Consumer of JWT can perform JWT signature verification, which is a cryptographic process to verify the authenticity of the information contained in the token, as well as validations of the information within the token payload.

The JWT will have the following components – Header, Payload/body,Signature

  xxxx.yyyy.zzzz

ie

  Base64URLencode(Header).Base64URLencode(body).Base64URLencode(signature)

Signature will have the following pseudo-code

  RSASHA256(Base64URLencode(Header).Base64URLencode(body), Secret)

JWT consists of three parts

  1. Header – Javascript Object Signing and Encryption (JOSE) Header. This part of the token provides details about the encryption mechanisms that must be applied to verify the token signature to confirm the authenticity of the information (claims) contained in the token.

    When working with JWKS, JOSE header will specify the following attributes:

    • Encryption algorithm – alg Declared with value “RS256” (asymmetric encryption algorithm, described at this specification)
    • Key id – kid This attribute contains the identifier for the public key that must be used to perform signature verification.
  2. Token payload – It consists on a set of key-value attributes commonly referred to as “Claims”, where the attribute name and value are called “Claim Name” and “Claim value”. Claims are ultimately the lowest level of information contained in the JWT, and can be used by the resource owners to determine any kind of information about the user who owns the token (access level, identity, authorization, etc.).
  3. Token signature – JWS. From the security standpoint, this is the most important part of a JWT, as it contains the token signature that must be used to perform the verification of the token. Token signature is the result of taking the token payload and apply RS256 encryption using the private key of the RSA key pair.

Token Signature = RS256 Encryption of Header, Payload signed with Secret

What are basic security goals?
Integrity is about making sure that some piece of data has not been altered from some “reference version”
Authenticity is about making sure that a given entity (with whom you are interacting) is who you believe it to be.
Non-repudiation It is the inability to refute responsibility. For example, if you take a pen and sign a (legal) contract your signature is a nonrepudiation device.Digital signature in this case.

What is the difference between Hash, MAC, and Digital Signature?
Hash – A (unkeyed) hash of the message, if appended to the message itself, only protects against accidental changes to the message (or the hash itself), as an attacker who modifies the message can simply calculate a new hash and use it instead of the original one. So this only gives integrity.
Message Authentication Code MAC – also known as keyed hash, protects against message forgery by anyone who doesn’t know the secret key (shared by sender and receiver). This means that the receiver can forge any message – thus we have both integrity and authentication (as long as the receiver doesn’t have a split personality), but not non-repudiation. MACs can be created from unkeyed hashes (e.g. with the HMAC construction), or created directly as MAC algorithms.
Digital Signature – A (digital) signature is created with a private key, and verified with the corresponding public key of an asymmetric key-pair. Only the holder of the private key can create this signature, and normally anyone knowing the public key can verify it. So this provides all of integrity, authentication, and non-repudiation.

Hash MAC(HMAC + SHA256) Digital Signature(RSA, PKCS1)
Integrity Yes Yes Yes
Authentication No Yes Yes
Non-repudiation No No Yes
Kind of keys None Symmetric Asymmetric

Does JWT is both Hashed and Signed?

JWT is both hashed and signed. Hashing algorithm used is specified in the Header. To make hashing stronger we use salt which is sometime refered as secret. However, using this secret is sometime confused with signing of JWT. Signing is a process where only the signer knows the key with which the payload is signed. As far the resource and authorization server are same usgae of the term signing and hashing holds true. Incase if resource and authorization server are different and symmetric key is used, signing payload should no longer used since signature is unique to entity but in above case there are two entities which holds the same signature.

Sometimes JWT is both hashed and signed. Most realtime implementation of JWT uses this methodology to make JWT more secure.

Why we do base64 encoding in JWT?
JWT is actually not Base64, instead, it’s Base64Url Encoded. It’s just like Base64, but there are a couple of characters different so that we can easily send a JWT as part of a Url parameter. All three parts of the JWT are Base64Url encoded, which makes the JWT URL-encoded, which means it can be shared between two or more parts using HTTP.

What are two common ways of implementation of JWT?

  1. Method 1 – Using asymmetric algorithm using public and private key. Implementing JWT using this method helps in authorization by Resource Server
  2. Method 2 – Using symmetric algorithm using same key for Signing. In this case only the server which has issued can authorize the user. The same copy of the key could be shared to resource server but at cost of compromising security scale.

Do we always need Public and Private Key?
No. It depends on the implementation. When the Authorization and the Resource server is same then we dont need two different keys. In this case the key is referred to as secret and secret is used for signing payload. But when Authorization and the Resource server are different then we need private key to sign the resource and public key to read the signature.

Symmetric Signing uses HS256 algorithm for signing. The same would be seen in header field.

{
   "typ":"JWT",
   "alg":"HS256"
}

Asymmetric signing uses RS256 algorithm for signing.

{
   "typ":"JWT",
   "alg":"RS256"
}

What is the difference between RS256 and HS256?
RS256 (RSA Signature with SHA-256) – is an asymmetric algorithm, and it uses a public/private key pair: the identity provider has a private (secret) key used to generate the signature, and the consumer of the JWT gets a public key to validate the signature. Since the public key, as opposed to the private key, doesn’t need to be kept secured, most identity providers make it easily available for consumers to obtain and use (usually through a metadata URL).

HS256 (HMAC with SHA-256) – on the other hand, involves a combination of a hashing function and one (secret) key that is shared between the two parties used to generate the hash that will serve as the signature. Since the same key is used both to generate the signature and to validate it, care must be taken to ensure that the key is not compromised.

If you will be developing the application consuming the JWTs, you can safely use HS256, because you will have control on who uses the secret keys. If, on the other hand, you don’t have control over the client, or you have no way of securing a secret key, RS256 will be a better fit, since the consumer only needs to know the public (shared) key exposed by JWK URL.

Why we need JWK Endpoints?
In Asymmetric signing public key should be exposed so who ever uses it could decrypt to read the signature. Validation will happen in the following steps

  1. Retrieve the JWKS from JWKS endpoint
  2. Get JWT and decode it.
  3. Grab the kid property from the header of the decoded JWT.
  4. Search the key with the matching kid property in retrieve keysets.
  5. Build a (public)certificate using the corresponding keyset
  6. Use the certificate to verify the JWT’s signature.

JSON Web Key & JSON Web Key Set
JWK consists on a JSON data structure that represents a cryptographic key. The members of the object represent properties of the key, including its value. A JWK Set is simply JSON data structure that represents a set of JWKs.

There are attributes that are mandatory within JWK, regardless on the signing algorithm

  1. kid (Key ID) Parameter is used to identify a key, with the purpose to choose among a set of keys within a JWK Set during key rollover. kid parameter is utilized to lookup the appropriate public key, as it is also included in the JWT JOSE header.
  2. kty (Key Type) Parameter. This attribute identifies the cryptographic algorithm family used with the key, such as “RSA” or “EC”.
  3. use (Public Key Use) Parameter. This parameter identifies the intended use of the public key. The “use” parameter is employed to indicate whether a public key is used for encrypting data or verifying the signature on data.
    Values defined by this specification are:

    1. sig (signature)
    2. enc (encryption)
  4. exp (Expiration) Parameter. Although “exp” is not mentioned in the JWK specification, it is widely used in the same way as described in the JWT specification, which can be found here. Its purpose is to define the expiration time for the given JWK. “exp” MUST be a number containing a NumericDate value.
  5. alg – parameter identifies the algorithm intended for use with the key.eg in RSA, we can have RSA256 or RSA512

JWT are used for authorization and not authentication. So a JWT will be created only after the user has been authenticated by the server by specifying the credentials. Once JWT has been created for all future interactions with the server JWT can be used. So JWT tells that server that this user has been authenticated, let him access the particular resource if he has the role.

Posted in JWT.

In JWT both Header and Payload is encoded to make it URL Safe but not encrypted. So any one can see the content after decoding the Header and Payload. We cannot send any sensitive data using JWT.The signature is created using the header, the payload, and the secret that is saved on the server.

   Signature = Header + Payload + Secret

The above process is Signing the JSON Web Token. The signing algorithm takes the header, the payload, and the secret to creating a unique signature. So only this data plus the secret can create this signature. Together with the header and the payload, these signature forms the JWT, which then gets sent to the client.

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the JSON Web Token.

The signature is an HMAC, which uses a particular type of cryptographic function. Such an HMAC algorithm is indicated with the “HS” prefix, as shown in the sample token above. The HMAC takes the header, the payload, and a secret key as input, and returns a unique signature over all three inputs. Service uses the same secret key to calculate the HMAC of the JWT. If the resulting HMAC is the same as the signature in the token, the service knows that all three inputs to the HMAC function were the same as before.

{
   "typ":"JWT",
   "alg":"HS256"
}

How Verification is Carried to check whether payload has been changed?

Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

The original signature that was generated when the JWT was first created is still in the token which is the key to this verification. We have to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified. If they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. Third party manipulating the payload does not have access to the secret(Private key used to sign), so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case.

Limitations of Symmetric Signatures
This signature scheme is straightforward. It is also the typical scheme used to explain JWTs to developers. Unfortunately, symmetric signatures prevent the sharing of the JWT with another service. To verify the JWT’s integrity, all services would need to have access to the same secret key. However, possession of the secret key is enough to generate arbitrary JWTs with a valid signature.

Sharing the HMAC secret with a third-party service creates a significant vulnerability. Even sharing the secret between different services within a single architecture is not recommended. If all services share the same key, the compromise of a single service immediately becomes an architecture-wide problem.

Instead of sharing the secret HMAC key, you can opt for using asymmetric signatures

Note: The above could be helpful of the Authorization Server and Resource Server is same.

Link to Repo

Posted in JWT.
  1. What is a Cipher?
    A cipher transforms data by processing the original, plaintext characters (or other data) into ciphertext, which should appear to be random data
  2. What is Message Digest? Why we need Message Digest?
    A message digest is a cryptographic hash function containing a string of digits created by a one-way hashing formula. Message digests are designed to protect the integrity of a piece of data or media to detect changes and alterations to any part of a message.This term is also known as a hash value and sometimes as a checksum.Message digests are encrypted with private keys creating a digital signature. This results in a type of validation ensuring that the appropriate user is accessing protected information. Message digests protect one-way hash algorithms taking random data and transmitting a set length hash value.
  3. What is role of Hasing in Security? Hashing helps in preventing or analyzing file tampering. The original data will generate a hash which is kept with the data. The data and the hash are sent together, and the receiving party checks that hash to see if the data has been compromised. If there were any changes to the data, the hash wont match.
  4. What is Secure Hash Algorithm (SHA)?Secure Hash Algorithms, also known as SHA, are a family of cryptographic functions designed to keep data secured. It works by transforming the data using a hash function: an algorithm that consists of bitwise operations, modular additions, and compression functions. The hash function then produces a fixed-size string that looks nothing like the original. These algorithms are designed to be one-way functions, meaning that once they’re transformed into their respective hash values, it’s virtually impossible to transform them back into the original data. A few algorithms of interest are SHA-1, SHA-2, and SHA-3, each of which was successively designed with increasingly stronger encryption in response to hacker attacks. SHA-0, for instance, is now obsolete due to the widely exposed vulnerabilities.
  5. What does MessageDigest getInstance() does?

    MessageDigest class provides a method named getInstance(). This method accepts a String variable specifying the name of the algorithm to be used and returns a MessageDigest object implementing the specified algorithm.Create MessageDigest object using the getInstance() method as shown below.

    MessageDigest md = MessageDigest.getInstance("SHA-256");
    

    After creating the message digest object, you need to pass the message/data to it. You can do so using the update() method of the MessageDigest class, this method accepts a byte array representing the message and adds/passes it to the above created MessageDigest object.

    md.update(msg.getBytes());
    

    You can generate the message digest using the digest() method od the MessageDigest class this method computes the hash function on the current object and returns the message digest in the form of byte array.Generate the message digest using the digest method.

    byte[] digest = md.digest();
    
  6. Could I use Public and Private Keys Inversely?
    Yes. The keys work inversely to each other. Encrypted something with your public key? Decrypt it with your private key. Conversely, if you encrypt something with your private key, you decrypt it with your public. Such is the nature of asymmetric cryptography.
  7. What is Symmetric and Asymmetric Keys?
    Symmetric just means that the same key is used to encrypt/decrypt. Asymmetric means that one key encrypts and a different key decrypts (and that the reverse is also true).

    #Creating a key Pair
    openssl genrsa -out private.pem 1024
    openssl rsa -in private.pem -out public.pem -pubout
    
    #Encrypt with public & decrypt with private
    openssl rsautl -encrypt -inkey public.pem -pubin -in message.txt -out message.ssl
    openssl rsautl -decrypt -inkey private.pem       -in message.ssl -out message.txt
    
    #Encrypt with private & decrypt with public
    openssl rsautl -sign    -inkey private.pem -in message.txt          -out message_enc_priv.ssl
    openssl rsautl -inkey public.pem -pubin    -in message_enc_priv.ssl -out message_priv.txt
    
  8. In the above example, you could see the public key is genarated first followed by generation of private key. Any idea why it is so?
    elliptic curve cryptography (also called “elliptic curve multiplication”) is the answer to the question. Elliptic curve cryptography is the mathematical relationship that makes the following conditions possible:

    • A public key can be mathematically generated from a private key
    • A private key cannot be mathematically generated from a public key (i.e. “trapdoor function”)
    • A private key can be verified by a public key

    a public/private keypair is created using elliptic curve cryptography, which by nature, creates a public and private key that are mathematically linked in both directions, but not mathematically derived in both directions.

  9. is JWT secured?
    JWT are used for authentication. JWTs are typically used to authenticate users and provide authorized access to resources by adding claims to the data, such as user data and files. JWT is suitable for stateless applications, as it allows the application to authenticate users and authorize access to resources without maintaining a session state on the server
  10. What is Resource and Authorization Server? Authorization server is the one which issues the JWT after authentication. Resource server is the one which authorizes User every time using JWT while accesing resource
  11. What does .pem file contains?
    PEM stands for Privacy-Enhanced Mail. A PEM file may contain anything including a public key, a private key, or both, because a PEM file is not a standard. In effect PEM just means the file contains a base64-encoded bit of data.
    Typically a PEM file contains a base64 encoded key or certificate with header and footer lines of the form —–BEGIN —– and —–END —-. Over time there have evolved many possibilities for , including private keys, public keys, X509 certificates, PKCS7 data, files containing multiple certificates, files containing both the private key and the X509 certificate.
  12. What is CSR and CRT(or)CER?
    Certificate Signing Request contains information such as the public key and common name required by a Certificate Authority to create and sign a certificate for the requester, the encoding could be PEM or DER. These get signed by the CA and a certificate is returned. The returned certificate is the public certificate (which includes the public key but not the private key). Since the public key is signed by CA, the CA is confident the one who has sent for signing is the only one who has access to private key.
  13. What is PKIX?
    PKIX is an IETF (Internet Engineering Task Force) working group with the goal of supporting public key infrastructures based on X.509 on the Internet.X.509 certificate is a digital certificate based on the widely accepted International Telecommunications Union (ITU) X.509 standard, which defines the format of public key infrastructure (PKI) certificates. They are used to manage identity and security in internet communications and computer networking

In the below code there might arise a question why we need to do hashing and extract the final secret key from it. The importance of this step could be felt incase we are storing passwords in DBs instead of directly using actual secret key and hashing, the hashing by using message digest adds more strength.

EncryptUtil.java

package com.mugil.org;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

public class EncryptUtil {
    private static SecretKeySpec secretKey;
    private static byte[] key;

    public static void setKey(String myKey) {
        MessageDigest sha = null;
        try {
            //Byte Arrays are secured compared to storing in String as it is immutable
            key = myKey.getBytes("UTF-8");

            /*
              MessageDigest class represents a cryptographic hash function which can calculate a
              message digest from binary data.A hash function is a mathematical function that 
              converts a numerical input value into another compressed numerical value.The input to 
              the hash function is of arbitrary length but output is always of fixed length.
              Values returned by a hash function are called message digest or simply hash values.
            */

            /*
              Code will work without below two lines but hashing adds more strength to secret key
              AES needs a 128/192/256 bits key. If you don't hash your key and only trim the input it
              would only use the first 16/24/32 Bytes. So generating a Hash is the only reasonable way.
             */
            sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);

            /*Use SHA-1 to generate a hash from your key and trim the result to 128 bit (16 bytes).*/
            key = Arrays.copyOf(key, 16);

            /*Taking Key that would be used for Encrytion */
            secretKey = new SecretKeySpec(key, "AES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static String encrypt(String strToEncrypt, String secret) {
        try {
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        } catch (Exception e) {
            System.out.println("Error while encrypting: " + e.toString());
        }
        return null;
    }

    public static String decrypt(String strToDecrypt, String secret) {
        try {
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
        } catch (Exception e) {
            System.out.println("Error while decrypting: " + e.toString());
        }
        return null;
    }
}

SimpleEncryption.java

package com.mugil.org;

public class SimpleEncryption {
    public static void main(String[] args) {
        final String secretKey = "ItSecretKey";

        String originalString = "You Nailed It!!!";
        String encryptedString = EncryptUtil.encrypt(originalString, secretKey) ;
        String decryptedString = EncryptUtil.decrypt(encryptedString, secretKey) ;

        System.out.println(originalString);
        System.out.println(encryptedString);
        System.out.println(decryptedString);
    }
}

You Nailed It!!!
lFY4a0e0BRVfcfko56Lpe78iUfPoZm5wkq/zv0hrFco=
You Nailed It!!!

பொதுவாக ஜோதிடப்படி, ராகுகாலம், எமகண்டத்தில் எந்தவொரு நல்ல செயலை செய்யமாட்டார்கள். ஆனால், குளிகை நேரத்தில் செய்யப்படும் எந்த காரியமும் திரும்பத் திரும்ப நடக்கும். ஆகையால், நல்ல காரியங்களுக்கு குளிகை நேரம் உகந்ததாகவும், ஈமச்சடங்கு போன்ற கெட்ட காரியங்களுக்கு குளிகை நேரம் பொருத்தமில்லாததாகவும் கருதப்படுகிறது. குளிகை நேரத்தில் ஒரு காரியத்தை தொடங்கினால், அது வளர்ந்துக்கொண்டே இருக்கும்.

குளிகையில் என்ன செய்யலாம்?

  • குளிகை நேரத்தில் சொத்து வாங்குவது
  • சுப நிகழ்வுகள்
  • கடனை திருப்பி கொடுப்பது
  • பிறந்தநாள் கொண்டாடுவது

போன்றவற்றை செய்வதால் அச்செயல்கள் எந்த தடையும் இல்லாமல் நடப்பது மட்டுமின்றி, இதுபோன்ற நல்ல நிகழ்ச்சிகள் தொடர்ந்து நடந்து கொண்டும் இருக்கும்.

குளிகையில் என்ன செய்யக்கூடாது?

  • அடகுவைப்பது
  • கடன் வாங்குவது
  • வீட்டை காலிசெய்வது
  • இறந்தவர் உடலை கொண்டு செல்வது
  • போன்ற விஷயங்களை குளிகை நேரத்தில் செய்யக்கூடாது.

நல்ல காரியங்களை செய்வதற்கு உகந்த குளிகை நேரத்திற்குரிய குளிகனின் பிறப்பே ஒரு நல்ல நிகழ்வை தொடங்குவதற்காகத்தான் உருவானது.

குளிகன் உருவான கதை :

ராவணனின் மனைவி மண்டோதரி, கருவுற்று நிறைமாத கர்ப்பிணியாக இருந்தார். ராவணன் தனது குல குருவான சுக்கிராச்சாரியாரை சந்தித்து, எப்போது வேண்டுமானாலும் குழந்தை பிறக்கும் நிலையில் உள்ளது என்றும், யாராலும் வெல்ல முடியாத, அழகும், அறிவும் கொண்ட மகனே தனக்கு பிறக்க வேண்டும் என்றும், அதற்கு என்ன வழி என்றும் கேட்டார்.அதற்கு பதில் அளித்த சுக்கிராச்சாரியார், கிரகங்கள் அனைத்தும் ஒரே கட்டத்தில் இருக்கும் நேரத்தில் உனக்கு குழந்தை பிறந்தால், அந்த குழந்தை நீ விரும்பிய எல்லா சிறப்புகளும் கொண்டதாக இருக்கும் என்று யோசனை சொன்னார். உடனே, நவகிரகங்கள் அனைத்தையும் சிறைப்பிடித்து, ஒரே அறைக்குள் அடைத்துவிட்டார் ராவணன். ஒரே அறையில் இருந்த கிரகங்கள் யாவும் தவித்துப் போயினர். இந்த யோசனையை சொன்ன சுக்கிராச்சாரியாரை கடிந்து கொண்டனர். ஒரே இடத்தில் இருப்பதால் நடக்கப்போகும் தீமைகளை எண்ணி கவலை கொண்டனர்.

இதேநேரத்தில் குழந்தை பிறக்க முடியாமல் மண்டோதரி பெரும் தவிப்பில் கிடந்தார். வலி அதிகம் இருந்தபோதிலும் குழந்தை பிறக்கவே இல்லை. இந்த செய்தி நவகிரகங்களின் காதிற்கு எட்டியதும், அதற்கும் தாங்கள்தான் காரணம் என்று ராவணன் தண்டிப்பாரோ என்று அச்சம் கொண்டனர். இது குறித்து சுக்கிராச்சாரியாரிடம் ஆலோசனை கேட்டனர். இந்த சிக்கலில் இருந்து விடுபட வேண்டுமானால், உங்கள் ஒன்பது பேரை தவிர, நல்ல செயல் புரிவதற்கென்று இன்னொரு புதியவனை சிருஷ்டித்து, ஒவ்வொரு நாளிலும் ஒரு குறிப்பிட்ட நேரத்தை அவனுடைய ஆளுகைக்கு உட்பட்ட நேரமாக மாற்றிக் கொடுத்தால், உங்களுக்கு நன்மை உண்டாகும் என்றார்.

அவனை சிருஷ்டிக்கும் அதேவேளையிலேயே மண்டோதரிக்கு சுகப்பிரசவம் உண்டாகும். நீங்களும் விடுதலை ஆகலாம் என்றார். அதன்படி சனீஸ்வர பகவான் சிறையில் இருந்தபடியே தனது சக்தியால் ஜேஷ்டாதேவிக்கு ஒரு மகன் பிறக்க வழிசெய்தார். குளிகன் பிறந்த அதேநேரம் மண்டோதரிக்கும் அழகான ஒரு மகன் பிறந்தான். அவனுக்கு மேகநாதன் என்று பெயர் சூட்டினர்.தான் பிறக்கும்போதே நல்லதை நடத்தி வைத்ததால், குளிகன் நவகிரகங்களால் பாராட்டப்பட்டார். குளிகை நேரம் என்றே தினமும் பகலிலும், இரவிலும் ஒரு நாழிகை நேரம் கொடுக்கப்பட்டது. அந்த நேரம், காரிய விருத்தி நேரம் என ஆசீர்வதிக்கப்பட்டது. இதனாலேயே குளிகை நேரத்தில் செய்யப்படும் எந்த ஒரு நல்ல காரியமும் தொடர்ந்து நடைபெறும் என்று கூறப்பட்டது.

Icebreaker Session : An ice breaker is an activity, game, or event that is used to welcome and warm up the conversation among participants in a meeting.

Activity 1: Form Small Teams and ask them to discuss one common interest among group members. They would talk within themself and end up in one common interest. This should be done within 60 Seconds.

Again the same process is repeated for 60 seconds by combining team together and finding their common interest.

I.E. Suppose there are 30 people in the room and we are dividing 5 teams with 6 members in each team we would come up with common interest for 6 members in team in the first 60 seconds and we would come up with common interest for 12 members after combining team in the second 60 seconds.

Common interests could be anything like food, sports, going for a walk, dislikes, or horror movies.

At the end of 60 seconds, one team member should let others know what is the common thing is shared by the team members.

Activity 2: Ask the client about them and one secret.

Crowd Storming: Crowdstorming is a massive collaborative brainstorming session with a large community of people. With crowd storming, you tap into ideation—or the collection of ideas from a group of people—and leverage it to solve a specific issue.

Activity 1: Take sticky notes and ask the 30 members in the room to write an idea in a few words. The idea could be anything I.E Openness and collaboration, 4Hr work week, Team Outing, Pair Programming, Regular connect with clients. You would give 30 seconds to think so the members would write their ideas on a sticky note with their names on top. Once they are done we would play music and make them take walk in the room.

Once the music is paused we would hand over the sticky notes to a random person who is next to them and ask for a rating. The other person reads the idea and writes the rating on a sticky note and hands it back to the person to whom it belongs to and vice versa. The rating could be 1 to 5. The same process is repeated by playing and pausing music three times and getting their ideas rated thrice by three different persons.

Now all the 3 ratings from 3 individuals would be summed. The crowd storming boards would have 3 sections.

<----------1-5--------->|<----------5-10--------->|<----------11-15--------->
                        |                         |                 
                        |                         |        
                        |                         |                          
                        |                         |          

Collect all the sticky notes and post it in the appropriate section. The Stickies in sections 11-15 could be collected and ideas could be discussed and elaborated with the members who wrote in as a group in the room.

Back to Back Drawing : You would make the team members stand in line and the last person to pick a chit from a lot that has simple drawings. The last person in the group should guide the before one by drawing at their back. This continues till the first person draws the figure on board.

While doing this using paper and a marker to draw would be effective. Try to get Plastic Sheets that could be used to place the paper while drawing on someone’s back since using markers on someone’s back may end up with creases or strains in their shirts. The drawing in chit should be simple shapes and not complex ones.

Below are a few drawings that could be used.

Chinese whispers Make people standin line. The message should be read by last person and communicated to the before person in action. It should be simple phrases from things around them in the room. I.E Temperature is hot, I dont know, Salt and pepper, Its Sunny outside. The first person in the line should come back to the last person and convey what he understood.

Other Things to be checked before Client Arrival:

  1. WiFi – Check whether the wifi is connecting and available to them in your mobile before they arrive
  2. Check the TV connectivity for conference call incase needed. Also do dry run if possible with some one at onsite
  3. Availability of water bottles in Room.
  4. Room Temperature and AC
  5. Some mild music which could be played when they enter the room

Casual Conversation Questions to Ask

  • How is your flight
  • How do you like the city
## Summary

Below are the List of Features available in Code

1. Reading payload from JSON File and using it as mocked Response
2. Object creation from JSON File
---

## Things Newly Implemented

1. JSON Payload files are found in src/test/resources/json-data
2. In the Code Converstion to Employee Object after reading Employee JSON and Stringify of JSON Object are both done  
3. MockMvc Testing is implemented for Controllers	
	- For AddEmployee Endpoint - Request from JSON file, Response from mocked response  
	- For GetEmployee Endpoint - Request by URL, Response from mocked Employee object constructed from JSON File
	- For GetAllEmployees Endpoint - Request by URL, Response from method returning Employee Object
	- For DeleteEmployee Endpoint - Request by URL, Response from mocked method	 	  
---

## Changes in pom.xml 
```xml
<build>
    <testResources>
        <testResource>
            <directory>${project.basedir}/src/test/resources</directory>
        </testResource>			
    </testResources>
    .
    .
    .
</build>
```
---

# API endpoints
## GET
`Get All Employees Detail` [/empmgmt/employees](#getallemployee) <br/>
`Get Employee Details` [/empmgmt/employees/{empId}](#getemployeesempid) <br/>

## POST
`Add Employee Details` [/empmgmt/employees](#addemployee) <br/>

## DELETE
`Delete EmpDetails` [/empmgmt/employees/{empId}](#deleteemployee) <br/>
___

<a name="getemployeesempid"></a>
### GET /empmgmt/employees/{empId}
Get Employee Detail

**Parameters**

|          Name | Required |  Type   | Description                                                                                                                                                           |
| -------------:|:--------:|:-------:| --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|     `empId` | required | string  | Employee Id

**Response**

```
// Employee Details added Succesfully
[
    {
        "empID": 1,
        "empName": "Mugil",
        "empAge": "36"
    }
]
```
___

<a name="getallemployee"></a>
### GET /empmgmt/employees

**Response**
```
// Employee Details added Succesfully
[
    {
        "empID": 1,
        "empName": "Mugil",
        "empAge": "36"
    }
]
```
___

<a name="addemployee"></a>
### POST /empmgmt/employees
Add Employee Details

**Parameters**

|          Name | Required |  Type   | Description                                                                                                                                                           |
| -------------:|:--------:|:-------:| --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|     `empName` | required | string  | Name of Employee
|     `empAge` | required | string  | Age of Employee

**Request**
```
// Employee Details 
{
    "empName" : "Mugil",
    "empAge" : "36"
}
```


**Response**

```
// Employee Details added Succesfully
[
    {
        "empID": 1,
        "empName": "Mugil",
        "empAge": "36"
    }
]
```
___

<a name="deleteemployee"></a>
### DELETE /empmgmt/employees/{empId}

**Parameters**

|          Name | Required |  Type   | Description                                                                                                                                                           |
| -------------:|:--------:|:-------:| --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|     `empId` | required | string  | Employee Id


**Response**

```
Employee Deleted Successfully
```
___



## Note

* While reading file from resources folder I continously got error telling the file doesnot exists. 
  The Same problem is faced while working in office project. After adding above lines in pom.xml it started 
  working. It kept working, even after removing above lines
* The URL returned in _Link in add employee wont have a port number. The test keeps failing if you copy and paste
  URL from postman and try to asset the _links in mockMVC

___    

Copy paste the code in URL to see in action : https://markdownlivepreview.com/

Readme file screen shot for above code

TestTraits.java

package com.mugil.org;

import com.google.gson.Gson;
import com.mugil.org.models.Employee;
import org.springframework.core.io.ClassPathResource;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public interface TestTraits {
    public static Object getObjfromJson(String fileLoctaion) throws IOException {
        Gson gson = new Gson();
        Employee objEmployee2 = gson.fromJson(getReader(fileLoctaion), Employee.class);
        return objEmployee2;
    }

    public static Reader getReader(String fileLoctaion) throws IOException {
        return new FileReader(new ClassPathResource(fileLoctaion).getFile());
    }
}

EmployeeObject.json

{
  "empID": 101,
  "empName": "Mani",
  "empAge": "35"
}

EmployeeControllerTest.java
Read JSON Value as from File and Convert to Employee Object and to JSON String

JSON Value from File -> Employee Object -> JSON String from Object

  @Test
    void addEmployeeDetails() throws Exception {
        
        //Read values from JSON  
        Employee objEmployee = (Employee) TestTraits.getObjfromJson("json-data/EmployeeObject.json");

        //Convert Object to JSON String
        String jsonRequestString = mapper.writeValueAsString(objEmployee);

        when(employeeServiceImpl.saveEmployee(any())).thenReturn("101");

        ResultActions objResultActions = this.mockMvc.perform(post("/empmgmt/employees")
                .contentType(MediaType.APPLICATION_JSON)
                .content(jsonRequestString))
                .andDo(print())
                .andExpect(jsonPath("$.empID", is(Matchers.notNullValue())))
                .andExpect(jsonPath("$.empID", is(101)))
                .andExpect(jsonPath("$.empName", is("Mani")))
                .andExpect(status().isCreated());
    }

EmployeeControllerTest.java
Read JSON Value as from File and Convert to Employee Object and to JSON String

JSON Value from File -> Employee Object for Mocking Service Call


@Test
    void getEmployeeDetails() throws Exception {
          
        //Object Construction by reading file
        Employee objEmployee = (Employee) TestTraits.getObjfromJson("json-data/EmployeeObject.json");

        //Making object as Optional
        Optional<Employee> objEmp = Optional.ofNullable(objEmployee);

        //Mocked service response from object created
        when(employeeServiceImpl.findEmployee(EMP_ID)).thenReturn(objEmp);

        ResultActions objResultActions = this.mockMvc.perform(get("/empmgmt/employees/{empID}",EMP_ID))
                                                    .andDo(print())
                                                    .andExpect(jsonPath("$.empID", is(101)))
                                                    .andExpect(jsonPath("$.empName", is("Mani")))
                                                    .andExpect(jsonPath("$._links.all-employees.href", is("http://localhost/empmgmt/employees")))
                                                    .andExpect(status().isOk());
    }

Repo Link
https://bitbucket.org/Mugil/restwithspringboot/branch/feature/7MockMVCTesting_3

POST

 @Test
    void addEmployeeDetails() throws Exception {
        Employee objEmployee = (Employee) TestTraits.getObjfromJson("json-data/EmployeeObject.json");

        String jsonRequestString = mapper.writeValueAsString(objEmployee);

        when(employeeServiceImpl.saveEmployee(any())).thenReturn("101");

        ResultActions objResultActions = this.mockMvc.perform(post("/empmgmt/employees")
                .contentType(MediaType.APPLICATION_JSON)
                .content(jsonRequestString))
                .andDo(print())
                .andExpect(jsonPath("$.empID", is(Matchers.notNullValue())))
                .andExpect(jsonPath("$.empID", is(101)))
                .andExpect(jsonPath("$.empName", is("Mani")))
                .andExpect(status().isCreated());
    }

GET

 @Test
    void getEmployeeDetails() throws Exception {
        ClassLoader loader = Test.class.getClassLoader();
        Employee objEmployee = (Employee) TestTraits.getObjfromJson("json-data/EmployeeObject.json");

        Optional<Employee> objEmp = Optional.ofNullable(objEmployee);
        when(employeeServiceImpl.findEmployee(EMP_ID)).thenReturn(objEmp);

        ResultActions objResultActions = this.mockMvc.perform(get("/empmgmt/employees/{empID}",EMP_ID))
                                                    .andDo(print())
                                                    .andExpect(jsonPath("$.empID", is(101)))
                                                    .andExpect(jsonPath("$.empName", is("Mani")))
                                                    .andExpect(jsonPath("$._links.all-employees.href", is("http://localhost/empmgmt/employees")))
                                                    .andExpect(status().isOk());
    }

DELETE

 @Test
    void deleteEmployeeDetails() throws Exception {
        when(employeeServiceImpl.deleteEmployee(Long.valueOf(EMP_ID))).thenReturn(true);

        this.mockMvc.perform(delete("/empmgmt/employees/{empID}",EMP_ID))
                .andDo(print())
                .andExpect(content().string(containsString("Employee Deleted Successfully")))
                .andExpect(status().isOk());
    }

EmployeeControllerTest.java

package com.mugil.org.controllers;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mugil.org.TestTraits;
import com.mugil.org.models.Employee;
import com.mugil.org.services.EmployeeServiceImpl;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@ExtendWith(SpringExtension.class)
@WebMvcTest(EmployeeController.class)
class EmployeeControllerTest {

    @MockBean
    EmployeeServiceImpl employeeServiceImpl;

    ObjectMapper mapper = new ObjectMapper();

    @Autowired
    private MockMvc mockMvc;

    private static final String EMP_ID = "101";

    @Test
    void getEmployeeDetails() throws Exception {
        ClassLoader loader = Test.class.getClassLoader();
        Employee objEmployee = (Employee) TestTraits.getObjfromJson("json-data/EmployeeObject.json");

        Optional<Employee> objEmp = Optional.ofNullable(objEmployee);
        when(employeeServiceImpl.findEmployee(EMP_ID)).thenReturn(objEmp);

        ResultActions objResultActions = this.mockMvc.perform(get("/empmgmt/employees/{empID}",EMP_ID))
                                                    .andDo(print())
                                                    .andExpect(jsonPath("$.empID", is(101)))
                                                    .andExpect(jsonPath("$.empName", is("Mani")))
                                                    .andExpect(jsonPath("$._links.all-employees.href", is("http://localhost/empmgmt/employees")))
                                                    .andExpect(status().isOk());
    }

    @Test
    void deleteEmployeeDetails() throws Exception {
        when(employeeServiceImpl.deleteEmployee(Long.valueOf(EMP_ID))).thenReturn(true);

        this.mockMvc.perform(delete("/empmgmt/employees/{empID}",EMP_ID))
                .andDo(print())
                .andExpect(content().string(containsString("Employee Deleted Successfully")))
                .andExpect(status().isOk());
    }

    @Test
    void getAllEmployeeDetails() throws Exception {
        List<Employee> arrEmployees = new ArrayList<>();
        arrEmployees.add(getEmployee());

        when(employeeServiceImpl.findAllEmployee()).thenReturn(arrEmployees);

        ResultActions objResultActions = this.mockMvc.perform(get("/empmgmt/employees")
                .contentType(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(jsonPath("$[0].empID", is(Matchers.notNullValue())))
                .andExpect(jsonPath("$[0].empID", is(101)))
                .andExpect(jsonPath("$[0].empName", is("Shivaji")))
                .andExpect(status().is2xxSuccessful());
    }

    @Test
    void addEmployeeDetails() throws Exception {
        Employee objEmployee = (Employee) TestTraits.getObjfromJson("json-data/EmployeeObject.json");

        String jsonRequestString = mapper.writeValueAsString(objEmployee);

        when(employeeServiceImpl.saveEmployee(any())).thenReturn("101");

        ResultActions objResultActions = this.mockMvc.perform(post("/empmgmt/employees")
                .contentType(MediaType.APPLICATION_JSON)
                .content(jsonRequestString))
                .andDo(print())
                .andExpect(jsonPath("$.empID", is(Matchers.notNullValue())))
                .andExpect(jsonPath("$.empID", is(101)))
                .andExpect(jsonPath("$.empName", is("Mani")))
                .andExpect(status().isCreated());
    }

    private Employee getEmployee(){
        Employee objEmployee = new Employee();

        objEmployee.setEmpID(Long.valueOf(101));
        objEmployee.setEmpAge("35");
        objEmployee.setEmpName("Shivaji");

        return objEmployee;
    }
}