<pre>
  BIP: 38


===Proposed specification===

* Object identifier prefix: 0x0142 (non-EC-multiplied) or 0x0143 (EC-multiplied).  These are constant bytes that appear at the beginning of the Base58Check-encoded record, and their presence causes the resulting string to have a predictable prefix.
* How the user sees it: 58 characters always starting with '6P'
** Visual cues are present in the third character for visually identifying the EC-multiply and compress flag.
* Count of payload bytes (beyond prefix): 37
** 1 byte (''flagbyte''): 
*** the most significant two bits are set as follows to preserve the visibility of the compression flag in the prefix, as well as to keep the payload within the range of allowable values that keep the "6P" prefix intact.  For non-EC-multiplied keys, the bits are 11.  For EC-multiplied keys, the bits are 00.
*** the bit with value 0x20 when set indicates the key should be converted to a base58check encoded P2PKH bitcoin address using the DER compressed public key format. When not set, it should be a base58check encoded P2PKH bitcoin address using the DER uncompressed public key format.
*** the bits with values 0x10 and 0x08 are reserved for a future specification that contemplates using multisig as a way to combine the factors such that parties in possession of the separate factors can independently sign a proposed transaction without requiring that any party possess both factors.  These bits must be 0 to comply with this version of the specification.
*** the bit with value 0x04 indicates whether a lot and sequence number are encoded into the first factor, and activates special behavior for including them in the decryption process.  This applies to EC-multiplied keys only.  Must be 0 for non-EC-multiplied keys.
*** remaining bits are reserved for future use and must all be 0 to comply with this version of the specification.
** 4 bytes: SHA256(SHA256(expected_bitcoin_address))[0...3], used both for typo checking and as salt
**16 bytes: Contents depend on whether EC multiplication is used.
**16 bytes: lasthalf: An AES-encrypted key material record (contents depend on whether EC multiplication is used)
* Range in base58check encoding for non-EC-multiplied keys without compression (prefix 6PR):
** Minimum value: 6PRHv1jg1ytiE4kT2QtrUz8gEjMQghZDWg1FuxjdYDzjUkcJeGdFj9q9Vi (based on 01 42 C0 plus thirty-six 00's)
** Maximum value: 6PRWdmoT1ZursVcr5NiD14p5bHrKVGPG7yeEoEeRb8FVaqYSHnZTLEbYsU (based on 01 42 C0 plus thirty-six FF's) 
* Range in base58check encoding for non-EC-multiplied keys with compression (prefix 6PY):
** Minimum value: 6PYJxKpVnkXUsnZAfD2B5ZsZafJYNp4ezQQeCjs39494qUUXLnXijLx6LG (based on 01 42 E0 plus thirty-six 00's)
** Maximum value: 6PYXg5tGnLYdXDRZiAqXbeYxwDoTBNthbi3d61mqBxPpwZQezJTvQHsCnk (based on 01 42 E0 plus thirty-six FF's) 
* Range in base58check encoding for EC-multiplied keys without compression (prefix 6Pf):
** Minimum value: 6PfKzduKZXAFXWMtJ19Vg9cSvbFg4va6U8p2VWzSjtHQCCLk3JSBpUvfpf (based on 01 43 00 plus thirty-six 00's)
** Maximum value: 6PfYiPy6Z7BQAwEHLxxrCEHrH9kasVQ95ST1NnuEnnYAJHGsgpNPQ9dTHc (based on 01 43 00 plus thirty-six FF's)
* Range in base58check encoding for EC-multiplied keys with compression (prefix 6Pn):
** Minimum value: 6PnM2wz9LHo2BEAbvoGpGjMLGXCom35XwsDQnJ7rLiRjYvCxjpLenmoBsR (based on 01 43 20 plus thirty-six 00's)
** Maximum value: 6PnZki3vKspApf2zym6Anp2jd5hiZbuaZArPfa2ePcgVf196PLGrQNyVUh (based on 01 43 20 plus thirty-six FF's)



====Encryption when EC multiply mode is used====
Encrypting a private key with EC multiplication offers the ability for someone to generate encrypted keys knowing only an EC point derived from the original passphrase and some salt generated by the passphrase's owner, and without knowing the passphrase itself.  Only the person who knows the original passphrase can decrypt the private key.  A code known as an ''intermediate code'' conveys the information needed to generate such a key without knowledge of the passphrase.

This methodology does not offer the ability to encrypt a known private key - this means that the process of creating encrypted keys is also the process of generating new addresses.  On the other hand, this serves a security benefit for someone possessing an address generated this way: if the address can be recreated by decrypting its private key with a passphrase, and it's a strong passphrase one can be certain only he knows himself, then he can safely conclude that nobody could know the private key to that address.

The person who knows the passphrase and who is the intended beneficiary of the private keys is called the ''owner''.  He will generate one or more "intermediate codes", which are the first factor of a two-factor redemption system, and will give them to someone else we'll call ''printer'', who generates a key pair with an intermediate code can know the address and encrypted private key, but cannot decrypt the private key without the original passphrase.

An intermediate code should, but is not required to, embed a printable "lot" and "sequence" number for the benefit of the user.  The proposal forces these lot and sequence numbers to be included in any valid private keys generated from them.  An owner who has requested multiple private keys to be generated for him will be advised by applications to ensure that each private key has a unique lot and sequence number consistent with the intermediate codes he generated.  These mainly help protect ''owner'' from potential mistakes and/or attacks that could be made by ''printer''.

The "lot" and "sequence" number are combined into a single 32 bit number.  20 bits are used for the lot number and 12 bits are used for the sequence number, such that the lot number can be any decimal number between 0 and 1048575, and the sequence number can be any decimal number between 0 and 4095.  For programs that generate batches of intermediate codes for an ''owner'', it is recommended that lot numbers be chosen at random within the range 100000-999999 and that sequence numbers are assigned starting with 1.

Steps performed by ''owner'' to generate a single intermediate code, if lot and sequence numbers are being included:
# Generate 4 random bytes, call them ''ownersalt''.
# Encode the lot and sequence numbers as a 4 byte quantity (big-endian): lotnumber * 4096 + sequencenumber.  Call these four bytes ''lotsequence''.
# Concatenate ''ownersalt'' + ''lotsequence'' and call this ''ownerentropy''.
# Derive a key from the passphrase using scrypt
#* Parameters: ''passphrase'' is the passphrase itself encoded in UTF-8 and normalized using Unicode Normalization Form C (NFC).  salt is ''ownersalt''. n=16384, r=8, p=8, length=32.
#* Call the resulting 32 bytes ''prefactor''.
#* Take SHA256(SHA256(''prefactor'' + ''ownerentropy'')) and call this ''passfactor''. The "+" operator is concatenation.
# Compute the elliptic curve point G * ''passfactor'', and convert the result to compressed notation (33 bytes).  Call this ''passpoint''.  Compressed notation is used for this purpose regardless of whether the intent is to create Bitcoin addresses with or without compressed public keys.
# Convey ''ownersalt'' and ''passpoint'' to the party generating the keys, along with a checksum to ensure integrity.
#* The following Base58Check-encoded format is recommended for this purpose: magic bytes "2C E9 B3 E1 FF 39 E2 51" followed by ''ownerentropy'', and then ''passpoint''.  The resulting string will start with the word "passphrase" due to the constant bytes, will be 72 characters in length, and encodes 49 bytes (8 bytes constant + 8 bytes ''ownerentropy'' + 33 bytes ''passpoint'').  The checksum is handled in the Base58Check encoding.  The resulting string is called ''intermediate_passphrase_string''.

If lot and sequence numbers are not being included, then follow the same procedure with the following changes:
* ''ownersalt'' is 8 random bytes instead of 4, and ''lotsequence'' is omitted.  ''ownerentropy'' becomes an alias for ''ownersalt''.
* The SHA256 conversion of ''prefactor'' to ''passfactor'' is omitted.  Instead, the output of scrypt is used directly as ''passfactor''.
* The magic bytes are "2C E9 B3 E1 FF 39 E2 53" instead (the last byte is 0x53 instead of 0x51).

Steps to create new encrypted private keys given ''intermediate_passphrase_string'' from ''owner'' (so we have ''ownerentropy'', and ''passpoint'', but we do not have ''passfactor'' or the passphrase):
# Set ''flagbyte''.
#* Turn on bit 0x20 if the Bitcoin address will be formed by hashing the compressed public key (optional, saves space, but many Bitcoin implementations aren't compatible with it)
#* Turn on bit 0x04 if ''ownerentropy'' contains a value for ''lotsequence''.  (While it has no effect on the keypair generation process, the decryption process needs this flag to know how to process ''ownerentropy'')
# Generate 24 random bytes, call this ''seedb''.  Take SHA256(SHA256(''seedb'')) to yield 32 bytes, call this ''factorb''.
# ECMultiply ''passpoint'' by ''factorb''.  Use the resulting EC point as a public key and hash it into a Bitcoin address using either compressed or uncompressed public key methodology (specify which methodology is used inside ''flagbyte'').  This is the generated Bitcoin address, call it ''generatedaddress''.
# Take the first four bytes of SHA256(SHA256(''generatedaddress'')) and call it ''addresshash''.
# Now we will encrypt ''seedb''.  Derive a second key from ''passpoint'' using scrypt
#*Parameters: ''passphrase'' is ''passpoint'' provided from the first party (expressed in binary as 33 bytes).  ''salt'' is ''addresshash'' + ''ownerentropy'', n=1024, r=1, p=1, length=64.  The "+" operator is concatenation.
#*Split the result into two 32-byte halves and call them ''derivedhalf1'' and ''derivedhalf2''.
# Do AES256Encrypt(block = (seedb[0...15] xor derivedhalf1[0...15]), key = derivedhalf2), call the 16-byte result ''encryptedpart1''
# Do AES256Encrypt(block = ((encryptedpart1[8...15] + seedb[16...23]) xor derivedhalf1[16...31]), key = derivedhalf2), call the 16-byte result ''encryptedpart2''.  The "+" operator is concatenation.

The encrypted private key is the Base58Check-encoded concatenation of the following, which totals 39 bytes without Base58 checksum:
* 0x01 0x43 + ''flagbyte'' + ''addresshash'' + ''ownerentropy'' + ''encryptedpart1''[0...7] + ''encryptedpart2''

=====Confirmation code=====
The party generating the Bitcoin address has the option to return a ''confirmation code'' back to ''owner'' which allows ''owner'' to independently verify that he has been given a Bitcoin address that actually depends on his passphrase, and to confirm the lot and sequence numbers (if applicable).  This protects ''owner'' from being given a Bitcoin address by the second party that is unrelated to the key derivation and possibly spendable by the second party.  If a Bitcoin address given to ''owner'' can be successfully regenerated through the confirmation process, ''owner'' can be reasonably assured that any spending without the passphrase is infeasible.  This confirmation code is 75 characters starting with "cfrm38".

To generate it, we need ''flagbyte'', ''ownerentropy'', ''factorb'', ''derivedhalf1'' and ''derivedhalf2'' from the original encryption operation.
# ECMultiply ''factorb'' by G, call the result ''pointb''.  The result is 33 bytes.
# The first byte is 0x02 or 0x03.  XOR it by (derivedhalf2[31] & 0x01), call the resulting byte ''pointbprefix''.
# Do AES256Encrypt(block = (pointb[1...16] xor derivedhalf1[0...15]), key = derivedhalf2) and call the result ''pointbx1''.
# Do AES256Encrypt(block = (pointb[17...32] xor derivedhalf1[16...31]), key = derivedhalf2) and call the result ''pointbx2''.
# Concatenate ''pointbprefix'' + ''pointbx1'' + ''pointbx2'' (total 33 bytes) and call the result ''encryptedpointb''.

The result is a Base58Check-encoded concatenation of the following:
* 0x64 0x3B 0xF6 0xA8 0x9A + ''flagbyte'' + ''addresshash'' + ''ownerentropy'' + ''encryptedpointb''

A confirmation tool, given a passphrase and a confirmation code, can recalculate the address, verify the address hash, and then assert the following: "It is confirmed that Bitcoin address ''address'' depends on this passphrase".  If applicable: "The lot number is ''lotnumber'' and the sequence number is ''sequencenumber''."

To recalculate the address:
# Derive ''passfactor'' using scrypt with ''ownerentropy'' and the user's passphrase and use it to recompute ''passpoint''
# Derive decryption key for ''pointb'' using scrypt with ''passpoint'', ''addresshash'', and ''ownerentropy''
# Decrypt ''encryptedpointb'' to yield ''pointb''
# ECMultiply ''pointb'' by ''passfactor''. Use the resulting EC point as a public key and hash it into ''address'' using either compressed or uncompressed public key methodology as specifid in ''flagbyte''.

=====Decryption=====
# Collect encrypted private key and passphrase from user.
# Derive ''passfactor'' using scrypt with ''ownersalt'' and the user's passphrase and use it to recompute ''passpoint''
# Derive decryption key for ''seedb'' using scrypt with ''passpoint'', ''addresshash'', and ''ownerentropy''
# Decrypt ''encryptedpart2'' using AES256Decrypt to yield the last 8 bytes of ''seedb'' and the last 8 bytes of ''encryptedpart1''.
# Decrypt ''encryptedpart1'' to yield the remainder of ''seedb''.
# Use ''seedb'' to compute ''factorb''.
# Multiply ''passfactor'' by ''factorb'' mod N to yield the private key associated with ''generatedaddress''.
# Convert that private key into a Bitcoin address, honoring the compression preference specified in the encrypted key.
# Hash the Bitcoin address, and verify that ''addresshash'' from the encrypted private key record matches the hash.  If not, report that the passphrase entry was incorrect.

==Backwards compatibility==
Backwards compatibility is minimally applicable since this is a new standard that at most extends [[Wallet Import Format]].  It is assumed that an entry point for private key data may also accept existing formats of private keys (such as hexadecimal and [[Wallet Import Format]]); this draft uses a key format that cannot be mistaken for any existing one and preserves auto-detection capabilities.

==Suggestions for implementers of proposal with alt-chains==
If this proposal is accepted into alt-chains, it is requested that the unused flag bytes not be used for denoting that the key belongs to an alt-chain.

Alt-chain implementers should exploit the address hash for this purpose.  Since each operation in this proposal involves hashing a text representation of a coin address which (for Bitcoin) includes the leading '1', an alt-chain can easily be denoted simply by using the alt-chain's preferred format for representing an address.  Alt-chain implementers may also change the prefix such that encrypted addresses do not start with "6P".

==Discussion item: scrypt parameters==
This proposal leaves the scrypt parameters up in the air.  The following items are proposed for consideration:

The main goal of scrypt is to reduce the feasibility of brute force attacks.  It must be assumed that an attacker will be able to use an efficient implementation of scrypt.  The parameters should force a highly efficient implementation of scrypt to wait a decent amount of time to slow attacks.

On the other hand, an unavoidably likely place where scrypt will be implemented is using slow interpreted languages such as javascript.  What might take milliseconds on an efficient scrypt implementation may take seconds in javascript.

It is believed, however, that someone using a javascript implementation is probably dealing with codes by hand, one at a time, rather than generating or processing large batches of codes.  Thus, a wait time of several seconds is acceptable to a user.

A private key redemption process that forces a server to consume several seconds of CPU time would discourage implementation by the server owner, because they would be opening up a denial of service avenue by inviting users to make numerous attempts to invoke the redemption process.  However, it's also feasible for the server owner to implement his redemption process in such a way that the decryption is done by the user's browser, offloading the task from his own server (and providing another reason why the chosen scrypt parameters should be tolerant of javascript-based decryptors).

The preliminary values of 16384, 8, and 8 are hoped to offer the following properties:
* Encryption/decryption in javascript requiring several seconds per operation
* Use of the parallelization parameter provides a modest opportunity for speedups in environments where concurrent threading is available - such environments would be selected for processes that must handle bulk quantities of encryption/decryption operations.  Estimated time for an operation is in the tens or hundreds of milliseconds.


 

Java online compiler

Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.

Taking inputs (stdin)

OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).

import java.util.Scanner;
class Input {
    public static void main(String[] args) {
    	Scanner input = new Scanner(System.in);
    	System.out.println("Enter your name: ");
    	String inp = input.next();
    	System.out.println("Hello, " + inp);
    }
}

Adding dependencies

OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies

apply plugin:'application'
mainClassName = 'HelloWorld'

run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }

repositories {
    jcenter()
}

dependencies {
    // add dependencies here as below
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}

About Java

Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.

Syntax help

Variables

short x = 999; 			// -32768 to 32767
int   x = 99999; 		// -2147483648 to 2147483647
long  x = 99999999999L; // -9223372036854775808 to 9223372036854775807

float x = 1.2;
double x = 99.99d;

byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;

Loops

1. If Else:

When ever you want to perform a set of operations based on a condition If-Else is used.

if(conditional-expression) {
  // code
} else {
  // code
}

Example:

int i = 10;
if(i % 2 == 0) {
  System.out.println("i is even number");
} else {
  System.out.println("i is odd number");
}

2. Switch:

Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.

switch(<conditional-expression>) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 //code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.

for(Initialization; Condition; Increment/decrement){  
    //code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(<condition>){  
 // code 
}  

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {
  // code 
} while (<condition>); 

Classes and Objects

Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.

How to create a Class:

class keyword is required to create a class.

Example:

class Mobile {
    public:    // access specifier which specifies that accessibility of class members 
    string name; // string variable (attribute)
    int price; // int variable (attribute)
};

How to create a Object:

Mobile m1 = new Mobile();

How to define methods in a class:

public class Greeting {
    static void hello() {
        System.out.println("Hello.. Happy learning!");
    }

    public static void main(String[] args) {
        hello();
    }
}

Collections

Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.

Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:

  1. Interfaces
  2. Classes
  3. Algorithms

This framework also defines map interfaces and several classes in addition to Collections.

Advantages:

  • High performance
  • Reduces developer's effort
  • Unified architecture which has common methods for all objects.
CollectionDescription
SetSet is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc
ListList is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors
QueueFIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue.
DequeDeque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail)
MapMap contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc.