解密java时出错

解密java时出错,java,encryption,Java,Encryption,我解密有问题;我得到以下错误: javax.crypto.BadPaddingException:解密错误 我要加密的代码如下: userName = URLDecoder.decode(userName, "ISO-8859-1"); Cipher objCipherTunkicloud = Cipher.getInstance("RSA/ECB/PKCS1Padding"); objCipherTunkicloud.init(Cipher.ENCRYPT_MODE, loadPublicK

我解密有问题;我得到以下错误:

javax.crypto.BadPaddingException:解密错误

我要加密的代码如下:

userName = URLDecoder.decode(userName, "ISO-8859-1");
Cipher objCipherTunkicloud = Cipher.getInstance("RSA/ECB/PKCS1Padding");

objCipherTunkicloud.init(Cipher.ENCRYPT_MODE, loadPublicKey("/keylecordonbleu/public.key", "RSA"));

byte[] arrDecryptedKeyBytes = objCipherTunkicloud.doFinal(userName.getBytes(StandardCharsets.UTF_8));
log.error("SECURITY - key en array de bytes");

String tkn = new String(arrDecryptedKeyBytes);

userName = URLEncoder.encode(tkn, "ISO-8859-1");
要解密它是这样的:

userName = URLDecoder.decode(userName, "ISO-8859-1");

Cipher objCipherTunkicloud = Cipher.getInstance("RSA/ECB/PKCS1Padding");

objCipherTunkicloud.init(Cipher.DECRYPT_MODE, loadPrivateKey("/keylecordonbleu/private.key", "RSA"));

byte[] arrDecryptedKeyBytes = objCipherTunkicloud.doFinal(userName.getBytes(StandardCharsets.ISO_8859_1));

String tkn = new String(arrDecryptedKeyBytes);
问题是什么,我如何解决


解密时,我在这一行遇到错误:

byte[] arrDecryptedKeyBytes = objCipherTunkicloud.doFinal(userName.getBytes(StandardCharse‌​ts.ISO_8859_1));

问题似乎是您正在使用
doFinal(userName.getBytes(StandardCharsets.UTF_8))进行加密并使用doFinal(userName.getBytes(StandardCharsets.ISO_8859_1))进行解密

问题似乎是您正在使用
doFinal(userName.getBytes(StandardCharsets.UTF_8))进行加密并使用doFinal(userName.getBytes(StandardCharsets.ISO_8859_1))进行解密

@JB Nizet的评论解释并解决了您的问题。我会详细说明一下:

理论
  • (良好)加密的结果是随机的,例如随机字节数组。因此,结果将包含所有可能的字节组合
  • String(byte[])
    将给定的字节数组解释为默认(或给定)编码中的字符数据
  • 并非所有字节或字节序列都表示(取决于编码)有效字符。无效字节/序列的行为未定义-它们可能被忽略
  • 因此,
    String(byte[]encrypted).getBytes()
    不会为所有可能的字节数组返回
    加密的
  • 因此,对于某些输入,您的代码将失败
  • Base64(
    java.util.Base64
    )通常用于打印加密结果
  • 某些加密算法仅适用于特定长度的
    Cipher
    会处理此问题,并根据需要填充您的输入
  • 如果您的编码/解码周期丢失字符,则用于解码my的字节将不再与所需的块大小对齐,您将得到一个
    BadPaddingException
使用ISO-8859-1/Latin1 正如@dave_thompson_085所指出的,如果您强制java使用
String(encrypted,StandardCharsets.ISO_8859_1)
encrypted.getBytes(StandardCharsets.ISO_8859_1)
将字节数组解释为ISO-8859-1(拉丁语),则可以将字节数组转换为字符串并返回而不会丢失。ISO-8859-1映射所有256字节的值,并且没有任何“无效值”。我在代码中添加了相应的编码器/解码器

但是:在走这条路线时,确保你知道后果:

  • 字节数组不是字符串!虐待类型有很多副作用
  • 一旦您尝试在另一个程序中读取此字符串,您必须确保您的目标系统(以及正在进行的一切)对如何处理拉丁语1有相同的想法
    0x00
    可以标记字符串的结尾,
    0x0a
    0x0d
    可以被操作,控制字符可以被解释
  • Base64通常用于加密文本是有原因的
代码 你的代码做了很多不同的事情。尤其是在密码学方面,通常需要分离关注点,并独立测试它们。为了重现和解决问题,我做了一些更改:

  • 我省略了
    URLDecode
    /
    URLEncode
    ,因为它不会导致问题(可能属于另一层…)
  • 我们无法访问您的
    加载公钥(“/keylecordonbleu/public.key”,“RSA”)
    方法和您的密钥文件。。。我用每次测试时生成的
    密钥对
    替换了它。您可能希望从这开始,并在其他代码运行后添加密钥
  • 我提取代码,将加密的
    字节[]
    编码为
    字符串
    ,并将
    字符串
    解码为要解密的
    字节[]
这允许您:

  • 要测试裸en-/decrypt循环
    EncryptDecrypt往返(字符串用户名)
    ,无需对字符串进行编码。这在您的代码中已经起作用了
  • 要测试显然不适用于所有输入的字节[]->字符串->字节[]编码(
    testSimpleEncoder()
    ),请验证Base64编码是否适用(
    testBase64Encoder()
使用反/加密代码初始化:

public class CryptoUtils {
  private static final String ALGORITHM = "RSA";
  private static final String TRANSFORMATION = ALGORITHM + "/ECB/PKCS1Padding";

  public interface Encoder extends Function<byte[], String> { };
  public interface Decoder extends Function<String, byte[]> { };

  public static class EncoderNotWorking implements Encoder {
    @Override
    public String apply(byte[] encrypted) {
      return new String(encrypted);
    }
  }

  public static class DecoderNotWorking implements Decoder {
    @Override
    public byte[] apply(String encrypted) {
      return encrypted.getBytes();
    }
  }

  public static class EncoderLatin1 implements Encoder {
    @Override
    public String apply(byte[] encrypted) {
      return new String(encrypted, StandardCharsets.ISO_8859_1);
    }
  }

  public static class DecoderLatin1 implements Decoder {
    @Override
    public byte[] apply(String encrypted) {
      return encrypted.getBytes(StandardCharsets.ISO_8859_1);
    }
  }

  public static class EncoderBase64 implements Encoder {
    @Override
    public String apply(byte[] encrypted) {
      return new String(Base64.getEncoder().encode(encrypted));
    }
  }

  public static class DecoderBase64 implements Decoder {
    @Override
    public byte[] apply(String encrypted) {
      return Base64.getDecoder().decode(encrypted);
    }
  }

  /** Return Cipher for the given mode (de/encrypt) and key. */
  public Cipher getInitCipher(int opmode, Key key) throws InvalidKeyException,
      NoSuchAlgorithmException, NoSuchPaddingException {
    Cipher cipher = Cipher.getInstance(TRANSFORMATION);
    cipher.init(opmode, key);
    return cipher;
  }

  /** Generate a key pair for testing. */
  public KeyPair generateKeyPair()
      throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    keyGen.initialize(1024, random);
    return keyGen.generateKeyPair();
  }

  public byte[] encrypt(Key publicKey, String userName)
      throws InvalidKeyException, NoSuchAlgorithmException,
      NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    byte[] toEncrypt = userName.getBytes();
    Cipher cipher = getInitCipher(Cipher.ENCRYPT_MODE, publicKey);
    return cipher.doFinal(toEncrypt);
  }

  public String decrypt(Key privateKey, byte[] encryptedUserName)
      throws InvalidKeyException, NoSuchAlgorithmException,
      NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    Cipher cipher = getInitCipher(Cipher.DECRYPT_MODE, privateKey);
    byte[] decrypted = cipher.doFinal(encryptedUserName);
    return new String(decrypted);
  }

  /** Encrypt and encode using the given Encoder, */
  public String encryptAndEncode(Key publicKey, String userName,
      Encoder encoder) throws InvalidKeyException, NoSuchAlgorithmException,
      NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    byte[] encrypted = encrypt(publicKey, userName);
    return encoder.apply(encrypted);
  }

  /** Decrypt and Decode using the given Decoder, */
  public String decodeAndDecrypt(Key privateKey, String encryptedUserName,
      Decoder decoder) throws InvalidKeyException, NoSuchAlgorithmException,
      NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    byte[] toDecrypt = decoder.apply(encryptedUserName);
    return decrypt(privateKey, toDecrypt);
  }

  /** Encrypt and decrypt the given String, and assert the result is correct. */
  public void encryptDecryptRoundtrip(String userName)
      throws InvalidKeyException, NoSuchAlgorithmException,
      NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException,
      NoSuchProviderException {
    CryptoUtils crypto = new CryptoUtils();
    KeyPair keys = crypto.generateKeyPair();
    byte[] encrypted = crypto.encrypt(keys.getPublic(), userName);
    String decrypted = crypto.decrypt(keys.getPrivate(), encrypted);
    assert decrypted.equals(userName);
  }

  /**
   * As @link {@link #encryptDecryptRoundtrip(String)}, but further encodes and
   * decodes the result of the encryption to/from a String using the given
   * Encoder/Decoder before decrypting it.
   */
  public void encodeDecodeRoundtrip(Encoder encoder, Decoder decoder,
      String userName) throws InvalidKeyException, NoSuchAlgorithmException,
      NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException,
      NoSuchProviderException {
    CryptoUtils crypto = new CryptoUtils();
    KeyPair keys = crypto.generateKeyPair();
    String encrypted = crypto.encryptAndEncode(keys.getPublic(), userName,
        encoder);
    // encrypted could now be stored and later loaded...
    String decrypted = crypto.decodeAndDecrypt(keys.getPrivate(), encrypted,
        decoder);
    assert decrypted.equals(userName);
  }

  /** Test the working examples*/
  public static void main(String[] args) throws NoSuchAlgorithmException,
      NoSuchProviderException, InvalidKeyException, NoSuchPaddingException,
      IllegalBlockSizeException, BadPaddingException {
    CryptoUtils crypto = new CryptoUtils();
    String userName = "John Doe";
    crypto.encryptDecryptRoundtrip(userName);
    crypto.encodeDecodeRoundtrip(new EncoderBase64(), new DecoderBase64(),
        userName);
  }
}

@JB Nizet的评论解释并解决了您的问题。我会详细说明一下:

理论
  • (良好)加密的结果是随机的,例如随机字节数组。因此,结果将包含所有可能的字节组合
  • String(byte[])
    将给定的字节数组解释为默认(或给定)编码中的字符数据
  • 并非所有字节或字节序列都表示(取决于编码)有效字符。无效字节/序列的行为未定义-它们可能被忽略
  • 因此,
    String(byte[]encrypted).getBytes()
    不会为所有可能的字节数组返回
    加密的
  • 因此,对于某些输入,您的代码将失败
  • Base64(
    java.util.Base64
    )通常用于打印加密结果
  • 某些加密算法仅适用于特定长度的
    Cipher
    会处理此问题,并根据需要填充您的输入
  • 如果您的编码/解码周期丢失字符,则用于解码my的字节将不再与所需的块大小对齐,您将得到一个
    BadPaddingException
使用ISO-8859-1/Latin1 正如@dave_thompson_085所指出的,如果强制java将字节数组解释为ISO-8859-1,则可以将字节数组转换为字符串并返回而不会丢失(
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;

public class CryptoUtilsTest {

  /**
   * Byte array to test encoding.
   * 
   * @see https://stackoverflow.com/questions/1301402/example-invalid-utf8-string
   */
  private static final byte[] ENCODE_TEST_ARRAY = new byte[] { (byte) 0x00,
    (byte) 0x00, (byte) 0x0a, (byte) 0x0c, (byte) 0x0d, (byte) 0xc3,
    (byte) 0x28, (byte) 0x7f, (byte) 0x80, (byte) 0xfe, (byte) 0xff };

  public void encoderDecoderTest(Encoder encoder, Decoder decoder) {
    String encoded = encoder.apply(ENCODE_TEST_ARRAY);
    byte[] decoded = decoder.apply(encoded);
    assertArrayEquals("encoder \"" + encoder.getClass() + "\" / decoder \""
        + decoder.getClass() + "\" failed!", ENCODE_TEST_ARRAY, decoded);
  }

  /**
   * Shows that String(byte[] encrypted).getBytes() does not return encrypted
   * for all input, as some byte sequences can't be interpreted as a string as
   * there are bytes/sequences that just don't represent characters!           
   */
  @Test
  public void testSimpleEncoder() {
    Encoder encoder = new CryptoUtils.EncoderNotWorking();
    Decoder decoder = new CryptoUtils.DecoderNotWorking();
    encoderDecoderTest(encoder, decoder);
  }

  /**
   * Shows that encoding a byte array into a String interpreting it as Latin1
   * should work.
   */
  @Test
  public void testLatin1Encoder() {
    Encoder encoder = new CryptoUtils.EncoderLatin1();
    Decoder decoder = new CryptoUtils.DecoderLatin1();
    encoderDecoderTest(encoder, decoder);
  }

  /** Shows that Base64 encoder should be used to encode random byte arrays. */
  @Test
  public void testBase64Encoder() {
    Encoder encoder = new CryptoUtils.EncoderBase64();
    Decoder decoder = new CryptoUtils.DecoderBase64();
    encoderDecoderTest(encoder, decoder);
  }
}
static void SO46244541CryptAsURL (String... args) throws Exception {
    // arguments: data pubkeyfile(der) prvkeyfile(der) flag(if present specify 8859-1 on conversion)
    String clear = args[0];
    KeyFactory fact = KeyFactory.getInstance("RSA");
    Cipher objCipherTunkicloud = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    // encrypt side
    objCipherTunkicloud.init(Cipher.ENCRYPT_MODE, fact.generatePublic(new X509EncodedKeySpec(read_file(args[1]))));
    byte[] arrDecryptedKeyBytes = objCipherTunkicloud.doFinal(clear.getBytes(StandardCharsets.UTF_8));
    // for correct result must enable flag and specify 8859-1 on ctor
    String tkn = args.length>3? new String(arrDecryptedKeyBytes,StandardCharsets.ISO_8859_1): new String(arrDecryptedKeyBytes);
    String output = URLEncoder.encode(tkn, "ISO-8859-1");
    System.out.println (output);
    // decrypt side
    String temp = URLDecoder.decode(output, "ISO-8859-1");
    //reused: Cipher objCipherTunkicloud = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    objCipherTunkicloud.init(Cipher.DECRYPT_MODE, fact.generatePrivate(new PKCS8EncodedKeySpec(read_file(args[2]))));
    arrDecryptedKeyBytes = objCipherTunkicloud.doFinal(temp.getBytes(StandardCharsets.ISO_8859_1));
    System.out.println (new String(arrDecryptedKeyBytes));
}

public static byte[] read_file (String filename) throws Exception {
    return Files.readAllBytes(new File(filename).toPath());
}