有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将Vigenère密码与fibonacci相结合

我有Vigenère cipher java代码,它运行得很好,但我想用斐波那契公式修改这段代码,这样加密结果就像一个一次性pad方法。。 代码如下:

public class Coba {
public static void main(String[] args) {
String key = "abcd";
String ori = "satusatu";
String enc = enkripsibaru(ori, key);
System.out.println(enc);
System.out.println(key);
System.out.println(ori);
System.out.println(dekripsibaru(enc, key));
}
static String enkripsibaru (String plaintext, String key)
    {
        String s = "";
        int lengthPlainText = plaintext.length();
        int lengthKey = key.length();
        int j = 0;

        for (int i = 0; i < lengthPlainText; i++)
        {
            if (j >= lengthKey)
            {
            key = plaintext;
            lengthKey = lengthPlainText;
            j = 0;
            }

        s += (char) (((int) plaintext.charAt(i) + key.charAt(j))%26);
        j++;
        }
        return s;
    }   
    public static String dekripsibaru(String cipher, String kunci)
        {
            String s = "";
            int lengthCipherText = cipher.length();
            int lengthKey = kunci.length();
            int j = 0;
            int temp1;
            int a = 0;

            for (int i = 0; i<lengthCipherText; i++)
            {
            if (j >= lengthKey) 
            {
                temp1 = (int) cipher.charAt(i) - (int) s.charAt(a);
                if (temp1 < 0) {
                    temp1 += 26;
                }
            s += (char) (temp1 % 26);
            a++;
            }
            else
            {
            temp1 = (int) cipher.charAt(i) - (int)  kunci.charAt(j);
                if (temp1 < 0)
                {
                    temp1 += 26;
                }
                s += (char) (temp1 % 26);
            }
            j++;
            }
            return s;
        }

    }

我应该如何处理此代码才能与斐波那契结合? 谢谢


共 (1) 个答案

  1. # 1 楼答案

    我猜你想用斐波那契数列而不是键

    斐波那契序列如下:

    0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, etc.

    因此,各个字母的位移将是上面的,模26:

    0, 1, 1, 2, 3, 5, 8, 13, 21, 8, 3, etc.

    让我们用一种方法来计算斐波那契序列:

    static long fibonacci (int n) {
        if (n <= 1) return n;
        else return fibonacci(n-1) + fibonacci(n-2);
    }
    

    现在我们替换:

    s += (char) (((int) plaintext.charAt(i) + key.charAt(j))%26);
    

    与:

    s += (char) ((int) ((int) plaintext.charAt(i) + fibonacci(i)) % 26);