Exemplo n.º 1
0
 /**
  * initialise the RSA engine.
  *
  * @param forEncryption true if we are encrypting, false otherwise.
  * @param param the necessary RSA key parameters.
  */
 public void init(
     bool forEncryption,
     CipherParameters param)
 {
     this.key           = (RSAKeyParameters)param;
     this.forEncryption = forEncryption;
 }
Exemplo n.º 2
0
    public static RSA LoadDevelopment(string path, bool createIfMissing)
    {
        var fileExists = File.Exists(path);

        if (!fileExists && !createIfMissing)
        {
            throw new InvalidOperationException($"Couldn't find the file '{path}' and creation of a development key was not requested.");
        }

        if (fileExists)
        {
            var rsa = JsonConvert.DeserializeObject <RSAKeyParameters>(File.ReadAllText(path));
            return(rsa.GetRSA());
        }
        else
        {
            var parameters = RSAKeyParameters.Create();
            var directory  = Path.GetDirectoryName(path);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            File.WriteAllText(path, JsonConvert.SerializeObject(parameters));
            return(parameters.GetRSA());
        }
    }
Exemplo n.º 3
0
        public virtual void  init(bool forSigning, CipherParameters param)
        {
            RSAKeyParameters kParam = null;

            if (param is ParametersWithRandom)
            {
                ParametersWithRandom p = (ParametersWithRandom)param;

                kParam = (RSAKeyParameters)p.getParameters();
                random = p.getRandom();
            }
            else
            {
                kParam = (RSAKeyParameters)param;
                if (forSigning)
                {
                    random = new SecureRandom();
                }
            }

            cipher.init(forSigning, kParam);

            emBits = kParam.getModulus().bitLength() - 1;

            block = new byte[(emBits + 7) / 8];

            reset();
        }
Exemplo n.º 4
0
        public ScrambledKeyPair(AsymmetricCipherKeyPair pPair)
        {
            _pair = pPair;
            AsymmetricKeyParameter publicKey        = pPair.getPublic();
            RSAKeyParameters       rsaKeyParameters = publicKey as RSAKeyParameters;

            if (rsaKeyParameters != null)
            {
                ScrambledModulus = ScrambleModulus(rsaKeyParameters.getModulus());
            }
            PrivateKey = pPair.getPrivate();
        }
Exemplo n.º 5
0
        private RSAKeyParameters generateKeys()
        {
            RSAKeyPairGenerator        kpg   = new RSAKeyPairGenerator();
            RSAKeyGenerationParameters parms = new RSAKeyGenerationParameters(
                BigInteger.valueOf(0x11), new SecureRandom(), keySize,
                certainty);

            kpg.init(parms);
            AsymmetricCipherKeyPair pair = kpg.generateKeyPair();

            privateKey = (RSAKeyParameters)pair.getPrivate();
            return((RSAKeyParameters)pair.getPublic());
        }
Exemplo n.º 6
0
        public virtual void  init(bool forSigning, CipherParameters param)
        {
            RSAKeyParameters kParam = (RSAKeyParameters)param;

            cipher.init(forSigning, kParam);

            keyBits = kParam.getModulus().bitLength();

            block = new byte[(keyBits + 7) / 8];
            mBuf  = new byte[block.Length - 1];

            reset();
        }
Exemplo n.º 7
0
        public void createKeyPair(string country, string organization,
                                  string locality, string stateOrProvince, string emailAddress,
                                  string commonName)
        {
            RSAKeyParameters publicKey = generateKeys();

            certificate = generateCertificate(country, organization, locality,
                                              stateOrProvince, emailAddress, commonName, privateKey,
                                              publicKey);
            if (!certificate.isValid())
            {
                throw new Exception("Invalid certificate");
            }
        }
Exemplo n.º 8
0
        public static RSAKeyParameters GetParameters(RSA key)
        {
            var result        = new RSAKeyParameters();
            var rawParameters = key.ExportParameters(includePrivateParameters: true);

            if (rawParameters.D != null)
            {
                result.D = Convert.ToBase64String(rawParameters.D);
            }

            if (rawParameters.DP != null)
            {
                result.DP = Convert.ToBase64String(rawParameters.DP);
            }

            if (rawParameters.DQ != null)
            {
                result.DQ = Convert.ToBase64String(rawParameters.DQ);
            }

            if (rawParameters.Exponent != null)
            {
                result.E = Convert.ToBase64String(rawParameters.Exponent);
            }

            if (rawParameters.InverseQ != null)
            {
                result.IQ = Convert.ToBase64String(rawParameters.InverseQ);
            }

            if (rawParameters.Modulus != null)
            {
                result.M = Convert.ToBase64String(rawParameters.Modulus);
            }

            if (rawParameters.P != null)
            {
                result.P = Convert.ToBase64String(rawParameters.P);
            }

            if (rawParameters.Q != null)
            {
                result.Q = Convert.ToBase64String(rawParameters.Q);
            }

            return(result);
        }
Exemplo n.º 9
0
        /// <summary> Initialise the signer.
        ///
        /// </summary>
        /// <param name="forSigning">true if for signing, false if for verification.
        /// </param>
        /// <param name="param">parameters for signature generation/verification. If the
        /// parameters are for generation they should be a ParametersWithRandom,
        /// a ParametersWithSalt, or just an RSAKeyParameters object. If RSAKeyParameters
        /// are passed in a SecureRandom will be created.
        /// </param>
        /// <exception cref="ArgumentException"> IllegalArgumentException if wrong parameter type or a fixed
        /// salt is passed in which is the wrong length.
        /// </exception>
        public virtual void  init(bool forSigning, CipherParameters param)
        {
            RSAKeyParameters kParam = null;
            int lengthOfSalt        = saltLength;

            if (param is ParametersWithRandom)
            {
                ParametersWithRandom p = (ParametersWithRandom)param;

                kParam = (RSAKeyParameters)p.getParameters();
                random = p.getRandom();
            }
            else if (param is ParametersWithSalt)
            {
                ParametersWithSalt p = (ParametersWithSalt)param;

                kParam       = (RSAKeyParameters)p.getParameters();
                standardSalt = p.getSalt();
                lengthOfSalt = standardSalt.Length;
            }
            else
            {
                kParam = (RSAKeyParameters)param;
                if (forSigning)
                {
                    random = new SecureRandom();
                }
            }

            cipher.init(forSigning, kParam);

            keyBits = kParam.getModulus().bitLength();

            block = new byte[(keyBits + 7) / 8];

            if (trailer == TRAILER_IMPLICIT)
            {
                mBuf = new byte[block.Length - digest.getDigestSize() - lengthOfSalt - 1 - 1];
            }
            else
            {
                mBuf = new byte[block.Length - digest.getDigestSize() - lengthOfSalt - 1 - 2];
            }

            reset();
        }
Exemplo n.º 10
0
        public void init(
            bool forEncryption,
            CipherParameters param)
        {
            RSAKeyParameters kParam = null;

            if (typeof(ParametersWithRandom).IsInstanceOfType(param))
            {
                ParametersWithRandom rParam = (ParametersWithRandom)param;

                kParam = (RSAKeyParameters)rParam.getParameters();
            }
            else
            {
                kParam = (RSAKeyParameters)param;
            }

            engine.init(forEncryption, kParam);

            bitSize = kParam.getModulus().bitLength();

            this.forEncryption = forEncryption;
        }
Exemplo n.º 11
0
        private X509Certificate generateCertificate(String country,
                                                    String organization, String locality, String stateOrProvince,
                                                    String emailAddress, String commonName, RSAKeyParameters privateKey,
                                                    RSAKeyParameters publicKey)
        {
            string     dateString   = DateTime.Now.ToString("yyyyMMddHHmmssfff", DateTimeFormatInfo.InvariantInfo);
            BigInteger serialNumber = new BigInteger(dateString);

            DateTime notBefore = DateTime.Today.AddDays(-1);
            DateTime notAfter  = DateTime.Today.AddDays(730);

            Hashtable attrs = new Hashtable();

            attrs.Add(X509Name.C, country);             // Country
            attrs.Add(X509Name.O, organization);        // Organization
            attrs.Add(X509Name.L, locality);            // Locality
            attrs.Add(X509Name.ST, stateOrProvince);    // State/Province
            attrs.Add(X509Name.EmailAddress, emailAddress);
            attrs.Add(X509Name.CN, commonName);         // Common Name

            // Create a certificate
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.setSerialNumber(serialNumber);
            certGen.setIssuerDN(new X509Name(attrs));
            certGen.setNotBefore(notBefore);
            certGen.setNotAfter(notAfter);
            certGen.setSubjectDN(new X509Name(attrs));
            certGen.setPublicKey(publicKey);
            certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

            X509Certificate certificate = certGen
                                          .generateX509Certificate(privateKey);

            return(certificate);
        }
Exemplo n.º 12
0
 public RSACipher(FolaighKeyStore keyStore, string keyName, bool usePrivateKey)
 {
     key = keyStore.getKey(keyName, usePrivateKey);
 }
Exemplo n.º 13
0
        /// <summary>
        /// Create a Subject Public Key Info object for a given public key.
        /// </summary>
        /// <param name="key">One of ElGammalPublicKeyParameters, DSAPublicKeyParameter, DHPublicKeyParameters, RSAKeyParameters or ECPublicKeyParameters</param>
        /// <returns>A subject public key info object.</returns>
        /// <exception cref="Exception">Throw exception if object provided is not one of the above.</exception>
        public static SubjectPublicKeyInfo CreateSubjectPublicKeyInfo(AsymmetricKeyParameter key)
        {
            if (key.isPrivate())
            {
                throw (new Exception("Private key passed - public key expected."));
            }

            if (key is ElGamalPublicKeyParameters)
            {
                ElGamalPublicKeyParameters _key = (ElGamalPublicKeyParameters)key;
                SubjectPublicKeyInfo       info =
                    new SubjectPublicKeyInfo(
                        new AlgorithmIdentifier(
                            OIWObjectIdentifiers.elGamalAlgorithm,
                            new ElGamalParameter(
                                _key.getParameters().getP(),
                                _key.getParameters().getG()
                                ).toASN1Object()), new DERInteger(_key.getY()));

                return(info);
            }


            if (key is DSAPublicKeyParameters)
            {
                DSAPublicKeyParameters _key = (DSAPublicKeyParameters)key;
                SubjectPublicKeyInfo   info =
                    new SubjectPublicKeyInfo(
                        new AlgorithmIdentifier(
                            X9ObjectIdentifiers.id_dsa,
                            new DSAParameter(_key.getParameters().getP(), _key.getParameters().getQ(), _key.getParameters().getG()).toASN1Object()),
                        new DERInteger(_key.getY())
                        );

                return(info);
            }


            if (key is DHPublicKeyParameters)
            {
                DHPublicKeyParameters _key = (DHPublicKeyParameters)key;
                SubjectPublicKeyInfo  info = new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(X9ObjectIdentifiers.dhpublicnumber,
                                            new DHParameter(_key.getParameters().getP(),
                                                            _key.getParameters().getG(),
                                                            _key.getParameters().getJ()).toASN1Object()), new DERInteger(_key.getY()));

                return(info);
            } // End of DH

            if (key is RSAKeyParameters)
            {
                RSAKeyParameters _key = (RSAKeyParameters)key;
                if (_key.isPrivate())
                {
                    throw (new Exception("Private RSA Key provided."));
                }

                SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, new DERNull()), new RSAPublicKeyStructure(_key.getModulus(), _key.getExponent()).toASN1Object());
                return(info);
            } // End of RSA.

            if (key is ECPublicKeyParameters)
            {
                ECPublicKeyParameters _key = (ECPublicKeyParameters)key;
                X9ECParameters        ecP  = new X9ECParameters(
                    _key.getParameters().getCurve(),
                    _key.getParameters().getG(),
                    _key.getParameters().getN(),
                    _key.getParameters().getH(),
                    _key.getParameters().getSeed());
                X962Parameters       x962 = new X962Parameters(ecP);
                ASN1OctetString      p    = (ASN1OctetString)(new X9ECPoint(_key.getQ()).toASN1Object());
                SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, x962.toASN1Object()), p.getOctets());
                return(info);
            } // End of EC

            throw (new Exception("Class provided no convertable:" + key.GetType()));
        }
Exemplo n.º 14
0
 public void addKey(String alias, RSAKeyParameters privateKey, X509Certificate certificate)
 {
     store.setKeyEntry(alias, new AsymmetricKeyEntry(privateKey),
                       new X509CertificateEntry[] { new X509CertificateEntry(certificate) });
 }