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!
getKey()method as well, as it is used in line, which fails.char, anyways; thatord()method doesn't always return valid data, and isn't international safe (combined characters). Also, you're swallowingExceptions, which is bad, and simply printing toSystem.out(and not even.err!), instead of properly logging. And look upStringBuilder- your implementation is not optimal.