标签: bouncycastle

如何使用AES和PBE的Bouncy Castle轻量级API

我有一块使用JCE算法"PBEWithSHA256And256BitAES-CBC-BC"创建的密文.提供者是BouncyCastle.我想做的是使用BouncyCastle轻量级API解密这个密文.我不想使用JCE,因为这需要安装Unlimited Strength Jurisdiction Policy Files.

在使用BC与PBE和AES时,文档似乎很薄.

这是我到目前为止所拥有的.解密代码无例外地运行但返回垃圾.

加密代码,

String password = "qwerty";
String plainText = "hello world";

byte[] salt = generateSalt();
byte[] cipherText = encrypt(plainText, password.toCharArray(), salt);

private static byte[] generateSalt() throws NoSuchAlgorithmException {
    byte salt[] = new byte[8];
    SecureRandom saltGen = SecureRandom.getInstance("SHA1PRNG");
    saltGen.nextBytes(salt);
    return salt;
}

private static byte[] encrypt(String plainText, char[] password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    Security.addProvider(new BouncyCastleProvider());

    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);

    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKeyFactory keyFac …
Run Code Online (Sandbox Code Playgroud)

java cryptography bouncycastle jce aes

9
推荐指数
2
解决办法
1万
查看次数

x509 C#例子?

我一直在逐条填写关于x509证书创建,签名等的文章,但我还没有找到解决我问题的方法 - 想知道是否有人可以指出我正确的方向,因为我在这一点上完全糊涂了.这是我正在尝试做的事情:

对于客户端应用程序:

  1. 生成公钥/私钥对
  2. 将键作为byte []抓取并将它们存储在文件系统中.
  3. 生成x509证书
  4. 生成签名请求

对于服务器应用程序:

  1. 生成公钥/私钥对
  2. 将键作为byte []抓取并将它们存储在文件系统中.
  3. 创建自签名X509证书
  4. 签署客户证书
  5. 将客户端证书验证为由上面#3中的自签名证书签名.

我需要在.Net中以编程方式执行此操作,而不使用外部.exe,如makecert.exe或openssl.exe - 我需要使用进程内库等.

我使用Bouncy Castle,.Net Crypto,openssl等各种库来制作零碎的东西 - 但是我总是遇到一个障碍,要么缺乏文档,要么无法以字节[]的形式到达密钥对,所以我可以坚持他们等等.要么我比这更难,要么就是严重缺乏文件 - 或者两者兼而有之.

我认为之前有人必须这样做,我真的很感激一些帮助 - 我对所有建议都持开放态度 - 谢谢!

..和PKIBlackbox不是一个选项 - 它的成本太高:(

.net openssl cryptography bouncycastle x509

9
推荐指数
1
解决办法
6765
查看次数

使用Bouncy Castle的C#RSA解密

我得到了一个Base64编码加密字符串,它使用Bouncy Castle在Java中加密.下面的示例Java代码段:

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, key.getPublic());
byte[] encryptedText = cipher.doFinal("xxxxx|xxxxx".getBytes("UTF-8"));
String encodedText = new BASE64Encoder().encode(encryptedText);
Run Code Online (Sandbox Code Playgroud)

我需要使用Bouncy Castle解密生成的字符串,但是在C#中,我已经获得了关于如何在Java中执行此操作的代码片段,但我无法将其转换为C#(原因是我们正在构建.net站点,以及将成为Java站点中的iFrame.Java站点将把RSA加密字符串传递给.NET站点.下面解密的示例Java代码:

Cipher cipherDec = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipherDec.init(Cipher.DECRYPT_MODE, key.getPrivate());
byte[] decodedText = new BASE64Decoder().decodeBuffer(encodedText);
byte[] decryptedText = cipherDec.doFinal(decodedText);
String finalValue = new String(decryptedText, "UTF-8");
Run Code Online (Sandbox Code Playgroud)

我从http://www.bouncycastle.org/csharp/下载了示例,但似乎没有输入字符串值来加密的示例,然后它通过加密/解密过程.

我已经给出了模数,公共指数,私有指数,素数P,素数q,素数指数p,素数指数qcrt系数的值.

我看到我可以使用以下内容:

IAsymmetricBlockCipher signer = new Pkcs1Encoding(new RsaEngine());
signer.Init(true, pubParameters);
Run Code Online (Sandbox Code Playgroud)

但是该signer对象似乎与上面的Java示例没有相同的方法.

我只能使用的方法是

ProcessBlock(byte[] inbuf, int inOff, int inLen);
Run Code Online (Sandbox Code Playgroud)

但我无法看到如何在我的上下文中使用它. …

c# java cryptography rsa bouncycastle

9
推荐指数
1
解决办法
1万
查看次数

Why does SSL handshaking sometimes kill my CPU?

We are running in to a very strange problem: we're using a modified version of the Selenium HTTP proxy (more akin to the BrowserMob Proxy) and finding that in some circumstances, which we can't reliably reproduce, CPU grinds to a halt when handling SSL connections.

A stack dump reveals that that the thread gets either stuck here:

"ProxyHandler$SslRelay3-1" prio=10 tid=0x09f9a400 nid=0x81f runnable [0xb2e69000]
   java.lang.Thread.State: RUNNABLE
    at java.math.BigInteger.multiply(BigInteger.java:1144)
    at java.math.BigInteger.lucasLehmerSequence(BigInteger.java:820)
    at java.math.BigInteger.passesLucasLehmer(BigInteger.java:750)
    at java.math.BigInteger.primeToCertainty(BigInteger.java:730)
    at java.math.BitSieve.retrieve(BitSieve.java:188)
    at java.math.BigInteger.largePrime(BigInteger.java:606)
    at java.math.BigInteger.<init>(BigInteger.java:511) …
Run Code Online (Sandbox Code Playgroud)

java security ssl https bouncycastle

9
推荐指数
1
解决办法
1982
查看次数

C#SignedCms的Java实现

我正在使用Java实现C#SignedCms功能.

我正在使用bouncycastle libs.问题是我得到的java签名与使用SignedCms生成的签名不同.


C#代码

X509Certificate2 certificate = new X509Certificate2("myCertPath", "myPass"); 
String text = "text"; 
ContentInfo contentInfo = new ContentInfo(System.Text.Encoding.UTF8.GetBytes(text)); 
SignedCms cms = new SignedCms(contentInfo, false); 
CmsSigner signer = new CmsSigner(certificate); 
signer.IncludeOption = X509IncludeOption.None; 
signer.DigestAlgorithm = new Oid("SHA1"); 
cms.ComputeSignature(signer, false); 
byte[] signature = cms.Encode(); 
print(signature); 
Run Code Online (Sandbox Code Playgroud)

Java代码

Security.addProvider(new BouncyCastleProvider()); 
char[] password = "myPass".toCharArray(); 
String text = "text"; 
FileInputStream fis = new FileInputStream("myCertPath"); 
KeyStore ks = KeyStore.getInstance("pkcs12"); 
ks.load(fis, password); 

String alias = ks.aliases().nextElement(); 
PrivateKey pKey = (PrivateKey)ks.getKey(alias, password); 
X509Certificate cert = (X509Certificate)ks.getCertificate(alias); 
java.util.List …
Run Code Online (Sandbox Code Playgroud)

c# java bouncycastle asn.1 digital-signature

9
推荐指数
1
解决办法
3221
查看次数

阅读C#和Bouncy Castle的RSA PrivateKey

我已成功使用OpenSSL格式写入公钥和私钥文件.

文件:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpHCHYgawzNlxVebSKXL7vfc/i
hP+dQgMxlaPEi7/vpQtV2szHjIP34MnUKelXFuIETJjOgjWAjTTJoj38MQUWc3u7
SRXaGVggqQEKH+cRi5+UcEObIfpi+cIyAm9MJqKabfJK2e5X/OS7FgAwPjgtDbZO
ZxamOrWWL8KGB+lH+QIDAQAB
-----END PUBLIC KEY-----

-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCpHCHYgawzNlxVebSKXL7vfc/ihP+dQgMxlaPEi7/vpQtV2szH
jIP34MnUKelXFuIETJjOgjWAjTTJoj38MQUWc3u7SRXaGVggqQEKH+cRi5+UcEOb
Ifpi+cIyAm9MJqKabfJK2e5X/OS7FgAwPjgtDbZOZxamOrWWL8KGB+lH+QIDAQAB
AoGBAIXtL6jFWVjdjlZrIl4JgXUtkDt21PD33IuiVKZNft4NOWLu+wp17/WZYn3S
C2fbSXfaKZIycKi0K8Ab6zcUo0+QZKMoaG5GivnqqTPVAuZchkuMUSVgjGvKAC/D
12/b+w+Shs9pvqED1CxfvtePXNwL6ZNuaREFC5hF/YpMVyg5AkEA3BUCZYJ+Ec96
2cwsdY6HocW8Kn+RIqMjkNtyLA19cQV5mpIP7kAiW6drBDlraVANi+5AgK2zQ+ZT
hYzs/JfRKwJBAMS1g5/B7XXnfC6VTRs8AMveZudi5wS/aGpaApybsfx1NTLLsm3l
GmGTkbCr+EPzvJ5zRSIAHAA6N6NdORwzEWsCQHTli+JTD5dyNvScaDkAvbYFi06f
d32IXYnBpcEUYT65A8BAOMn5ssYwBL23qf/ED431vLkcig1Ut6RGGFKKaQUCQEfa
UdkSWm39/5N4f/DZyySs+YO90csfK8HlXRzdlnc0TRlf5K5VyHwqDkatmoMfzh9G
1dLknVXL7jTjQZA2az8CQG0jRSQ599zllylMPPVibW98701Mdhb1u20p1fAOkIrz
+BNEdOPqPVIyqIP830nnFsJJgTG2eKB59ym+ypffRmA=
-----END RSA PRIVATE KEY-----
Run Code Online (Sandbox Code Playgroud)

公钥当然只包含公钥部分.

使用公钥加密我的消息后.我想读取私钥文件并解密它,但它无法正常工作.我正在尝试读取私钥,因为无法将对象强制转换为不对称密钥.

这是我的代码:

public static AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFilename)
{
    var fileStream = System.IO.File.OpenText(pemFilename);
    var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(fileStream);
    var KeyParameter = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)pemReader.ReadObject();
    return KeyParameter;
}

static void Encrypt2(string publicKeyFileName, string inputMessage, string encryptedFileName)
    {   
        UTF8Encoding utf8enc = new UTF8Encoding();
        FileStream encryptedFile = null;

        try
        {
            // Converting …
Run Code Online (Sandbox Code Playgroud)

c# encryption rsa bouncycastle

9
推荐指数
1
解决办法
3万
查看次数

加密PHP,解密Java

我在php中有一个web服务,它生成一个用于加密消息的密钥对,以及一个用于检索私钥并解密消息的java应用程序.

对于php我正在使用http://phpseclib.sourceforge.net/并拥有这两个文件:

keypair.php

<?php

set_time_limit(0);
if( file_exists('private.key') )
{
    echo file_get_contents('private.key');
}
else
{
    include('Crypt/RSA.php');
    $rsa = new Crypt_RSA();
    $rsa->createKey();
    $res = $rsa->createKey();

    $privateKey = $res['privatekey'];
    $publicKey  = $res['publickey'];

    file_put_contents('public.key', $publicKey);
    file_put_contents('private.key', $privateKey);
}

?>
Run Code Online (Sandbox Code Playgroud)

encrypt.php

<?php

include('Crypt/RSA.php');

//header("Content-type: text/plain");

set_time_limit(0);
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$rsa->loadKey(file_get_contents('public.key')); // public key

$plaintext = 'Hello World!';
$ciphertext = $rsa->encrypt($plaintext);

echo base64_encode($ciphertext);

?>
Run Code Online (Sandbox Code Playgroud)

在java中我有这个代码:

package com.example.app;

import java.io.DataInputStream;
import java.net.URL;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;

public class MainClass …
Run Code Online (Sandbox Code Playgroud)

php rsa bouncycastle public-key-encryption phpseclib

9
推荐指数
1
解决办法
4786
查看次数

使用BouncyCastle验证Java中的ECDSA签名时出错

我已经测试了一个解决方案,以验证ECDSA签名(如何从EC公钥字节中获取PublicKey对象?),它与给定数据完美配合.

这是数据:

byte[] pubKey = DatatypeConverter.parseHexBinary("049a55ad1e210cd113457ccd3465b930c9e7ade5e760ef64b63142dad43a308ed08e2d85632e8ff0322d3c7fda14409eafdc4c5b8ee0882fe885c92e3789c36a7a");
byte[] message = DatatypeConverter.parseHexBinary("54686973206973206a75737420736f6d6520706f696e746c6573732064756d6d7920737472696e672e205468616e6b7320616e7977617920666f722074616b696e67207468652074696d6520746f206465636f6465206974203b2d29");
byte[] signature = DatatypeConverter.parseHexBinary("304402205fef461a4714a18a5ca6dce6d5ab8604f09f3899313a28ab430eb9860f8be9d602203c8d36446be85383af3f2e8630f40c4172543322b5e8973e03fff2309755e654");
Run Code Online (Sandbox Code Playgroud)

这是代码(打印为true):

private static boolean isValidSignature(byte[] pubKey, byte[] message,byte[] signature) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, InvalidKeySpecException {
    Signature ecdsaVerify = Signature.getInstance("SHA256withECDSA", new BouncyCastleProvider());
    ecdsaVerify.initVerify(getPublicKeyFromBytes(pubKey));
    ecdsaVerify.update(message);
    return ecdsaVerify.verify(signature);
}

private static PublicKey getPublicKeyFromBytes(byte[] pubKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
    ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("prime256v1");
    KeyFactory kf = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider());
    ECNamedCurveSpec params = new ECNamedCurveSpec("prime256v1", spec.getCurve(), spec.getG(), spec.getN());
    ECPoint point =  ECPointUtil.decodePoint(params.getCurve(), pubKey);
    ECPublicKeySpec pubKeySpec = …
Run Code Online (Sandbox Code Playgroud)

java bouncycastle signature ecdsa

9
推荐指数
1
解决办法
5428
查看次数

Jasypt与Bouncy Castle的EncryptionOperationNotPossibleException

我尝试将JasyptBouncy Castle一起使用,在Spring应用程序中提供(128Bit AES)解密实体属性,同时使用Hibernate保存它们.但是org.jasypt.exceptions.EncryptionOperationNotPossibleException当我试图保存这个委托时,我总是得到这个.

org.jasypt.exceptions.EncryptionOperationNotPossibleException
  Encryption raised an exception. A possible cause is you are using strong encryption
  algorithms and you have not installed the Java Cryptography Extension (JCE) Unlimited
  Strength Jurisdiction Policy Files in this Java Virtual Machine
at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.handleInvalidKeyException(StandardPBEByteEncryptor.java:1073)
at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.encrypt(StandardPBEByteEncryptor.java:924)
at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.encrypt(StandardPBEStringEncryptor.java:642)
at org.jasypt.hibernate4.type.AbstractEncryptedAsStringType.nullSafeSet(AbstractEncryptedAsStringType.java:155)
at org.hibernate.type.CustomType.nullSafeSet(CustomType.java:158)
Run Code Online (Sandbox Code Playgroud)

(下面的完整堆栈跟踪)

我不使用Java Cryptography Extension(JCE),这就是我尝试使用Bouncy Castle的原因

我认为弹簧配置有问题,是否有人发现问题?

我的春季配置是:

<bean id="bouncyCastleProvider" class="org.bouncycastle.jce.provider.BouncyCastleProvider"/>
<bean class="org.jasypt.hibernate4.encryptor.HibernatePBEStringEncryptor" depends-on="bouncyCastleProvider">

    <property name="provider" ref="bouncyCastleProvider"/>  
    <property name="providerName" value="BC"/>

    <property name="saltGenerator">
        <bean class="org.jasypt.salt.RandomSaltGenerator"/>
    </property>

    <property …
Run Code Online (Sandbox Code Playgroud)

java spring hibernate bouncycastle jasypt

9
推荐指数
1
解决办法
2万
查看次数

使用C#从p7 + p8文件获取PEM

介绍

我正在努力将Java库转换为.Net.

该库是多态假名解密的实现,将在荷兰用于解密欧洲eIDAS电子识别服务领域的"BSNk".

我已经转换了大部分库,并与Java版本的作者一起验证了结果.下一步是让.Net库实际上可以用于荷兰公司,这就是我在过去两周一直被困住的地方.

算法使用PEM文件中的椭圆曲线作为计算的一部分.但是客户端(库的用户)将以p7和p8文件的形式接收它,您可以将其转换/解压缩/解码(?)到PEM数据.

如何从te#7 + p8文件到C#中的PEM字符串?

最好只使用System.Security.Cryptography.Pkcs,但我目前在其他部分使用BouncyCastle(因为Java版本确实如此).下面没有列出,但我也尝试使用SignedCms和EnvelopedCms来做这件事,但除此之外什么也没有(对我来说)难以理解的错误.我在密码学方面没有很多经验,但在过去的几周里学到了很多东西.

如果我理解正确,我会解释这个,因为p7文件是PEM消息的信封,并且信封是使用p8文件中的私钥进行签名/加密的?

public static string ConvertToPem(string p7File, string p8File)
{
    var p7Data = File.ReadAllBytes(p7File);
    var p8Data = File.ReadAllBytes(p8File);

    // Java version gets the private key like this:
    // KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(bytesArray));
    var privateKey = PrivateKeyFactory.CreateKey(p8Data);

    var parser = new CmsEnvelopedDataParser(p7Data);
    var recipients = parser.GetRecipientInfos().GetRecipients().OfType<RecipientInformation>();
    var recipientInformation = recipients.First();

    //Java version gets the message like this:
    //final byte[] message = keyInfo.getContent(new JceKeyTransEnvelopedRecipient(key).setProvider("BC"));

    var keyInfo = (KeyTransRecipientInformation)recipientInformation;
    var message = keyInfo.GetContent(privateKey);

    return Encoding.ASCII.GetString(message); …
Run Code Online (Sandbox Code Playgroud)

c# cryptography bouncycastle pem pkcs#7

9
推荐指数
1
解决办法
787
查看次数