0

我正在尝试在 JDK 1.6.0_35 中使用 SHA1 和私钥进行加密。

但我得到以下异常:

线程“主”java.security.NoSuchAlgorithmException 中的异常:找不到任何支持 SHA1 的提供程序

相同的代码适用于 AES。这是代码:

public class ExecuteEncryptDecryptSample {
        private static String method="SHA1"; 
        public static SecretKeySpec getKeySpec() throws IOException, NoSuchAlgorithmException {
            byte[] bytes = new byte[16];
            File f = new File("sample_aes_key");
        SecretKey key = null;
        SecretKeySpec spec = null;
        if (f.exists()) {
            new FileInputStream(f).read(bytes);
        } else {
            //KeyGenerator kgen = KeyGenerator.getInstance("SHA1");//PBKDF2WithHmacSHA1
            KeyGenerator kgen = KeyGenerator.getInstance(method);
            kgen.init(256);
            key = kgen.generateKey();
            bytes = key.getEncoded();
            new FileOutputStream(f).write(bytes);

        }
        spec = new SecretKeySpec(bytes,method);
        return spec;
    }
    public static void encrypt(String text) throws Exception {
        SecretKeySpec spec = getKeySpec();
        Cipher cipher = Cipher.getInstance(method);
        cipher.init(Cipher.ENCRYPT_MODE, spec);
        BASE64Encoder enc = new BASE64Encoder();
        System.out.println(enc.encode(cipher.doFinal(text.getBytes())));
    }

    public static void main(String[] args) throws Exception {
        String text = "1234000156237828282873773";
        //Security security;
        //security.getProviders();
        System.out.println();
        encrypt(text);
    }
}

jdk 6中是否有SHA1的提供者..?

任何帮助将不胜感激。

谢谢。

4

3 回答 3

1

SHA-1 是一种安全的散列算法。即使有时将其用作一个,它也不是密钥派生函数。所以虽然你可以使用MessageDigestwith 算法"SHA-1",但你不能使用KeyGeneratorwith "SHA-1"

如果出于兼容性原因要生成密钥,则可以使用MessageDigestwith"SHA-1"并获取输出的第一个字节(根据需要创建密钥)。之后,您可以使用 egSecretKeySpec(firstBytes, "AES")SecretKeyFactory3DES 密钥。

于 2013-08-26T21:22:14.843 回答
0

如果您被要求使用 SHA1 进行对称密钥加密,那么这可能意味着您应该使用对称密钥(例如 AES)进行加密并使用 HMACSHA1 进行身份验证。用于身份验证的类是

javax.crypto.Mac

(不是 MessageDigest),算法将是“HMACSHA1”而不是(“SHA1”)。当然这是很多猜测,不幸的是我今天没有带水晶球,所以我可能是错的。(例如,这也可能是对加密术语的可怕滥用,这意味着您应该使用 SHA1 散列并使用 RSA 签名,当然使用 SHA1 将不再合适。)

于 2013-08-27T10:00:05.890 回答
-2

尝试列出密钥库的所有条目,看起来 SHA 不存在于密钥库中,而 AES 存在。如果不存在,请尝试将该值添加到密钥库并再次测试。

于 2013-08-26T21:07:30.533 回答