I am implementing a method to encrypt with a key and i made a call like this:
Crypto c = new Crypto("mysecretkey");
String enc = c.encrypt("mytext");
But i am getting an exception
“crypto encrypt error: String index out of range: -1”
at this part:
String sKeyChar = getKey().substring((i % getKey().length()) - 1, 1);
And I don’t know what I am doing wrong because I made the same thing in PHP and works good. Maybe this is simple but I am stuck, this is my method:
public String encrypt(String sData) {
String sEncrypted = null;
try {
String sResult = null;
for (int i = 0; i < sData.length(); i++) {
String sChar = sData.substring(i, 1);
String sKeyChar = getKey().substring((i % getKey().length()) - 1, 1);
char c = (char) (ord(sChar) - ord(sKeyChar));
String sPart = (new StringBuffer().append(c)).toString();
sResult += sPart;
}
byte[] sResultBuff = sResult.getBytes("UTF-8");
sEncrypted = Base64.encode(sResultBuff);
} catch (Exception e) {
System.out.println("crypto encrypt error: " + e.getMessage());
sEncrypted = null;
}
return sEncrypted;
}
Other method needed:
public int ord(String sChar) {
int ascii_code = 0;
try {
ascii_code = String.valueOf(sChar.charAt(0)).codePointAt(0);
} catch (Exception e) {
System.out.println("crypto ord error: " + e.getMessage());
ascii_code = 0;
}
return ascii_code;
}
PHP equivalent method:
function encrypt($sData, $sKey='mysecretkey'){
$sResult = '';
for($i=0;$i<strlen($sData);$i++){
$sChar = substr($sData, $i, 1);
$sKeyChar = substr($sKey, ($i % strlen($sKey)) - 1, 1);
$sChar = chr(ord($sChar) + ord($sKeyChar));
$sResult .= $sChar;
}
return encode_base64($sResult);
}
Thanks!
You see the difference between PHP and Java because PHP’s
substrunderstands negative numbers, but Java’ssubstringdoes not: it throws an exception.In PHP, passing negative 1 to
substrmeans “get me the last character”, but in Java you need to pass the index of the last character (i.e.str.length()-1) to achieve the same effect.If this is not a mistake, and this is precisely the effect that you wanted to achieve, you can address this issue with an
ifcondition:EDIT As Thomas correctly pointed out, the other difference between PHP version of
substrand Java’ssubstringis in their treatment of the second argument: PHP thinks it’s length; Java thinks it’s the index of the last character plus one.