Java 和子字符串错误

标签 java indexing substring

我正在实现一种使用 key 加密的方法,我进行了如下调用:

Crypto c = new Crypto("mysecretkey");
String enc = c.encrypt("mytext");

但是我得到了一个异常(exception)

"crypto encrypt error: String index out of range: -1"

在这部分:

String sKeyChar = getKey().substring((i % getKey().length()) - 1, 1);

而且我不知道自己做错了什么,因为我用 PHP 做了同样的事情并且运行良好。也许这很简单,但我被卡住了,这是我的方法:

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;
    }

需要的其他方法:

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 等效方法:

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); 
} 

谢谢!

最佳答案

您的计算是错误的:(i % getKey().length()) - 1 将导致 i = 0 为 -1,即在第一个迭代。因此,您尝试将 -1 传递给 substring(...) 方法,这是不允许的。

另请注意,如果数据比 key 长,i % getKey().length() 将导致 key 长度的每个倍数为 0。

此外,substring(...) 的参数不是indexlength,而是startIndex (包含)和 endIndex(不包含)。因此,一旦 i 达到 2(及以上),String sChar = sData.substring(i, 1); 将抛出异常,并且不会为 i 返回任何内容= 1

您可能想使用 charAt(i) 代替(在下一行中使用 getKey().charAt(i % getKey().length())) .请注意,这将返回单个字符,这将使 ord(...) 方法过时。

作为旁注:String.valueOf(sChar.charAt(0)).codePointAt(0) 等同于 sChar.codePointAt(0)

另一个旁注:

char c = (char) (ord(sChar) - ord(sKeyChar));
String sPart = (new StringBuffer().append(c)).toString();
sResult += sPart; 

可以简化为

char c = (char) (ord(sChar) - ord(sKeyChar));
sResult += c; //you could also merge those two lines

关于Java 和子字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9071826/

相关文章:

regex - Perl正则表达式删除字符串中重复的连续子字符串

java - 超大文件中的正则表达式搜索模式

python - 确定两个 numpy 数组在 Python 中相交的参数

php - 使用 PHP 删除行时更新 mySQL 数据库中的 ids

python - 添加具有不同列名的两个 Pandas 系列的值

javascript - ElasticSearch术语在子字符串上聚合

regex - 子集不是基于完全匹​​配,而是基于 R 中的部分

java - Java中的静态初始化和动态初始化有什么区别?

java - Google Drive API 列表文件错误和 Web 链接错误

线程的 Java 垃圾收集