Re: Encryption Code Problem
Re: Encryption Code Problem
- Subject: Re: Encryption Code Problem
- From: Georg Tuparev <email@hidden>
- Date: Mon, 16 Jun 2003 14:49:51 +0200
Well, decode() is a bit buggy.
My unit test does not pass:
public class HexCoderTestCase extends WOUTTestCase {
private static final byte[] bytes = {1,2,3,4};
protected void setUp() throws Exception {
super.setUp();
// your setup code here
}
protected void tearDown() throws Exception {
// your tearDown code here
super.tearDown();
}
public void testEncodingAndDecoding() {
String stringFromBytes = HexCoder.hexEncode(bytes);
byte[] revertBytes = HexCoder.hexDecode(stringFromBytes);
assertTrue(stringFromBytes.equals("01020304"));
assertTrue(HexCoder.hexEncode(bytes).equals(HexCoder.hexEncode(revertByt
es)));
}
}
Here is the fixed version:
public static byte[] hexDecode(String aString) throws
IllegalArgumentException {
if (aString != null) {
int aLength = aString.length();
byte[] someBytes = new byte[aLength / 2];
int anIndex = 0;
int anotherIndex = 0;
char[] someChars = aString.toCharArray();
while (anIndex < aLength) {
char upperChar = someChars[anIndex];
char lowerChar = someChars[anIndex + 1];
someBytes[anotherIndex++] =
(byte) ((HexCoder.charToNibble(upperChar) << 4)
+ HexCoder.charToNibble(lowerChar));
anIndex += 2;
}
return someBytes;
}
else throw new IllegalArgumentException("HexCoder.decode: null
string.");
}
On Tuesday, Jun 3, 2003, at 22:32 Europe/Amsterdam, Jonathan 'Wolf'
Rentzsch wrote:
OK, I found my version of this code on my disk. I prefered lower-case
hex
characters, and I believe Raphael's original encode() implementation
reversed the hex output. Anyway, here's my version. It's been through
extensive unit tests (grin).
// HexCoder.java
//
// Copyright (C) 2001 Petite Abeille. All Rights Reserved.
// This class is hereby released for all uses. No warranties
whatsoever.
//
// by Petite Abeille <email@hidden>
public static byte[] decode(String aString) {
if (aString != null) {
int aLength = aString.length();
byte[] someBytes = new byte[aLength / 2];
int anIndex = 0;
int anotherIndex = aLength / 2;
char[] someChars = aString.toCharArray();
while (anIndex < aLength) {
char upperChar = someChars[anIndex];
char lowerChar = someChars[anIndex + 1];
someBytes[--anotherIndex] =
(byte) ((HexCoder.charToNibble(upperChar) << 4)
+ HexCoder.charToNibble(lowerChar));
anIndex += 2;
}
return someBytes;
}
throw new IllegalArgumentException("HexCoder.decode: null
string.");
}
-- georg --
"More Trees, less Bushes!"
_______________________________________________
webobjects-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/webobjects-dev
Do not post admin requests to the list. They will be ignored.