This topic has
9
replies
on
1
page.
Hi,
i've found a nice function which converts my byte array to a hex string.
static char [] hexChar = {
'0' , '1' , '2' , '3' ,
'4' , '5' , '6' , '7' ,
'8' , '9' , 'A' , 'B' ,
'C' , 'D' , 'E' , 'F'
} ;
public static String toHexString ( byte [] b ) {
StringBuffer sb = new StringBuffer( b.length * 2 );
for ( int i=0; i<b.length; i++ ) {
// look up high nibble char
sb.append( hexChar [( b[i] & 0xf0 ) >>> 4] ); // fill left with zero bits
// look up low nibble char
sb.append( hexChar [b[i] & 0x0f] );
}
return sb.toString();
}
It's working fine, but i need the conversion in the other direction. It should be very easy, but i didn't get it.
I first tried to use simply
byte [] bArray = hexStr.getBytes();
but it seems to be something different.
But why is it different?
paulcw
Posts:17,590
Registered: 2/22/00
It's different because it returns the bytes of the characters representing the original bytes, not the original bytes themselves, which is presumably what you want.
To convert back, you can take 2-char substrings and pass them to Integer.parseInt(theSubString, 16).
paulcw
Posts:17,590
Registered: 2/22/00
And come to think of it you could have converted to a hex string using Integer.toHexString on each byte, rather than maintaining the list of hex chars yourself.
Thank you!
It's finally working.
public static byte [] toBinArray( String hexStr ){
byte bArray[] = new byte [hexStr.length()/2];
for (int i=0; i<(hexStr.length()/2); i++){
byte firstNibble = Byte.parseByte(hexStr.substring(2*i,2*i+1),16); // [x,y)
byte secondNibble = Byte.parseByte(hexStr.substring(2*i+1,2*i+2),16);
int finalByte = (secondNibble) | (firstNibble << 4 ); // bit-operations only with numbers, not bytes.
bArray[i] = (byte ) finalByte;
}
return bArray;
}
paulcw
Posts:17,590
Registered: 2/22/00
Maybe I don't get what you're doing but couldn't you have done this?
public static byte [] toBinArray( String hexStr ) {
byte bArray[] = new byte [hexStr.length()/2];
for (int i=0; i< bArray.length; i++) {
bArray[i] = Byte.parseByte(hexStr.substring(2*i,2*i+2),16);
}
return bArray;
}
awyork
Posts:42
Registered: 3/6/01
Maybe I don't get what you're doing but couldn't you
have done this?
public static byte [] toBinArray( String hexStr
) {
byte bArray[] = new byte [hexStr.length()/2];
for (int i=0; i< bArray.length; i++) {
bArray[i] =
Byte.parseByte(hexStr.substring(2*i,2*i+2),16);
}
return bArray;
Ignore the above post, it doesn't work. For some reason Sun calls "a2" an invalid hex value.
JosAH
Posts:13,022
Registered: 4/6/04
Ignore the above post, it doesn't work. For some
reason Sun calls "a2" an invalid hex value.
Nope, don't spread non-understood rumours. A byte can take values in
the range [-128, 127] (in hexadecimal notation: [0x80, 0x7f]) because
byte type values are assumed to be
signed values.
The best thing to do is to use a
wider int type, use that one and cast
the value back to a byte type. (byte)Integerer.parseInt(String, 16) comes
to mind.
kind regards,
Jos
awyork
Posts:42
Registered: 3/6/01
The value 0xFF is -1 in two's compliment. Why isn't that a valid byte balue then?
I have read this Thread and I am not able to get the solution of my Problem.
I got two codes:
1)SHA that generates the Encrypted Value in form of String.
2)DES that takes a key and encrypts the data using that Key.
Now the problem is that I need to convert the String (generated by SHA) to SecretKey Format (which will be inputted into DES).
I have tried the code given in this thread but I am not able to solve the problem.
Code for SHA:
import java.lang.;
import java.io. ;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
//import org.myorg.SystemUnavailableException;
//import java.security.NoSuchAlgorithmException;
//import javax.crypto.spec.;
import sun.misc.BASE64Encoder;
import sun.misc.CharacterEncoder;
import javax.crypto.spec.DESKeySpec. ;
import javax.crypto.;
/*public / final class PasswordService
{
/private / static PasswordService instance;
/private / PasswordService()
{
}
public synchronized String encrypt(String plaintext) //throws SystemUnavailableException
{
MessageDigest md = null;
try
{
md = MessageDigest.getInstance("SHA"); //step 2
}
catch(NoSuchAlgorithmException e)
{
System.out.println("1"); //throw new SystemUnavailableException(e.getMessage());
}
try
{
md.update(plaintext.getBytes("UTF-8")); //step 3
}
catch(UnsupportedEncodingException e)
{
System.out.println("2"); //throw new SystemUnavailableException(e.getMessage());
}
byte raw[] = md.digest(); //step 4
System.out.println("Digest"raw);
String hash = (new BASE64Encoder()).encode(raw); //step 5
return hash; //step 6
}
public static synchronized PasswordService getInstance() //step 1
{
if(instance == null)
{
instance = new PasswordService();
}
return instance;
}
}
class Mainclass
{
public static void main(String args[])
{
PasswordService p ;
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str=new String();
String hash=new String();
System.out.println("Enter the password");
str=br.readLine();
p=PasswordService.getInstance();
System.out.println("p:"+p);
hash=p.encrypt(str);
System.out.println("hash:"+hash);
byte bData[]=hash.getBytes();
System.out.println("Bytes: "+bData);
int code=hash.hashCode();
System.out.println("Code:"+code);
}
}
catch(Exception e)
{
System.out.println("Exception"+e);
}
}
}
Code for DES:
import javax.crypto.;
/*import java.io. ;
import java.security.;
import java.math. ;
import cryptix.util.core.;
import cryptix.provider.key. ;/
class DesEncrypter
{
/ Creating objects of type Cipher /
Cipher ecipher;
Cipher dcipher;
/ Constructor of the Class DesEncrypter /
DesEncrypter(SecretKey key)
{
try
{
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
catch (javax.crypto.NoSuchPaddingException e)
{
System.out.println("NoSuchPaddingException");
}
catch (java.security.NoSuchAlgorithmException e)
{
System.out.println("NoSuchAlgorithmException");
}
catch (java.security.InvalidKeyException e)
{
System.out.println("InvalidKeyException");
}
}
public String encrypt(String str)
{
try
{
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
}
catch (javax.crypto.BadPaddingException e)
{
System.out.println("BadPaddingException");
}
catch (IllegalBlockSizeException e)
{
System.out.println("IllegalBlockSizeException");
}
/ catch (UnsupportedEncodingException e)
{
System.out.println("UnsupportedEncodingException");
}/
catch (java.io.IOException e)
{
System.out.println("IOException");
}
return null;
}
public String decrypt(String str)
{
try
{
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
}
catch (javax.crypto.BadPaddingException e)
{
System.out.println("BadPaddingException");
}
catch (IllegalBlockSizeException e)
{
System.out.println("IllegalBlockSizeException");
}
/ catch (UnsupportedEncodingException e)
{
System.out.println("UnsupportedEncodingException");
}/
catch (java.io.IOException e)
{
System.out.println("IOException");
}
return null;
}
}
/ Here's an example that uses the class: /
class MyDes
{
public static void main(String args[])
{
try
{
// Generate a temporary key. In practice, you would save this key.
// See also e464 Encrypting with DES Using a Pass Phrase.
/*RawSecretKey key2=new RawSecretKey("DES",Hex.fromString("3812A419C63BE771"));
System.out.println("Key2"+key2); /
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter(key);
// Encrypt
String encrypted = encrypter.encrypt("Hi Kerberos!! How are You?");
System.out.println("Encrypted String: " encrypted);
// Decrypt
String decrypted = encrypter.decrypt(encrypted);
System.out.println("Decrypted String: "+ decrypted);
}
catch (Exception e)
{
System.out.println("Exception"+e);
}
}
}
public String toHexString(byte[] in){
BigInteger temp = new BigInteger(in);
return temp.toString(16);
}
public byte[] fromHexString(String in){
BigInteger temp = new BigInteger(in, 16);
return temp.toByteArray();
}
you can try this two simple methods
This topic has
9
replies
on
1
page.
Back to Forum
Read the Developer Forums Code of Conduct
Email this Topic
Edit this Topic
Site Upgrade
Forums 7.1.8 was deployed Oct 26th. The release consists of minor fixes & a few enhancements.
Forums Statistics
Users Online : 28 Guests : 133
About Sun forums
Oracle Forums is a large collection of user generated
discussions. It is here to help you ask questions, find answers, and
participate in discussions.
Check out our guide on Getting
started with Oracle Forums for a full walkthrough of how to best
leverage the benefits of this community.