为什么java.security.NoSuchProviderException没有这样的提供者:BC?

2022-08-31 12:20:42

jar (bcprov-jdk16-145.jar) 已添加到项目中,已添加到类中,并且确实返回“BC”,但 AesFileIo.writeFile() 仍然会抛出 。有什么想法吗?Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider())BouncyCastleProvider.PROVIDER_NAMEjava.security.NoSuchProviderException No such provider: BC

import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class AesFileIo {

    private static final String AES_ALGORITHM = "AES/CTR/NoPadding";
    private static final String PROVIDER = BouncyCastleProvider.PROVIDER_NAME;
    private static final byte[] AES_KEY_128 = { // Hard coded for now
        78, -90, 42, 70, -5, 20, -114, 103,
        -99, -25, 76, 95, -85, 94, 57, 54};
    private static final byte[] IV = { // Hard coded for now
        -85, -67, -5, 88, 28, 49, 49, 85,
        114, 83, -40, 119, -65, 91, 76, 108};
    private static final SecretKeySpec secretKeySpec =
            new SecretKeySpec(AES_KEY_128, "AES");
    private static final IvParameterSpec ivSpec = new IvParameterSpec(IV);

    public void AesFileIo() {
        Security.addProvider(new org.bouncycastle.jce.provider
                .BouncyCastleProvider());
    }

    public void writeFile(String fileName, String theFile) {
        try {
            Cipher cipher = Cipher.getInstance(AES_ALGORITHM, PROVIDER);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivSpec);
            byte[] encrypted = cipher.doFinal(theFile.getBytes());
            ObjectOutputStream os = new ObjectOutputStream(
                new FileOutputStream(fileName));
            os.write(encrypted);
            os.flush();
            os.close();
        } catch (Exception e) {
            StackTraceElement se = new Exception().getStackTrace()[0];
            System.err.println(se.getFileName() + " " + se.getLineNumber()
                    + " " + e);
        }
    }
}

答案 1

我不是很熟悉Android sdk,但似乎附带的提供商已经添加到安全性中。android-sdkBouncyCastle

在PC环境中,您所要做的就是手动添加它,

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

如果您有权访问该文件,只需添加如下条目:policy

security.provider.5=org.bouncycastle.jce.provider.BouncyCastleProvider 

请注意,它等于已添加的提供程序的序号。.5


答案 2

您可以通过使用以下代码编辑java.security并创建静态块来添加安全性提供程序:

static {
    Security.addProvider(new BouncyCastleProvider());
}

如果您使用的是maven项目,那么您将不得不为BouncyCastleProvider添加依赖项,如下所示在项目的pom.xml文件中。

<dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.47</version>
</dependency>

如果您使用的是普通的java项目,则可以从下面给出的链接添加下载的bcprov-jdk15on-147.jar并编辑您的类路径。

http://www.java2s.com/Code/Jar/b/Downloadbcprovextjdk15on147jar.htm