ENOEHT's Java Source Series (5) - Character Series Decryption

zhaozj2021-02-16  53

The content of this is a simple class that decrypts characters:

Then call its encrypt or decrypt method with an authenticator byte array (the parameter Auth which is a 16 octet byte array) and the data which is wanted to be encoded or decoded, the result is a byte array you wanted.

Package org.kyle.util;

Import java.security. *;

Import java.io. *;

Import java.text. *;

Import java.util. *;

Import java.math. *;

/ * Call The Shared Secret S and The Pseudo-Random 128-bit

Authenticator Ra. Break The Password Into 16-OcTet Chunks P1, P2,

Etc. with the last one padded at the end with nulls to a 16-octet

Boundary. Call The Ciphertext Blocks C (1), C (2), etc. We'll NEED

Intermediate Values ​​B1, B2, ETC.

B1 = MD5 (S RA) C (1) = p1 xor b1

B2 = MD5 (S C (1)) C (2) = p2 xor b2

.

.

.

Bi = MD5 (S C (I-1)) c (i) = pi xor bi

THE STRING WILL CONTAIN C (1) C (2) ... C (i) Where Denotes

Concatenation.

On Receipt, The Process Is Reverse To Yield The Original

Password.

* /

Public Class Cryptology

{

/ ** Hidden Secret Data for Encryption and Decryption. * /

Private Byte [] m_secret;

/ ** Default Secret Length. * /

Private int m_defaultsecretLength = 256;

/ **

* Default constructor to create Object with default Hidden Secret.

* /

Public Cryptology () PUBLIC CRYPTOLOGY ()

{

m_secret = CreateSecret (M_DefaultSecretLength, Normalize (). getName ()));

}

/ **

* Allow to use user desired Hidden Secret To Instantiate this Object.

* @Param Specsecret The User Desired Hidden Secret String.

* @Param Secretlen the length of secret in bytes.

* /

Public Cryptology (String Specsecret, int SECRETLEN)

{

IF (SpecSecret == Null) specsecret = getClass (). getname ();

m_secret = CREATESECRET (Secretlen, Normalize (SpecSecret);

}

/ **

* SET A New Shared Secret for Encryption and Decryption.

* @Param newsecret Byte [] The New Shared Secret.

* /

Public void setsecret (Byte [] newsecret

{

m_secret = newsecret;

}

/ **

* Set a string for shared secret.

* /

Public void setsecret (String Therecret)

{

m_secret = Normalize (THESECRET);

}

Public Byte [] getsecret ()

{

Return m_secret;

}

/ **

Encrypting the Rawdata with Random Auth value.

* /

Public Byte [] encrypt (byte [] rawdata, byte [] auth)

{

// if no secret or no automator data, don't Encrypt The Rawdata.

IF (Rawdata == Null ||

Auth == null ||

Auth.Length! = 16 ||

m_secret == NULL)

Return Rawdata;

ArrayList CBlocks = getCipherblocks (getchunks (Rawdata), AUTH, TRUE;

Return Concatchunks (CBLOCKS);

}

/ **

Decoding The Encoded Data (Encdata) with Given Authenticator Array (Auth). The result is the byte array of plain value.

* /

Public Byte [] Decrypt (byte [] encData, byte [] auth

{

// if no secret or no automator data, don't decrypt the Encdata.

IF (encData == null ||

Auth == null ||

Auth.Length! = 16 ||

m_secret == NULL)

Return ENCDATA;

ArrayList CBLOCKS = GetCipherblocks (Getchunks (EncData), Auth, False;

Return Concatchunks (CBLOCKS);

}

/ **

* Data to Be Encrypted Should Be Normalized to Multiple 16 OCTES FIRST.

* Origin String Should Be Encoded to Bytes in UTF-8. IF UTF-8 Not Supported, * Null Will Be Returned.

* /

Public static Byte [] Normalize (String WDATA)

{

Try

{

Byte Odata [] = WData.getbytes ("UTF-8"); // Return Bnormalize (ODATA);

Return Odata;

}

Catch (unsupportedencodingexception UEE)

{

//Debug.println (New DBGMSG (UEE, 3));

Debug.Warning ("Normalize Unsupportedencodingexception In Class Cryptology);

}

Return NULL;

}

/ **

* Get the utf-8 encoded string of a decrypted byte arch.

* @Param Odata Byte Array Which Was Decrypted from an encrypted byte Array.

* @Return String Encoded in UTF-8. if Odata Length is Zero,

* EMPTY STRING RETURNED, IF UTF-8 Not Supported, NULL RETURNED.

* /

Public static string rnormalize (byte odata [])

{

Int wdlen = odata.length;

//Debug.println ("raw data length: " wdlen);

IF (wdlen == 0) Return "";

Try

{

Return New String (OData, "UTF-8");

}

Catch (unsupportedencodingexception UEE)

{

Debug.Warning ("Normalize Unsupportedencodingexception In Class Cryptology);

}

Return NULL;

}

Private Byte [] Concatchunks (ArrayList Chunks)

{

IF (chunks == null) Return New Byte [0];

BYTEARRAYOUTPUTSTREAM baos = new byteArrayoutputStream ();

For (int i = 0; i

{

Biginteger bgint = (Biginteger) Chunks.get (i);

Byte [] CBYTES = BGINT.TOBYTEARRAY ();

Baos.Write (Cbytes, 0, CBYTES.LENGTH);

}

Return baos.tobytearray ();

}

//

Private arraylist getcipherblocks (arraylist pchunks, byte [] rabytes, boolean cipher)

{

IF (m_secret == null || rabytes == null || pchunks == null) Return NULL;

BYTE [] ss = new byte [m_secret.length];

System.ArrayCopy (m_secret, 0, s, 0, m_secret.length);

Iterator IPS = PChunks.ITerator ();

ArrayList Cipherblocks = New ArrayList (pchunks.size ()); Biginteger Bi = GetMedcialue (SS, RABYTES);

String interface = "intermedium integer:" bi.intValue () "/ n";

String ciph = "";

While (ips.hasnext ())

{

Biginteger Pi = (Biginteger) ips.next ();

Biginteger Ci = Cipherblock (PI, BI);

// Error Occurred, Invalid Password Not Necessary to be createdebug.println ("Intermediate Integer:" bi.intValue ()); ED.

IF (CI == Null) Return NULL;

Cipherblocks.Add (CI);

// CIPH = "CREATED CIPHERED INTEGER:" CI.intValue () "(Bitlen:" Ci.bitLength () ") / n";

IF (cipher)

Bi = getIntmedivalue (ss, ci.tobytearray ());

Else

Bi = getIntmedivalue (ss, pi.tobytearay ());

// Inter = "Intermediate integer:" (bi == null? "null": bi.intValue () (Bitlen: " bi.bitLength ()") / n ");

}

//Debug.println (new dbgmsg (inter, debug.trace_in);

//Debug.println (new dbgmsg (ciph, debug.trace_in);

Return Cipherblocks;

}

Private arraylist getchunks (byte [] rawpwd)

{

IF (Rawpwd == Null) Return NULL;

INT chunkcnt = (Rawpwd.Length 15) / 16;

ArrayList Chunks = New ArrayList (chunkcnt);

BYTEARRAYINPUTSTREAM Bais = New byteArrayInputStream (Rawpwd);

String msg = "";

For (int i = 0; i

{

INT LEN = Bais.available ();

IF (len> 16) len = 16;

Byte [] chunk = new byte [16];

Int Bitlen = Bais.read (chunk, 0, len);

//Debug.println ("AREAD BYTES:" Bitlen "; Value:" (New String (chunk));

IF (Bitlen! = -1) {

IF (Len <16)

Arrays.Fill (CHUNK, LEN, 15, (Byte) 0x00);

Biginteger Bi = New Biginteger (Chunk);

Chunks.Add (BI);

}

}

//Debug.println (new dbgmsg (msg, debug.trace_in);

Return chunks;

}

Private Biginteger getIntmediValue (byte [] second, byte [] raorct)

{

IF (Secret == null || raorct == null || raorct.Length <16) Return NULL;

Try

{

MessageDigest Msgdgt = MessageDigest.getInstance ("MD5");

Byte [] INPUT = New Byte [Secret.length raorct.length];

System.ArrayCopy (Secret, 0, Input, 0, Secret.length);

System.ArrayCopy (raorct, 0, input, secret.length, raorct.length);

Return New Biginteger (Msgdgt.Digest (Input));

}

Catch (NosuchalgorithMexception NSAE)

{

Debug.warning ("Normalize Nosuchalgorithmexception In Class Cryptology);

}

Return NULL;

}

Private Biginteger Cipherblock (Biginteger Pi, Biginteger Bi)

{

IF (pi == null || bi == null) Return NULL;

Biginteger CPBK = pi.xor (bi);

Return CPBK;

}

/ **

* If a password's length is less 16, it will be padded

* To 16 with null. This Makes ITS Decrypted Value Have A

* Invalid Tail Encoded in the Nulls. This Method Will Compare

* The string from decrypted bytes and stiled Origin String

* with the palming nulls tail considered.

* @Param DecryptedPwd The Restored Password String

* Created from decrypted bytes.

* @Param StoredPwd The Origin Password Stored

* For authentication.

* @Return Boolean True IF and Only if The DecryptedPWD

* Is started with storedpwd and appended

* BY a serias of nulls or none. * /

Public Static Boolean Equals (String DecryptedPwd, String StoredPwd)

{

Try

{

IF (decryptedpwd.length ()

Byte [] DP = DecryptedPwd.getbytes ("ISO-8859-1");

Byte [] sp = storedpwd.getbytes ("ISO-8859-1");

IF (DP.LENGTH> Sp.Length)

{

INT tlen = dp.length - sp.Length;

Byte [] SPE = New byte [TLEN];

Arrays.Fill (Spe, (Byte) 0x00);

BYTEARRAYOUTPUTSTREAM baos = new byteArrayoutputStream ();

Baos.Write (SP);

Baos.Write (SPE);

sp = baos.tobytearray ();

}

Return Arrays.Equals (DP, SP);

}

Catch (Exception E)

{

Debug.warning ("Normalize Exception In Class Cryptology);

}

Return False;

}

Private Byte [] CreateSecret (Int Len, Byte [] SEED

{

IF (SEED == NULL)

{

Seed = normalize (getClass (). getname ());

}

IF (len <= 0) len = m_defaultsecretLength;

Securerandom Scrdm = New Securerandom (SEED);

BYTE [] ASEC = New byte [len];

SCRDM.NEXTBYTES (ASEC);

Return ASEC;

}

/ **

* If a password's length is less 16, it will be padded

* To 16 with null. This Makes ITS Decrypted Value Have A

* INVALID TAIL ENCODEDION THE NULLS. THIS Method Will Cut the

* INVALID TAIL AND RETURN The "Clear" DATA.

* @Param data byte [] The Origin Decrypted byte Array.

* @Return Byte [] bytes from data without the nulls tail.

* If any Exception Occurred, NULL RETURNED.

* /

Public static botty [] getcleardata (byte [] data)

{

Try

{

StringBuffer SB = new stringbuffer ();

SB.Append (New String (Data, "ISO-8859-1));

sb.reverse ();

Biginteger RBI = New Biginteger (sb.tostring (). GetBytes ("ISO-8859-1"); SB = New StringBuffer ();

Sb.append (new string (rbi.tobytearray (), "ISO-8859-1"));

sb.reverse ();

Return sb.toString (). GetBytes ("ISO-8859-1");

}

Catch (Exception E)

{

Debug.warning ("Normalize Exception In Class Cryptology);

}

Return NULL;

}

/ *

// for test

Public static void main (String Argv [])

{

Cryptology Crypto = New Cryptology ();

IF (argv.length <1)

{

System.exit (0);

}

// store default secret to file default.sec

Try

{

FileOutputStream Fos = New FileoutputStream ("default.sec");

Fos.write (crypto.getSecret ());

Fos.close ();

}

Catch (IOException E) {}

IF (argv.Length == 2)

Crypto.setsecret (Argv [1]);

Securerandom SCRDM = New Securerandom (Securerandom.getSeed (16));

Byte [] auth = new byte [16];

SCRDM.NEXTBYTES (Auth);

String Rawstr = argv [0];

System.out.println ("Origin String:" RawStr);

Byte [] scstr = crypto.normalize (rawstr);

IF (scstr == null)

{

System.out.println ("Normalization of Origin String Failed.");

System.exit (0);

}

Try

{

SCSTR = Crypto.encrypt (SCSTR, AUTH);

System.out.println ("Encrypted String:" Crypto.rnormalize (SCSTR); bytescount: " scstr.length);

SCSTR = Crypto.decrypt (SCSTR, AUTH);

System.out.println ("Decrypted String:" Crypto.rnormalize (SCSTR));

System.out.println ("Cleared Decrypted Password:" (Cryptology.getCleardata))))))

}

Catch (Exception UEE)

{}

}

* /

}

转载请注明原文地址:https://www.9cbs.com/read-21311.html

New Post(0)