2

やあ、

私はフグを使って Java で暗号化と復号化を行っています。

暗号化は正常に機能しますが、復号化は失敗します。

復号化するための私のJavaコードは次のとおりです。

String encryptedString = … ;
String decryptedString = null;
SecretKeySpec key = new SecretKeySpec(myKey.getBytes(), "Blowfish");
Cipher cipher;
try {
    cipher = Cipher.getInstance("Blowfish");
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decrypted = cipher.doFinal(encryptedString.getBytes());
    decryptedString = new String(decrypted, Charset.forName("UTF-8"));
} [ catch Exceptions … ]

例外が発生します:

Exception. javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher

これを簡単に機能させる方法を教えてください。ありがとうございました。

私が提供する入力は、暗号化 Java コード + Base64 でのエンコードから得られ、この復号化操作に渡す直前に Base64 からデコードします。

4

8 に答える 8

10

バイトを 16 進数に変換して戻すのは難しい作業です。これで問題が解決するはずです。(encryptedString の文字列表現を修正する必要があります)

出力:

StackOverflow 537461636B4F766572666C6F77 [83, 116, 97, 99, 107, 79, 118, 101, 114, 102, 108, 111, 119]
J~3¹ÙÂÖ"¢ª„¨u 194A7E33B9060CD9C2D622A2AA84A875 [25, 74, 126, 51, -71, 6, 12, -39, -62, -42, 34, -94, -86, -124, -88, 117]
StackOverflow 537461636B4F766572666C6F77 [83, 116, 97, 99, 107, 79, 118, 101, 114, 102, 108, 111, 119]

コード:

import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Main {

  public static void main(String[] args) throws Exception {

    KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");
    SecretKey secretkey = keygenerator.generateKey();

    String plaintextString = "StackOverflow";
    System.out.println(plaintextString + " " + bytesToHex(plaintextString.getBytes()) + " " + Arrays.toString(plaintextString.getBytes()));

    SecretKeySpec key = new SecretKeySpec(secretkey.getEncoded(), "Blowfish");
    Cipher cipher = Cipher.getInstance("Blowfish");

    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] encrypted = cipher.doFinal(plaintextString.getBytes());
    String encryptedString = bytesToHex(encrypted);
    System.out.println(new String(encrypted) + " " + encryptedString + " " + Arrays.toString(encrypted));

    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decrypted = cipher.doFinal(hexToBytes(encryptedString));
    String decryptedString = bytesToHex(decrypted);
    System.out.println(new String(decrypted) + " " + decryptedString + " " + Arrays.toString(decrypted));

  }

  public static byte[] hexToBytes(String str) {
    if (str == null) {
      return null;
    } else if (str.length() < 2) {
      return null;
    } else {
      int len = str.length() / 2;
      byte[] buffer = new byte[len];
      for (int i = 0; i < len; i++) {
        buffer[i] = (byte) Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16);
      }
      return buffer;
    }

  }

  public static String bytesToHex(byte[] data) {
    if (data == null) {
      return null;
    } else {
      int len = data.length;
      String str = "";
      for (int i = 0; i < len; i++) {
        if ((data[i] & 0xFF) < 16)
          str = str + "0" + java.lang.Integer.toHexString(data[i] & 0xFF);
        else
          str = str + java.lang.Integer.toHexString(data[i] & 0xFF);
      }
      return str.toUpperCase();
    }
  }
}
于 2013-04-11T13:16:46.830 に答える
3

myKey 変数の長さは 8 の倍数でなければなりません

于 2013-04-11T12:30:06.663 に答える
1

今、私は解決策を持っています!

まず、Unicode に問題があったため、ISO-8859-1 をあらゆる場所に配置しました。Base64 エンコーディングとデコーディングに含まれます。

次に、バリアントをジャグリングしました。

以下は、Blowfish の復号化で機能する私の Java コードです。

String encryptedString = … ;
String decryptedString = null;
SecretKeySpec key = new SecretKeySpec(myKey.getBytes(CHARSET_ISO_8859_1), "Blowfish");
Cipher cipher;
try {
    cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decrypted = cipher.doFinal(encryptedString.getBytes(CHARSET_ISO_8859_1));
    decryptedString = new String(decrypted, CHARSET_ISO_8859_1);
} [ catch Exceptions … ]

インスタンスを取得するために に"Blowfish"置き換えまし たが、キーに対して同じことを行うと失敗することに注意してください。"Blowfish/ECB/PKCS5Padding"Cipher

キー myKeyは、8 文字の Latin-1 文字列でなければなりません。これにより、128 ビットのキーが作成されます。Blowfish アルゴリズムではより大きなキーを使用できますが、Java では JRE の米国輸出制限により失敗します。米国では暗号化が許可されていますが、NSAが解読できるものよりも強力ではありません。

CHARSET_ISO_8859_1、次のように定義された定数です。

final Charset CHARSET_ISO_8859_1 = Charset.forName("ISO-8859-1");

そしてCharsetですjava.nio.charset.Charset

最後になりましたが、それに応じて暗号化 Java コードを変更しました。

于 2013-04-11T15:27:19.737 に答える
1
String encryptedString = … ;  
String decryptedString = null;
SecretKeySpec key = new SecretKeySpec(myKey.getBytes(), "Blowfish");
private static byte[] linebreak = {}; // Remove Base64 encoder default linebreak
private static Base64 coder;
Cipher cipher;
try {
    coder = new Base64(32, linebreak, true);
    cipher = Cipher.getInstance("Blowfish");
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decrypted = cipher.doFinal(encryptedString.getBytes());
    decryptedString = new String(coder.encode(decrypted));
} [ catch Exceptions … ]

Base64 クラスを使用してこの問題を解決できます。

于 2013-04-11T13:56:23.193 に答える
0

これを試して

private byte[] encrypt(String key, String plainText) throws GeneralSecurityException {

    SecretKey secret_key = new SecretKeySpec(key.getBytes(), ALGORITM);

    Cipher cipher = Cipher.getInstance(ALGORITM);
    cipher.init(Cipher.ENCRYPT_MODE, secret_key);

    return cipher.doFinal(plainText.getBytes());
}

ここでは、enc/dec でクラス全体を見つけることができます --- http://dextr.com/post/57145943236/blowfish-encrypt-and-decrypt-in-Java-android

于 2013-08-02T12:20:50.087 に答える
0

Cipherモードとパディングを宣言することで、より明確にする必要があります。このコードはどのように暗号化されていますか? 実際には何がありString encryptedStringますか?16 進数でエンコードされているか、base64 でエンコードされていますか? エンコードされていない場合、間違いなくトラブルの原因となる可能性があります。

于 2013-04-11T13:25:22.207 に答える
0
    try {
        /**
         * Initialize the cipher for decryption
         */
     cipher.init(Cipher.DECRYPT_MODE, secretKey);
        /**
         * Initialize input and output streams
         */
        inStream = new FileInputStream(encryptedFile);
        outStream = new FileOutputStream(decryptedFile);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inStream.read(buffer)) > 0) {
            outStream.write(cipher.update(buffer, 0, len));
            outStream.flush();
        }
        outStream.write(cipher.doFinal());
        inStream.close();
        outStream.close();
    }

...

  1. リスト項目
于 2021-07-29T09:30:56.523 に答える