public byte[] EnDecrypt(bool forEncrypt, byte[] inBytes) { cipher = CipherUtilities.GetCipher(algorithm); cipher.Init(forEncrypt, key); int outBytesSize = cipher.GetOutputSize(inBytes.Length); byte[] outBytes = new byte[outBytesSize]; int outLentgh; outLentgh = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); outLentgh += cipher.DoFinal(outBytes, outLentgh); if (outLentgh != outBytesSize) { return null; } return outBytes; }
public static string PrivateKeyEncrypt(string data) { ///加载私钥 RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider(); RsaPkcs8Util m_pPrivateRsaPkcs8Util = new RsaPkcs8Util(Encoding.GetEncoding(m_cConfigConstants.SYSTEM_ENCODING), null, m_cConfigConstants.PRIVATE_KEY); privateRsa.ImportParameters(m_pPrivateRsaPkcs8Util.PrivateRsa.ExportParameters(false)); ///转换密钥 AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa); ///使用RSA/ECB/PKCS1Padding格式 ///第一个参数为true表示加密,为false表示解密;第二个参数表示密钥 IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); ///分段加密 cipher.Init(true, keyPair.Private); byte[] dataToEncrypt = Encoding.UTF8.GetBytes(data); int bufferSize = (privateRsa.KeySize / 8) - 11; byte[] buffer = new byte[bufferSize]; byte[] outBytes = null; using (MemoryStream input = new MemoryStream(dataToEncrypt)) using (MemoryStream ouput = new MemoryStream()) { while (true) { int readLine = input.Read(buffer, 0, bufferSize); if (readLine <= 0) { break; } byte[] temp = new byte[readLine]; Array.Copy(buffer, 0, temp, 0, readLine); byte[] encrypt = cipher.DoFinal(temp); ouput.Write(encrypt, 0, encrypt.Length); } outBytes = ouput.ToArray(); } return(Convert.ToBase64String(outBytes)); }
public IActionResult Get() { string plain_text = "hello world"; // 加密 byte[] pubkey = System.Convert.FromBase64String(pub_key); Asn1Object pubKeyObj = Asn1Object.FromByteArray(pubkey); AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(SubjectPublicKeyInfo.GetInstance(pubKeyObj)); IBufferedCipher cipher1 = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); cipher1.Init(true, pubKey);//true表示加密 byte[] enc_utf8 = System.Text.Encoding.UTF8.GetBytes(plain_text); byte[] encoded_data = cipher1.DoFinal(enc_utf8); // 解密 var keyPair = ReadPem(pri_key); _logger.LogError(keyPair.ToString()); AsymmetricKeyParameter private_key = keyPair.Private; PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(private_key); Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object(); AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(asn1ObjectPrivate)); IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); cipher.Init(false, priKey); //false表示解密 var dec_utf8 = cipher.DoFinal(encoded_data); var answer = System.Text.Encoding.UTF8.GetString(dec_utf8); var result = new { plain_text, enc_utf8 = (enc_utf8), encoded_data = (encoded_data), encoded_len = (encoded_data.Length), dec_utf8 = (dec_utf8), answer }; return(Ok(result)); }
internal static byte[] TripleDESKeyWrapEncrypt(byte[] rgbKey, byte[] rgbWrappedKeyData) { byte[] rgbCKS; var sha = DigestUtilities.GetDigest("SHA-1"); rgbCKS = new byte[sha.GetDigestSize()]; sha.BlockUpdate(rgbWrappedKeyData, 0, rgbWrappedKeyData.Length); sha.DoFinal(rgbCKS, 0); byte[] rgbIV = new byte[8]; SecureRandom rng = new SecureRandom(); rng.NextBytes(rgbIV); byte[] rgbWKCKS = new byte[rgbWrappedKeyData.Length + 8]; IBufferedCipher enc1 = null; IBufferedCipher enc2 = null; try { enc1 = CipherUtilities.GetCipher("DESEDE/CBC/NOPADDING"); enc2 = CipherUtilities.GetCipher("DESEDE/CBC/NOPADDING"); enc1.Init(true, new ParametersWithIV(new DesEdeParameters(rgbKey), rgbIV)); enc2.Init(true, new ParametersWithIV(new DesEdeParameters(rgbKey), s_rgbTripleDES_KW_IV)); Buffer.BlockCopy(rgbWrappedKeyData, 0, rgbWKCKS, 0, rgbWrappedKeyData.Length); Buffer.BlockCopy(rgbCKS, 0, rgbWKCKS, rgbWrappedKeyData.Length, 8); byte[] temp1 = enc1.DoFinal(rgbWKCKS); byte[] temp2 = new byte[rgbIV.Length + temp1.Length]; Buffer.BlockCopy(rgbIV, 0, temp2, 0, rgbIV.Length); Buffer.BlockCopy(temp1, 0, temp2, rgbIV.Length, temp1.Length); Array.Reverse(temp2); return(enc2.DoFinal(temp2)); } finally { } }
public static EncryptionResult EncryptMessage(byte[] userKey, byte[] userSecret, byte[] data, ushort padding = 0, bool randomisePadding = false) { SecureRandom Random = new SecureRandom(); byte[] Salt = new byte[16]; Random.NextBytes(Salt); X9ECParameters Curve = ECNamedCurveTable.GetByName("prime256v1"); ECDomainParameters Spec = new ECDomainParameters(Curve.Curve, Curve.G, Curve.N, Curve.H, Curve.GetSeed()); ECKeyPairGenerator Generator = new ECKeyPairGenerator(); Generator.Init(new ECKeyGenerationParameters(Spec, new SecureRandom())); AsymmetricCipherKeyPair KeyPair = Generator.GenerateKeyPair(); ECDHBasicAgreement AgreementGenerator = new ECDHBasicAgreement(); AgreementGenerator.Init(KeyPair.Private); BigInteger IKM = AgreementGenerator.CalculateAgreement(new ECPublicKeyParameters(Spec.Curve.DecodePoint(userKey), Spec)); byte[] PRK = GenerateHKDF(userSecret, IKM.ToByteArrayUnsigned(), Encoding.UTF8.GetBytes("Content-Encoding: auth\0"), 32); byte[] PublicKey = ((ECPublicKeyParameters)KeyPair.Public).Q.GetEncoded(false); byte[] CEK = GenerateHKDF(Salt, PRK, CreateInfoChunk("aesgcm", userKey, PublicKey), 16); byte[] Nonce = GenerateHKDF(Salt, PRK, CreateInfoChunk("nonce", userKey, PublicKey), 12); if (randomisePadding && padding > 0) { padding = Convert.ToUInt16(Math.Abs(Random.NextInt()) % (padding + 1)); } byte[] Input = new byte[padding + 2 + data.Length]; Buffer.BlockCopy(ConvertInt(padding), 0, Input, 0, 2); Buffer.BlockCopy(data, 0, Input, padding + 2, data.Length); IBufferedCipher Cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding"); Cipher.Init(true, new AeadParameters(new KeyParameter(CEK), 128, Nonce)); byte[] Message = new byte[Cipher.GetOutputSize(Input.Length)]; Cipher.DoFinal(Input, 0, Input.Length, Message, 0); return(new EncryptionResult() { Salt = Salt, Payload = Message, PublicKey = PublicKey }); }
public static PrivateKeyInfo CreatePrivateKeyInfo( char[] passPhrase, bool wrongPkcs12Zero, EncryptedPrivateKeyInfo encInfo) { AlgorithmIdentifier algID = encInfo.EncryptionAlgorithm; IBufferedCipher cipher = PbeUtilities.CreateEngine(algID) as IBufferedCipher; if (cipher == null) { throw new Exception("Unknown encryption algorithm: " + algID.Algorithm); } ICipherParameters cipherParameters = PbeUtilities.GenerateCipherParameters( algID, passPhrase, wrongPkcs12Zero); cipher.Init(false, cipherParameters); byte[] keyBytes = cipher.DoFinal(encInfo.GetEncryptedData()); return(PrivateKeyInfo.GetInstance(keyBytes)); }
/// <summary> /// 私钥解密(XML格式) /// </summary> /// <param name="xmlPrivateKey"></param> /// <param name="strDncryptString"></param> /// <returns></returns> public string RSADecryptByPrivateKey(string xmlPrivateKey, string strDncryptString) { //加载私钥 RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider(); privateRsa.FromXmlString(xmlPrivateKey); //转换密钥 AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa); IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");// 参数与Java中加密解密的参数一致 //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥 c.Init(false, keyPair.Private); byte[] DataToDecrypt = Convert.FromBase64String(strDncryptString); byte[] outBytes = c.DoFinal(DataToDecrypt); //解密 string str = System.Text.Encoding.UTF8.GetString(outBytes); //Convert.ToBase64String(outBytes); return(str); }
/// <summary> /// 用私钥给数据进行RSA加密(PEM格式) /// </summary> /// <param name="pemPrivateKey">pem格式私钥</param> /// <param name="strEncryptString">加密字符串</param> /// <returns></returns> public string RSAEncryptByPrivateKeyPem(string pemPrivateKey, string strEncryptString) { var xmlPrivateKey = RSAKeyConvert.RSAPrivateKeyJava2DotNet(pemPrivateKey.Replace("\n", "").Replace("-----END PRIVATE KEY-----", "").Replace("-----BEGIN PRIVATE KEY-----", "")).Replace("-----BEGIN PRIVATE KEY-----", "").Replace("-----END ENCRYPTED PRIVATE KEY-----", ""); //加载私钥 RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider(); privateRsa.FromXmlString(xmlPrivateKey); //转换密钥 AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa); IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");// 参数与Java中加密解密的参数一致 //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥 c.Init(true, keyPair.Private); byte[] DataToEncrypt = Encoding.UTF8.GetBytes(strEncryptString); byte[] outBytes = c.DoFinal(DataToEncrypt);//加密 string strBase64 = Convert.ToBase64String(outBytes); return(strBase64); }
private static byte[] CryptPbeData( bool forEncryption, AlgorithmIdentifier algId, char[] password, bool wrongPkcs12Zero, byte[] data) { Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(algId.Parameters); ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters( algId.ObjectID, password, wrongPkcs12Zero, pbeParams); IBufferedCipher cipher = PbeUtilities.CreateEngine(algId.ObjectID) as IBufferedCipher; if (cipher == null) { throw new Exception("Unknown encryption algorithm: " + algId.ObjectID); } cipher.Init(forEncryption, cipherParams); return(cipher.DoFinal(data)); }
public void TestCcm() { byte[] K = Hex.Decode("404142434445464748494a4b4c4d4e4f"); byte[] N = Hex.Decode("10111213141516"); byte[] P = Hex.Decode("68656c6c6f20776f726c642121"); byte[] C = Hex.Decode("39264f148b54c456035de0a531c8344f46db12b388"); KeyParameter key = ParameterUtilities.CreateKeyParameter("AES", K); IBufferedCipher inCipher = CipherUtilities.GetCipher("AES/CCM/NoPadding"); IBufferedCipher outCipher = CipherUtilities.GetCipher("AES/CCM/NoPadding"); inCipher.Init(true, new ParametersWithIV(key, N)); byte[] enc = inCipher.DoFinal(P); if (!AreEqual(enc, C)) { Fail("ciphertext doesn't match in CCM"); } outCipher.Init(false, new ParametersWithIV(key, N)); byte[] dec = outCipher.DoFinal(C); if (!AreEqual(dec, P)) { Fail("plaintext doesn't match in CCM"); } try { inCipher = CipherUtilities.GetCipher("AES/CCM/PKCS5Padding"); Fail("bad padding missed in CCM"); } catch (SecurityUtilityException) { // expected } }
private static EncryptionResult EncryptMessage(byte[] userKey, byte[] userSecret, byte[] data, ushort padding = 0, bool randomisePadding = false) { SecureRandom random = new SecureRandom(); byte[] salt = new byte[16]; random.NextBytes(salt); X9ECParameters curve = ECNamedCurveTable.GetByName("prime256v1"); ECDomainParameters spec = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed()); ECKeyPairGenerator generator = new ECKeyPairGenerator(); generator.Init(new ECKeyGenerationParameters(spec, new SecureRandom())); AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair(); ECDHBasicAgreement agreementGenerator = new ECDHBasicAgreement(); agreementGenerator.Init(keyPair.Private); BigInteger ikm = agreementGenerator.CalculateAgreement(new ECPublicKeyParameters(spec.Curve.DecodePoint(userKey), spec)); byte[] prk = GenerateHkdf(userSecret, ikm.ToByteArrayUnsigned(), Encoding.UTF8.GetBytes("Content-Encoding: auth\0"), 32); byte[] publicKey = ((ECPublicKeyParameters)keyPair.Public).Q.GetEncoded(false); byte[] cek = GenerateHkdf(salt, prk, CreateInfoChunk("aesgcm", userKey, publicKey), 16); byte[] nonce = GenerateHkdf(salt, prk, CreateInfoChunk("nonce", userKey, publicKey), 12); if (randomisePadding && padding > 0) { padding = Convert.ToUInt16(Math.Abs(random.NextInt()) % (padding + 1)); } byte[] input = new byte[padding + 2 + data.Length]; Buffer.BlockCopy(ConvertInt(padding), 0, input, 0, 2); Buffer.BlockCopy(data, 0, input, padding + 2, data.Length); IBufferedCipher cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding"); cipher.Init(true, new AeadParameters(new KeyParameter(cek), 128, nonce)); byte[] message = new byte[cipher.GetOutputSize(input.Length)]; cipher.DoFinal(input, 0, input.Length, message, 0); return(new EncryptionResult() { Salt = salt, Payload = message, PublicKey = publicKey }); }
/// <summary> /// 公钥解密 /// </summary> /// <param name="xmlPublicKey">C#格式公钥</param> /// <param name="strEncryptString">密文</param> /// <returns></returns> public static string RSADecryptByPublicKey(string xmlPublicKey, string strEncryptString) { //得到公钥 RsaKeyParameters keyParams = RSAPublicKeyDotNet2Java(xmlPublicKey); //参数与Java中加密解密的参数一致 IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); //第一个参数 true-加密,false-解密;第二个参数表示密钥 c.Init(false, keyParams); //对密文进行base64解码 byte[] dataFromEncrypt = Convert.FromBase64String(strEncryptString); //解密 byte[] outBytes = c.DoFinal(dataFromEncrypt); //明文 string clearText = Encoding.Default.GetString(outBytes); return(clearText); }
/// <summary> /// Transforms the specified region of the specified byte array. /// </summary> /// <param name="inputBuffer">The input for which to compute the transform.</param> /// <param name="inputOffset">The offset into the byte array from which to begin using data.</param> /// <param name="inputCount">The number of bytes in the byte array to use as data.</param> /// <returns> /// The computed transform. /// </returns> /// <exception cref="System.Security.Cryptography.CryptographicException">Implementation only supports whole block processing and ECB.</exception> public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { try { byte[] final = new byte[_cipher.GetOutputSize(inputCount)]; int len = _cipher.ProcessBytes(inputBuffer, inputOffset, inputCount, final, 0); len += _cipher.DoFinal(final, len); if (len != final.Length) { byte[] shorter = new byte[len]; Array.Copy(final, 0, shorter, 0, len); final = shorter; } _cipher.Reset(); return(final); } catch (CryptoException ce) { throw new Core.Runtime.CryptoException("Error in cryptographic transformation.", ErrorStatus.CryptographicError, ce); } }
public static void Decrypt(Stream inputStream, Stream outputStream, string gamePath) { // Read the entire file into an array byte[] encryptedData = new byte[inputStream.Length - 8]; inputStream.Seek(0, SeekOrigin.Begin); inputStream.Read(encryptedData, 0, (int)inputStream.Length - 8); // Generate a CRC32 over the game path Crc32 crc32 = new Crc32(); uint seed = crc32.Get(Encoding.ASCII.GetBytes(gamePath)); // Create a new SeadRandom instance using the seed Nintendo.Sead.Random seadRandom = new Nintendo.Sead.Random(seed); // Create the encryption key and IV byte[] encryptionKey = CreateSequence(seadRandom); byte[] iv = CreateSequence(seadRandom); // Generate a KeyParameter instance KeyParameter parameter = new KeyParameter(encryptionKey); // Initialize the AES-CBC cipher IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CBC/NoPadding"); cipher.Init(false, new ParametersWithIV(parameter, iv)); // Return the decrypted bytes byte[] output = cipher.DoFinal(encryptedData); // Seek to the beginning outputStream.Seek(0, SeekOrigin.Begin); // Write to the output stream outputStream.Write(output, 0, output.Length); // Seek back to the beginning outputStream.Seek(0, SeekOrigin.Begin); }
public void TestEax() { byte[] K = Hex.Decode("233952DEE4D5ED5F9B9C6D6FF80FF478"); byte[] N = Hex.Decode("62EC67F9C3A4A407FCB2A8C49031A8B3"); byte[] P = Hex.Decode("68656c6c6f20776f726c642121"); byte[] C = Hex.Decode("2f9f76cb7659c70e4be11670a3e193ae1bc6b5762a"); KeyParameter key = ParameterUtilities.CreateKeyParameter("AES", K); IBufferedCipher inCipher = CipherUtilities.GetCipher("AES/EAX/NoPadding"); IBufferedCipher outCipher = CipherUtilities.GetCipher("AES/EAX/NoPadding"); inCipher.Init(true, new ParametersWithIV(key, N)); byte[] enc = inCipher.DoFinal(P); if (!AreEqual(enc, C)) { Fail("ciphertext doesn't match in EAX"); } outCipher.Init(false, new ParametersWithIV(key, N)); byte[] dec = outCipher.DoFinal(C); if (!AreEqual(dec, P)) { Fail("plaintext doesn't match in EAX"); } try { inCipher = CipherUtilities.GetCipher("AES/EAX/PKCS5Padding"); Fail("bad padding missed in EAX"); } catch (SecurityUtilityException) { // expected } }
internal Asn1Sequence DecryptData( AlgorithmIdentifier algId, byte[] data, char[] password, bool wrongPkcs12Zero) { Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(algId.Parameters); ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters( algId.ObjectID, password, wrongPkcs12Zero, pbeParams); IBufferedCipher cipher = PbeUtilities.CreateEngine(algId.ObjectID) as IBufferedCipher; if (cipher == null) { // TODO Throw exception? } cipher.Init(false, keyParameters); byte[] encoding = cipher.DoFinal(data); return((Asn1Sequence)Asn1Object.FromByteArray(encoding)); }
public static byte[] DecryptDES(byte[] cipherData, byte[] derivedKey) { byte[] output = null; try { KeyParameter keyparam = ParameterUtilities.CreateKeyParameter("DES", derivedKey); IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/ISO7816_4PADDING"); cipher.Init(false, keyparam); try { output = cipher.DoFinal(cipherData); } catch (System.Exception ex) { throw new CryptoException(ex.Message); } } catch { } return(output); }
/// <summary>用私钥给数据进行RSA加密 /// /// </summary> /// <param name="xmlPrivateKey">私钥</param> /// <param name="m_strEncryptString">待加密数据</param> /// <returns>加密后的数据(Base64)</returns> public static string RSAEncryptByPrivateKey(string xmlPrivateKey, string strEncryptString) { //xmlPrivateKey = RSAPrivateKeyJava2DotNet(RSAUtils.Siyao_privateKeyPEM); xmlPrivateKey = "<RSAKeyValue><Modulus>pe3HJgQ8U39K4cxD4IvOu/FjCnk0nmubcGq9PHg3Zfcum5C5WJNXSDaEcxIdxKmcBChRV5GIJxcNADh5sSiIMAdF8+B0YYFYhrH0JoZuJCRoxkKcxMwGwZcbnzXi6MEQ4a25Y5TO08fm0Ov/IipuLBd3EqKfMUZqPlFoiKB2BD0=</Modulus><Exponent>AQAB</Exponent><P>7P4HYz0ZQ2RWXnN0mn2MdN+3EqViLjTlO5kyyZwW3DPj9sCwTGTjtheM3iN+8cEbFc0FBABh33Eo9DwV2xPdUQ==</P><Q>szyo/g1auPHg8FMTd/69KDOKEHUpOavDO/24wazpkdP5G1nJfliPaLCKZGdp/PfZDkuajsKsB8iV+4i1tUsNLQ==</Q><DP>GHAhhuQ4BLEGDvtM3NlxcGPZVvzi4OznbnvfttZ3rQFU0o8QHvCQYqiPCCEU6A0Ho/neOIlpjkb2+ChyAINN4Q==</DP><DQ>a1CLgijuw8MWwe2Lv5HHIbXSGU5802nS6C1enJ9x7X00LjsRGFPf8XeaNMlyPSMMU7HSpV1LcRGZM1REL3rzNQ==</DQ><InverseQ>NHp47DqSikbu3y4EaAC72XYqZqhnsM7sh6QFGFGKVDC3mJvQiPR7EKUq+lCDL6DHplJYPaVi4SaEHZG9U6iuWg==</InverseQ><D>gVGJBXsFnTm3HbX6LNYpgFbIDtCaDuHk2j+GTsuOuXxlKb8ohP0IaHJ81cYHx089FgxqIOp+h6CydDqPtV/WivuqTqecAM7KFx8/3Z+VnfAd2cvNzXbdLnVfEjvjCas1ew7iUmk3E/Oay65is3xyZzHYqapxsmusu4pYd7BDoME=</D></RSAKeyValue>"; //加载私钥 RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider(); privateRsa.FromXmlString(xmlPrivateKey); //转换密钥 AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa); IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); // 参数与Java中加密解密的参数一致 //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥 c.Init(true, keyPair.Private); byte[] DataToEncrypt = Encoding.UTF8.GetBytes(strEncryptString); byte[] outBytes = c.DoFinal(DataToEncrypt);//加密 string strBase64 = Convert.ToBase64String(outBytes); return(strBase64); }
/// <summary> /// 用公钥给数据进行RSA解密 /// </summary> /// <param name="xmlPublicKey"> 公钥(XML格式字符串) </param> /// <param name="strDecryptString"> 要解密数据 </param> /// <returns> 解密后的数据 </returns> public static string PublicKeyDecrypt(string xmlPublicKey, string strDecryptString) { //加载公钥 RSACryptoServiceProvider publicRsa = new RSACryptoServiceProvider(); publicRsa.FromXmlString(xmlPublicKey); RSAParameters rp = publicRsa.ExportParameters(false); //转换密钥 AsymmetricKeyParameter pbk = DotNetUtilities.GetRsaPublicKey(rp); IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥 c.Init(false, pbk); byte[] DataToDecrypt = Convert.FromBase64String(strDecryptString); byte[] outBytes = c.DoFinal(DataToDecrypt);//解密 string strDec = Encoding.UTF8.GetString(outBytes); return(strDec); }
/** * signature with a "forged signature" (sig block not at end of plain text) */ private void DoTestBadSig( IAsymmetricKeyParameter priv, IAsymmetricKeyParameter pub) { IDigest sha1 = DigestUtilities.GetDigest("SHA1"); IBufferedCipher signer = CipherUtilities.GetCipher("RSA//PKCS1Padding"); signer.Init(true, priv); byte[] block = new byte[signer.GetBlockSize()]; sha1.Update((byte)0); byte[] sigHeader = Hex.Decode("3021300906052b0e03021a05000414"); Array.Copy(sigHeader, 0, block, 0, sigHeader.Length); // byte[] dig = sha1.digest(); byte[] dig = DigestUtilities.DoFinal(sha1); Array.Copy(dig, 0, block, sigHeader.Length, dig.Length); Array.Copy(sigHeader, 0, block, sigHeader.Length + dig.Length, sigHeader.Length); byte[] sig = signer.DoFinal(block); ISigner verifier = SignerUtilities.GetSigner("SHA1WithRSA"); verifier.Init(false, pub); verifier.Update((byte)0); if (verifier.VerifySignature(sig)) { Fail("bad signature passed"); } }
private Asn1Object CreateDERForRecipient(byte[] inp, X509Certificate cert) { String s = "1.2.840.113549.3.2"; byte[] outp = new byte[100]; DerObjectIdentifier derob = new DerObjectIdentifier(s); byte[] keyp = IVGenerator.GetIV(16); IBufferedCipher cf = CipherUtilities.GetCipher(derob); KeyParameter kp = new KeyParameter(keyp); byte[] iv = IVGenerator.GetIV(cf.GetBlockSize()); ParametersWithIV piv = new ParametersWithIV(kp, iv); cf.Init(true, piv); int len = cf.DoFinal(inp, outp, 0); byte[] abyte1 = new byte[len]; System.Array.Copy(outp, 0, abyte1, 0, len); DerOctetString deroctetstring = new DerOctetString(abyte1); KeyTransRecipientInfo keytransrecipientinfo = ComputeRecipientInfo(cert, keyp); DerSet derset = new DerSet(new RecipientInfo(keytransrecipientinfo)); Asn1EncodableVector ev = new Asn1EncodableVector(); ev.Add(new DerInteger(58)); ev.Add(new DerOctetString(iv)); DerSequence seq = new DerSequence(ev); AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(derob, seq); EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PkcsObjectIdentifiers.Data, algorithmidentifier, deroctetstring); Asn1Set set = null; EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, set); Org.BouncyCastle.Asn1.Cms.ContentInfo contentinfo = new Org.BouncyCastle.Asn1.Cms.ContentInfo(PkcsObjectIdentifiers.EnvelopedData, env); return(contentinfo.ToAsn1Object()); }
protected void oidTest( string[] oids, string[] names, int groupSize) { byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; for (int i = 0; i != oids.Length; i++) { IBufferedCipher c1 = CipherUtilities.GetCipher(oids[i]); IBufferedCipher c2 = CipherUtilities.GetCipher(names[i]); CipherKeyGenerator kg = GeneratorUtilities.GetKeyGenerator(oids[i]); KeyParameter k = ParameterUtilities.CreateKeyParameter(oids[i], kg.GenerateKey()); ICipherParameters cp = k; if (names[i].IndexOf("/ECB/") < 0) { cp = new ParametersWithIV(cp, new byte[16]); } c1.Init(true, cp); c2.Init(false, cp); byte[] result = c2.DoFinal(c1.DoFinal(data)); if (!AreEqual(data, result)) { Fail("failed OID test"); } if (k.GetKey().Length != (16 + ((i / groupSize) * 8))) { Fail("failed key length test"); } } }
/// <summary> /// <p> /// Close off the encrypted object - this is equivalent to calling Close() on the stream /// returned by the Open() method. /// </p> /// <p> /// <b>Note</b>: This does not close the underlying output stream, only the stream on top of /// it created by the Open() method. /// </p> /// </summary> public void Close() { if (cOut != null) { // TODO Should this all be under the try/catch block? if (digestOut != null) { // // hand code a mod detection packet // BcpgOutputStream bOut = new BcpgOutputStream( digestOut, PacketTag.ModificationDetectionCode, 20); bOut.Flush(); digestOut.Flush(); // TODO byte[] dig = DigestUtilities.DoFinal(digestOut.WriteDigest()); cOut.Write(dig, 0, dig.Length); } cOut.Flush(); try { pOut.Write(c.DoFinal()); pOut.Finish(); } catch (Exception e) { throw new IOException(e.Message, e); } cOut = null; pOut = null; } }
public string Encrypt(string data) { SecureRandom random = new SecureRandom(); // Generate 256-bits AES key byte[] aesKey = new byte[32]; random.NextBytes(aesKey); // Generate Initialization Vector byte[] IV = new byte[12]; random.NextBytes(IV); // Apply RSA/None/PKCS1Padding encryption to the AES key byte[] encyptedAESKey = rsaCipher.DoFinal(aesKey); // Apply AES/CCM/NoPadding encryption to the data byte[] cipherText = System.Text.Encoding.UTF8.GetBytes(data); var ccmParameters = new CcmParameters(new KeyParameter(aesKey), 64, IV, new byte[] { }); aesCipher = new CcmBlockCipher(new AesFastEngine()); aesCipher.Init(true, ccmParameters); var encrypted = new byte[aesCipher.GetOutputSize(cipherText.Length)]; var res = aesCipher.ProcessBytes(cipherText, 0, cipherText.Length, encrypted, 0); aesCipher.DoFinal(encrypted, res); // Merge 'IV' and 'encrypted' to 'result' byte[] result = new byte[IV.Length + encrypted.Length]; System.Buffer.BlockCopy(IV, 0, result, 0, IV.Length); System.Buffer.BlockCopy(encrypted, 0, result, IV.Length, encrypted.Length); // Return encrypted data return(Prefix + Version + Separator + System.Convert.ToBase64String(encyptedAESKey) + Separator + System.Convert.ToBase64String(result)); }
private void doTestAlgorithm( string name, byte[] keyBytes, byte[] iv, byte[] plainText, byte[] cipherText) { KeyParameter key = ParameterUtilities.CreateKeyParameter(name, keyBytes); IBufferedCipher inCipher = CipherUtilities.GetCipher(name); IBufferedCipher outCipher = CipherUtilities.GetCipher(name); if (iv != null) { inCipher.Init(true, new ParametersWithIV(key, iv)); outCipher.Init(false, new ParametersWithIV(key, iv)); } else { inCipher.Init(true, key); outCipher.Init(false, key); } byte[] enc = inCipher.DoFinal(plainText); if (!AreEqual(enc, cipherText)) { Fail(name + ": cipher text doesn't match"); } byte[] dec = outCipher.DoFinal(enc); if (!AreEqual(dec, plainText)) { Fail(name + ": plain text doesn't match"); } }
public static PrivateKeyInfo CreatePrivateKeyInfo( char[] passPhrase, bool wrongPkcs12Zero, EncryptedPrivateKeyInfo encInfo) { AlgorithmIdentifier algID = encInfo.EncryptionAlgorithm; IBufferedCipher cipher = PbeUtilities.CreateEngine(algID) as IBufferedCipher; if (cipher == null) { // TODO Throw exception? } ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters( algID, passPhrase, wrongPkcs12Zero); cipher.Init(false, keyParameters); byte[] keyBytes = encInfo.GetEncryptedData(); byte[] encoding = cipher.DoFinal(keyBytes); Asn1Object asn1Data = Asn1Object.FromByteArray(encoding); return(PrivateKeyInfo.GetInstance(asn1Data)); }
// Decrypt data using AES public byte[] decryptWithAES(byte[] input, byte [] key, bool use_GCM, int inOffset = 0) { string algo = AES_algorithm; if (use_GCM) { algo = AES_GCM_algorithm; } IBufferedCipher inCipher = CipherUtilities.GetCipher(algo); int blockSize = inCipher.GetBlockSize(); // Perform key expansion byte[] salt = new byte[blockSize]; for (int i = 0; i < blockSize; i++) { salt[i] = input[inOffset + i]; } ParametersWithIV withIV = new ParametersWithIV(new KeyParameter(key), salt); try { inCipher.Init(false, withIV); } catch (Exception e) { Logging.error(string.Format("Error initializing decryption. {0}", e.ToString())); } byte[] bytes = inCipher.DoFinal(input, inOffset + blockSize, input.Length - inOffset - blockSize); return(bytes); }
public override void PerformTest() { for (int i = 0; i != cipherTests1.Length; i += 2) { doTest(cipherTests1[i], input1, Hex.Decode(cipherTests1[i + 1])); } for (int i = 0; i != cipherTests2.Length; i += 2) { doTest(cipherTests2[i], input2, Hex.Decode(cipherTests2[i + 1])); } // // check for less than a block // try { IBufferedCipher c = CipherUtilities.GetCipher("AES/CTS/NoPadding"); c.Init(true, ParameterUtilities.CreateKeyParameter("AES", new byte[16])); c.DoFinal(new byte[4]); Fail("CTS failed to throw exception"); } catch (Exception e) { // if (!(e is IllegalBlockSizeException)) if (!(e is DataLengthException)) { Fail("CTS exception test - " + e, e); } } doTestExceptions(); }
private EncryptionResponse SealAes(KeyDataResponse keyDataResponse, string secret) { var plainText = Encoding.UTF8.GetBytes(secret); var bytes = keyDataResponse.Plaintext.ToArray(); var dataKey = new byte[32]; var hmacKey = new byte[32]; Buffer.BlockCopy(bytes, 0, dataKey, 0, 32); Buffer.BlockCopy(bytes, 32, hmacKey, 0, 32); IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CTR/NoPadding"); cipher.Init(true, new ParametersWithIV(ParameterUtilities.CreateKeyParameter("AES", dataKey), _initializationVector)); var cipherText = cipher.DoFinal(plainText); var hmac = new HMACSHA256(hmacKey); var hmacResult = hmac.ComputeHash(cipherText); return(new EncryptionResponse { CipherText = cipherText, Hmac = hmacResult }); }
internal static byte[] Crypt( bool encrypt, byte[] bytes, char[] password, string dekAlgName, byte[] iv) { PemBaseAlg baseAlg; PemMode mode; ParseDekAlgName(dekAlgName, out baseAlg, out mode); string padding; switch (mode) { case PemMode.CBC: case PemMode.ECB: padding = "PKCS5Padding"; break; case PemMode.CFB: case PemMode.OFB: padding = "NoPadding"; break; default: throw new EncryptionException("Unknown DEK algorithm: " + dekAlgName); } string algorithm; byte[] salt = iv; switch (baseAlg) { case PemBaseAlg.AES_128: case PemBaseAlg.AES_192: case PemBaseAlg.AES_256: algorithm = "AES"; if (salt.Length > 8) { salt = new byte[8]; Array.Copy(iv, 0, salt, 0, salt.Length); } break; case PemBaseAlg.BF: algorithm = "BLOWFISH"; break; case PemBaseAlg.DES: algorithm = "DES"; break; case PemBaseAlg.DES_EDE: case PemBaseAlg.DES_EDE3: algorithm = "DESede"; break; case PemBaseAlg.RC2: case PemBaseAlg.RC2_40: case PemBaseAlg.RC2_64: algorithm = "RC2"; break; default: throw new EncryptionException("Unknown DEK algorithm: " + dekAlgName); } string cipherName = algorithm + "/" + mode + "/" + padding; IBufferedCipher cipher = CipherUtilities.GetCipher(cipherName); ICipherParameters cParams = GetCipherParameters(password, baseAlg, salt); if (mode != PemMode.ECB) { cParams = new ParametersWithIV(cParams, iv); } cipher.Init(encrypt, cParams); return(cipher.DoFinal(bytes)); }
private static void DecryptThread(IBufferedCipher cipher, byte[] input, BlockingCollection<string> producerConsumerCollection, bool allPaddings = false) { var taskOutputs = new StringBuilder(); int lineCount = 0; IBlockCipherPadding[] paddings; if (allPaddings) { paddings = new IBlockCipherPadding[] { new ZeroBytePadding(), new ISO10126d2Padding(), new ISO7816d4Padding(), new Pkcs7Padding(), new TbcPadding(), new X923Padding(), new X923Padding(), }; } else { paddings = new IBlockCipherPadding[] {new Pkcs7Padding()}; } while (!producerConsumerCollection.IsCompleted) { string line; try { line = producerConsumerCollection.Take(); } catch (InvalidOperationException) { if (producerConsumerCollection.IsCompleted) break; throw; } // Use that line as the key. byte[] key = Encoding.ASCII.GetBytes(line); // For each possible padding... foreach (IBlockCipherPadding padding in paddings) { // Decrypt byte[] output; try { cipher.Init(false, new KeyParameter(key)); output = cipher.DoFinal(input); cipher.Reset(); } catch (InvalidCipherTextException) { // TODO: Possibly filder out those inputs before and/or tell the user not to generate them. continue; } // Convert to hexadecimal. foreach (byte b in output) { taskOutputs.Append(HexStringTable[b]); } taskOutputs.AppendFormat(" `{0}` [{1}]", line, padding.PaddingName); taskOutputs.AppendLine(); ++lineCount; } // Output the hashed values in a batch. if (taskOutputs.Length > 100000) { Console.Write(taskOutputs.ToString()); taskOutputs.Clear(); lineCount = 0; } } // Output the last hashed values. Console.Write(taskOutputs.ToString()); }
public static string EncryptPasswordForStorage(string password, string salt) { byte[] toBeEncrypt = Encoding.ASCII.GetBytes(salt + password); return(Convert.ToBase64String(cipher.DoFinal(toBeEncrypt))); }
/// <summary> /// Encrypt or decrypt a stream and send the result to an output stream. /// </summary> /// <param name="instream">The input stream to be encrypted.</param> /// <param name="outstream">The encrypted stream.</param> /// <param name="cipher">A PaddedBufferedBlockCipher configured to encrypt or decrypt.</param> private void DoCipher(Stream instream, Stream outstream, IBufferedCipher cipher) { byte[] buffer = new byte[1024]; int blocksize = buffer.Length; while((blocksize = instream.Read(buffer, 0, blocksize)) != 0) { byte[] enc = cipher.ProcessBytes(buffer, 0, blocksize); outstream.Write(enc, 0, enc.Length); } byte[] enc2 = cipher.DoFinal(); outstream.Write(enc2, 0, enc2.Length); outstream.Flush(); }