2011-05-19 74 views
5

我想在Java中使用RSA编写加密算法,我得到一个 “javax.crypto.BadPaddingException:数据必须以零开头”;我不知道这是什么例外。 这是我用的例子here在Java中的RSA加密

这是我的代码;请帮忙。

public byte[] getEncryptedValue(byte[] bytes, PublicKey key) { 
    try { 
     cipher.init(Cipher.ENCRYPT_MODE, key); 
     return blockCipher(bytes, Cipher.ENCRYPT_MODE); 
    } catch (Exception ex) { 
     Logger.getLogger(SecurityUtil.class.getName()).log(Level.SEVERE, null, ex); 
    } 
    return null; 
} 

public byte[] getDecryptedValue(byte[] bytes, PrivateKey key) { 
    try { 
     cipher.init(Cipher.DECRYPT_MODE, key); 
     return blockCipher(bytes, Cipher.DECRYPT_MODE); 
    } catch (Exception ex) { 
     Logger.getLogger(SecurityUtil.class.getName()).log(Level.SEVERE, null, ex); 
    } 
    return null; 
} 

private byte[] append(byte[] prefix, byte[] suffix) { 
    byte[] toReturn = new byte[prefix.length + suffix.length]; 
    System.arraycopy(prefix, 0, toReturn, 0, prefix.length); 
    System.arraycopy(suffix, 0, toReturn, prefix.length, suffix.length); 
    return toReturn; 
} 

private byte[] blockCipher(byte[] bytes, int mode) throws IllegalBlockSizeException, BadPaddingException { 
    byte[] scrambled = new byte[0]; 
    byte[] toReturn = new byte[0];blocks (because of RSA) 
    int length = (mode == Cipher.ENCRYPT_MODE) ? 100 : 128; 
    int n = 0; 
    byte[] buffer = new byte[length]; 

    for (int i = 0; i < bytes.length; i++) { 
     if ((i > 0) && (i % length == 0)) { 
      n = 0; 
      scrambled = cipher.doFinal(buffer); 
      toReturn = append(toReturn, scrambled); 
     } 
     buffer[i % length] = bytes[i]; 
     n++; 
    } 
    ***scrambled = cipher.doFinal(buffer, 0, n);*** <-- the exception is caught here 
    toReturn = append(toReturn, scrambled); 
    return toReturn; 
} 
+0

当你得到的例外 - 而加密或解密? – sinha 2011-05-19 05:50:44

+1

您是否在发布您的问题之前在javax.crypto.BadPaddingException上进行搜索?这看起来像[this](http://stackoverflow.com/questions/4895773)和[this]的可能重复(http://stackoverflow.com/questions/4580982)。回答:您不是将十六进制字符串正确地转换回字节数组以解密 – 2011-05-20 21:28:07

+0

称我为笨,但变量'cipher'是如何初始化的?它的内容是什么? 似乎没有声明或是全球? – bl4ckb0l7 2011-05-23 13:49:58

回答

2

问题可能是由于某些编码问题,使用套接字通过网络发送的数据可能会损坏。在开发简单的客户/服务器聊天程序时,我遇到了同样的问题,它使用非对称密钥对服务器和客户端之间的消息进行加密/解密,反之亦然,而不是将消息作为字符串发送,我将其作为字节数组发送加密的消息。

0
  • 检查,如果密钥匹配
  • 检查,如果通过getEncryptedValue返回的数据是,你传递给getDecryptedValue
  • 循环
  • 检查corectness在分组密码方法相同