Friday, May 25, 2018

Standard Python scalar types

Below are the standard Python scalar types:

Type: Description
None: The Python "null" value (only one instance of the None object exists)
str: String type; holds Unicode (UTF-8 encoded) strings
bytes: Raw ASCII bytes (or Unicode encoded as bytes)
float: Double-precision (64-bit) floating-point number (note there is no separate double type)
bool: A True or False value
int: Arbitrary precision signed integer





How to check/get/set an attribute or a method in Python (Reflection)

Python allows an easy way to check whether an object contains/has an attribute or method with the specified name as follows:

1) getattr:
Gets the attribute/method with the specified name, usage as follows:
usage: getattr(obj, 'method/attribute name')
eg: 
a='RK'; 
getattr(a, 'split')


2) hasattr:
Checks whether object has the attribute/method with the specified name, usage as follows:

usage: hasattr(obj, 'method/attribute name')
eg: 
a='RK'; 
hasattr(a, 'split')


3) setattr:
Sets the attribute/method with the specified name, usage as follows:
usage: setattr(obj, 'method/attribute name', value)
eg: 
a=Employee(23)
setattr(a, 'id', 45)


Python assignments are by references

When assigning a variable (or name) in Python, you are creating a reference, have a look at below:

CODE:
a=[1,2]
b=a
print("Before append: ", b)
b.append(3)
print("Shows a & b are same references, after append to b, a: ", a)



OUTPUT:

Before append:  [1, 2]
Shows a & b are same references, after append to b, a:  [1, 2, 3]

How to get rid of `grep: warning: GREP_OPTIONS is deprecated; please use an alias or script`?

Need to have an alias for grep to make the output colored as follows and unset the GREP_OPTIONS.


alias grep="grep --color=auto"
unset GREP_OPTIONS



Monday, May 21, 2018

How to create a self signed certificate, and how to validate the JWT token using Nimbus

This post will help you to generate a self-signed certificate and show you how to validate the JWT token using Nimbus Jose JWT library.


package com.varra.samples;

import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Date;

import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jose.crypto.RSASSAVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;

import sun.security.rsa.RSAPublicKeyImpl;
import sun.security.x509.AlgorithmId;
import sun.security.x509.CertificateAlgorithmId;
import sun.security.x509.CertificateSerialNumber;
import sun.security.x509.CertificateValidity;
import sun.security.x509.CertificateVersion;
import sun.security.x509.CertificateX509Key;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;

public class JWTTokenUtils {


/** 
* Create a self-signed X.509 Certificate
* @param dn the X.509 Distinguished Name, eg "CN=RK, L=Hyderabad, C=Hyderabad"
* @param pair the KeyPair
* @param days how many days from now the Certificate is valid for
* @param algorithm the signing algorithm, eg "SHA1withRSA"
*/ 
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
  throws GeneralSecurityException, IOException
{
  PrivateKey privkey = pair.getPrivate();
  X509CertInfo info = new X509CertInfo();
  Date from = new Date();
  Date to = new Date(from.getTime() + days * 86400000l);
  CertificateValidity interval = new CertificateValidity(from, to);
  BigInteger sn = new BigInteger(64, new SecureRandom());
  X500Name owner = new X500Name(dn);
 
  info.set(X509CertInfo.VALIDITY, interval);
  info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
  //info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
  info.set(X509CertInfo.SUBJECT, owner);
  info.set(X509CertInfo.ISSUER, owner);
  info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
  info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
  AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
  info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
 
  // Sign the cert to identify the algorithm that's used.
  X509CertImpl cert = new X509CertImpl(info);
  cert.sign(privkey, algorithm);
 
  // Update the algorith, and resign.
  algo = (AlgorithmId)cert.get(X509CertImpl.SIG_ALG);
  info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);
  cert = new X509CertImpl(info);
  cert.sign(privkey, algorithm);
  return cert;
}
public static String generateToken(RSAPrivateKey privateKey) throws Exception
{
// Create RSA-signer with the private key
final JWSSigner signer = new RSASSASigner(privateKey);
// Prepare JWT with claims set
final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
    .subject("alice")
    .issuer("Rajakrishna Reddy")
    .claim("user", "Rajakrishna Reddy")
    .claim("email", "abc@xyz.com")
    .claim("tenantId", "123")
    .expirationTime(new Date(new Date().getTime() + 60 * 1000))
    .build();
final SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet);
signedJWT.sign(signer);
return signedJWT.serialize();
}
public static boolean isValidToken(String token, RSAPublicKey publicKey) throws Exception
{
return SignedJWT.parse(token).verify(new RSASSAVerifier(publicKey));
}
public static boolean isValidToken(String token, String publicKey) throws Exception
{
byte[] decoded = Base64.getDecoder().decode(publicKey);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPublicKey generatePublic = (RSAPublicKey) kf.generatePublic(spec);
    BigInteger modulus = generatePublic.getModulus();
    BigInteger exponent = generatePublic.getPublicExponent();
    return SignedJWT.parse(token).verify(new RSASSAVerifier(new RSAPublicKeyImpl(modulus, exponent)));
//return SignedJWT.parse(token).verify(new RSASSAVerifier(publicKey));
}
public static void main(String[] args) throws Exception {
final String algorithmType = "RSA";
final String algorithm = "SHA256withRSA";
final String dn = "CN=Rajakrishna Reddy, OU=OU, O=varra, L=Hyderabad, ST=TL, C=IN";
final int days = 365;
final KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(algorithmType);
keyGenerator.initialize(2048);
final KeyPair kp = keyGenerator.genKeyPair();
final X509Certificate certificate = generateCertificate(dn, kp, days, algorithm);
System.out.println("X09.Certificate: "+certificate);
//final String token = generateToken((RSAPrivateKey) kp.getPrivate());
final String token = "eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE1MjUyNDUyMDAsInN1YiI6IkpXVCIsInVzZXJfbWV0YWRhdGEiOiJ7XCJVc2VybmFtZVwiOlwibWNzYVwifSIsImlhdCI6MTUyNTE1ODgwMH0.wbroKZfrdGPGnk3OaPWbRr56rRzkg4DFO999jmSsut8IYAthKU0f26CIjWfrNPXD5asV74JYIS49VFNkFwbWfnIFETY1CaLIIm6F6NP5cFE7LW5G-y0qNRaCJgOLaFV4z4lsQOi0KAfuFVckiL5EHxhyBks-MCQEXMWO2JIBBZjAxhIH7fmhMHsYQQUxvm8Tx1dpnbvyh9E6x5F9BNZeS2DcBCqvzCuSUAz2DbgsJ-gVyrDRJgcItiCnscZy2u3sZq3XBTK2qBiSIpS4zVZupVS0f-5v57y7BvdVX2siuu-StN5614zvON_MJRgNLdo1yA1Y5F8eJ9IZrelMWB5GZw";
final String publiKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2hg1nqteEY12r5AO/enYD14aXEUaoqgvhtcHDwEPQwf9KqGpwoeC8jQE1qHfb2K1Wm/o4ug60Kv02f7AEJiNrUuKe9MYJdTr/DhekVrE0ttJkGCjLoNiVgMZHKH557Ouf6RsWJc5QjUiqxg6azwYUuHu2U199MZzFXvAVVUQR+hh8YqQM4KIQytOpj1JhxH7hQehth9vF5kIhA+K8htIIO04UF9+8ScrBHMQgj9q0RLperVQLxGsYT8cEZIn9tv1r47jynrTS0z/Vq2uVMGRg/bRPuo598++XUIglM92Ehbih87j//ATcHtsabefzBAVQuN4OaqLTT375JRAWpoWmQIDAQAB";
System.out.println("Token: "+token);
//System.out.println("Is valid?: "+isValidToken(token, (RSAPublicKey) kp.getPublic()));
System.out.println("Is valid?: "+isValidToken(token, publiKey));
//System.out.println(isValidToken(token, CertificateUtil.parseRSAPublicKey()));
}
}

Monday, December 18, 2017

How to remove untracked/ignored files and directories from git local repository


There is always be a need to remove the unwanted files and directories from the git to clean the git local repo, but sometimes it's a tedious job to do if we are not aware of some simple cool features that are offered by git, such as git clean, there is a wonderful and informative article available in git docs.

Here I wanted to give you some useful commands that do the required job of cleaning the untracked or ignored files and directories from the git repo.

This is written according to the git documentation provided here. This should not be considered as a complete guide to git clean.


  • Run this command to see what are the files or dirs going be removed: git clean -n  or   git clean --dry-run 

    So it doesn't actually remove anything, just show what would be done.
  • Run this command to delete the files or directories actually: git cleanBeware that it removes the files and directories permanently!!

    If you want to remove directories, run git clean -f -d or git clean -fd
    If you want to remove ignored files, run git clean -f -X or git clean -fX
    If you want to remove ignored and non-ignored files, run git clean -f -x or git clean -fx

  
It is always advisable to have a glance at the complete documentation at git! Have a look at git clean documentation for a clear understanding.

Monday, December 4, 2017

How to add line numbers attributes to java class files

Add this info to your javac command to add line number attributes to the generated class files: 

javac debug="true" debuglevel="lines,vars,source" includeantruntime="true"

Tuesday, November 7, 2017

[Solved] ORA-01034: ORACLE not available

Have you got stuck up with this error in Oracle DB startup?? Here is the solution:


D:\oracle\code>sqlplus system/Admin123@xe

SQL*Plus: Release 11.2.0.2.0 Production on Tue Nov 7 14:44:36 2017

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

ERROR:
ORA-01034: ORACLE not available
ORA-27101: shared memory realm does not exist
Process ID: 0
Session ID: 0 Serial number: 0


Enter user-name: system
Enter password:
ERROR:
ORA-01034: ORACLE not available
ORA-27101: shared memory realm does not exist
Process ID: 0
Session ID: 0 Serial number: 0

Enter user-name:

D:\oracle\code>sqlplus / as sysdba

SQL*Plus: Release 11.2.0.2.0 Production on Tue Nov 7 14:45:00 2017

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

Connected to an idle instance.

SQL>
SQL> startup
ORACLE instance started.

Total System Global Area 1068937216 bytes
Fixed Size                  2260048 bytes
Variable Size             637535152 bytes
Database Buffers          423624704 bytes
Redo Buffers                5517312 bytes
Database mounted.
SQL> exit

Disconnected from Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production


D:\oracle\code>sqlplus system/Admin123@xe

SQL*Plus: Release 11.2.0.2.0 Production on Tue Nov 7 14:47:02 2017

Copyright (c) 1982, 2014, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production

SQL> exit
Disconnected from Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production

D:\oracle\code>




Thursday, August 3, 2017

How can we add colors and format the text in console in python 3

class color:     PURPLE = '\033[95m'     CYAN = '\033[96m'     DARKCYAN = '\033[36m'     BLUE = '\033[94m'     GREEN = '\033[92m'     YELLOW = '\033[93m'     RED = '\033[91m'     BOLD = '\033[1m'     UNDERLINE = '\033[4m'     END = '\033[0m'    print color.BOLD + 'Hello World !' + color.END

Tuesday, February 14, 2017

How to push NuGet package to NuGet server with ApiKey

These are the simple 3 steps that you can run to achieve this: 


  1. v:\krishna\nuget.exe sources Add -Name TPaaS-Snapshot-nuget  -Source https://artifactory.trimble.tools/artifactory/TPaaS-Snapshot-nuget/ -username {{username}} -password {{ApiKey}}
  2. v:\krishna\nuget.exe setapikey {{username}}:{{ApiKey}} -source https://artifactory.trimble.tools/artifactory/TPaaS-Snapshot-nuget/
  3.  v:\krishna\nuget.exe push {{package-path}}.nupkg -Source TPaaS-Snapshot-nuget