List of usage examples for org.bouncycastle.asn1.pkcs PrivateKeyInfo PrivateKeyInfo
public PrivateKeyInfo(AlgorithmIdentifier privateKeyAlgorithm, ASN1Encodable privateKey) throws IOException
From source file:ElGamalPrivatePGKey.java
License:Open Source License
/** * Return a PKCS8 representation of the key. The sequence returned * represents a full PrivateKeyInfo object. * * @return a PKCS8 representation of the key. *//* w w w . j ava 2 s .c om*/ public byte[] getEncoded() { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); PrivateKeyInfo info = new PrivateKeyInfo(new AlgorithmIdentifier(OIWObjectIdentifiers.elGamalAlgorithm, new ElGamalParameter(elSpec.getP(), elSpec.getG()).getDERObject()), new DERInteger(getX())); try { dOut.writeObject(info); dOut.close(); } catch (IOException e) { throw new RuntimeException("Error encoding ElGamal private key"); } return bOut.toByteArray(); }
From source file:ca.trustpoint.m2m.ecqv.EcqvProvider.java
License:Apache License
/** * Reconstruct the private key from the reconstruction data * * @param identifyingInfo the identity portion of the implicit certificate * @param reconstructionPoint the reconstruction point for the implicit certificate * @param privateKeyReconstructionData the private key reconstruction data associated with the * implicit certificate//from w ww . j a v a 2 s.c o m * @param ephemeralPrivateKey the requesters ephemeral private key * * @return the private key associated with the implicit certificate * * @throws IOException when there are errors with, or malformed provided data */ public PrivateKey reconstructPrivateKey(byte[] identifyingInfo, byte[] reconstructionPoint, byte[] privateKeyReconstructionData, PrivateKey ephemeralPrivateKey) throws IOException { // curve point order BigInteger n = curveParameters.getN(); // calculate H(Certu) for (byte b : identifyingInfo) { digest.update(b); } for (byte b : reconstructionPoint) { digest.update(b); } // compute the integer e from H(Certu) BigInteger e = calculateE(n, digest.digest()).mod(n); // compute the private Key dU = r + e*kU (mod n) BigInteger r = octetStringToInteger(privateKeyReconstructionData); // Check that the 'r' is less than 'n' if (n.compareTo(r) != 1) { throw new IOException("Octet String value is larger than modulus"); } // Private key dU. BigInteger dU = ((BCECPrivateKey) ephemeralPrivateKey).getD(); dU = e.multiply(dU); dU = r.add(dU); dU = dU.mod(n); return BouncyCastleProvider .getPrivateKey(new PrivateKeyInfo(algorithmId, new ASN1Integer(dU.toByteArray()))); }
From source file:com.github.autermann.sockets.ssl.SSLUtils.java
License:Apache License
private static PrivateKey createPrivateKey(PemObject privatePemObject) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { AlgorithmIdentifier algId = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE); RSAPrivateKey instance = RSAPrivateKey.getInstance(privatePemObject.getContent()); PrivateKeyInfo privateKeyInfo = new PrivateKeyInfo(algId, instance); return createKeyFromDER(privateKeyInfo.toASN1Primitive().getEncoded()); }
From source file:COSE.ECPrivateKey.java
public ECPrivateKey(OneKey oneKey) throws CoseException, IOException { X9ECParameters p = oneKey.GetCurve(); org.bouncycastle.math.ec.ECPoint pubPoint; ECDomainParameters parameters = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH()); if (oneKey.get(KeyKeys.EC2_Y).getType() == CBORType.Boolean) { byte[] X = oneKey.get(KeyKeys.EC2_X.AsCBOR()).GetByteString(); byte[] rgb = new byte[X.length + 1]; System.arraycopy(X, 0, rgb, 1, X.length); rgb[0] = (byte) (2 + (oneKey.get(KeyKeys.EC2_Y).AsBoolean() ? 1 : 0)); pubPoint = p.getCurve().decodePoint(rgb); point = new ECPoint(point.getAffineX(), point.getAffineY()); } else {/*from w ww. java2s . c o m*/ point = new ECPoint(new BigInteger(1, oneKey.get(KeyKeys.EC2_X).GetByteString()), new BigInteger(1, oneKey.get(KeyKeys.EC2_Y).GetByteString())); pubPoint = p.getCurve().createPoint(new BigInteger(1, oneKey.get(KeyKeys.EC2_X).GetByteString()), new BigInteger(1, oneKey.get(KeyKeys.EC2_Y).GetByteString())); } ECPublicKeyParameters pub = new ECPublicKeyParameters(pubPoint, parameters); ECPrivateKeyParameters priv = new ECPrivateKeyParameters( new BigInteger(1, oneKey.get(KeyKeys.EC2_D.AsCBOR()).GetByteString()), parameters); /* switch (AlgorithmID.FromCBOR(oneKey.get(KeyKeys.Algorithm))) { case ECDH_ES_HKDF_256: case ECDH_ES_HKDF_512: case ECDH_SS_HKDF_256: case ECDH_SS_HKDF_512: case ECDH_ES_HKDF_256_AES_KW_128: case ECDH_ES_HKDF_256_AES_KW_192: case ECDH_ES_HKDF_256_AES_KW_256: case ECDH_SS_HKDF_256_AES_KW_128: case ECDH_SS_HKDF_256_AES_KW_192: case ECDH_SS_HKDF_256_AES_KW_256: algorithm = "ECDH"; break; case ECDSA_256: algorithm = "SHA256withECDSA"; break; case ECDSA_384: algorithm = "SHA384withECDSA"; break; case ECDSA_512: algorithm = "SHA512withECDSA"; break; default: throw new CoseException("No algorithm specified"); } */ algorithm = "EC"; CBORObject curve = oneKey.get(KeyKeys.EC2_Curve); int keySize; ASN1ObjectIdentifier curveOID; if (curve.equals(KeyKeys.EC2_P256)) { curveOID = org.bouncycastle.asn1.sec.SECObjectIdentifiers.secp256r1; keySize = 256; } else if (curve.equals(KeyKeys.EC2_P384)) { curveOID = org.bouncycastle.asn1.sec.SECObjectIdentifiers.secp384r1; keySize = 384; } else if (curve.equals(KeyKeys.EC2_P521)) { curveOID = org.bouncycastle.asn1.sec.SECObjectIdentifiers.secp521r1; keySize = 521; } else { throw new CoseException("Unrecognized Curve"); } privateKey = new BigInteger(1, oneKey.get(KeyKeys.EC2_D).GetByteString()); ECField field = new ECFieldFp(p.getCurve().getField().getCharacteristic()); EllipticCurve crv = new EllipticCurve(field, p.getCurve().getA().toBigInteger(), p.getCurve().getB().toBigInteger()); ECPoint pt = new ECPoint(p.getG().getRawXCoord().toBigInteger(), p.getG().getRawYCoord().toBigInteger()); ecParameterSpec = new ECParameterSpec(crv, pt, p.getN(), p.getH().intValue()); AlgorithmIdentifier alg = new AlgorithmIdentifier(org.bouncycastle.asn1.x9.X9Curve.id_ecPublicKey, curveOID); org.bouncycastle.asn1.sec.ECPrivateKey asnPrivate = new org.bouncycastle.asn1.sec.ECPrivateKey(keySize, privateKey); byte[] x = asnPrivate.getEncoded(); PrivateKeyInfo asnPrivateX = new PrivateKeyInfo(alg, asnPrivate); encodedKey = asnPrivateX.getEncoded(); }
From source file:dorkbox.build.util.jar.JarSigner.java
License:Apache License
private static void writeDsaKeysToFile(DSAPrivateKeyParameters wimpyPrivateKey, DSAPublicKeyParameters wimpyPublicKey, File wimpyKeyRawFile) throws IOException, FileNotFoundException { DSAParameters parameters = wimpyPublicKey.getParameters(); // has to convert to DSAParameter so encoding works. byte[] publicKeyBytes = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(parameters.getP(), parameters.getQ(), parameters.getG()).toASN1Primitive()), new ASN1Integer(wimpyPublicKey.getY())).getEncoded(); // SAME AS://from w ww . j a v a2s . c om // Certificate[] certificates = Launcher.class.getProtectionDomain().getCodeSource().getCertificates(); // if (certificates.length != 1) { // // WHOOPS! // Exit.FailedSecurity("Incorrect certificate length!"); // } // // Certificate certificate = certificates[0]; // PublicKey publicKey = certificate.getPublicKey(); // byte[] publicKeyBytes = publicKey.getEncoded(); // // digest.reset(); // digest.update(publicKeyBytes, 0, publicKeyBytes.length); // hashPublicKeyBytes = digest.digest(); parameters = wimpyPrivateKey.getParameters(); byte[] privateKeyBytes = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(parameters.getP(), parameters.getQ(), parameters.getG()).toASN1Primitive()), new ASN1Integer(wimpyPrivateKey.getX())).getEncoded(); // write public length to bytes. byte[] publicKeySize = new byte[] { (byte) (publicKeyBytes.length >>> 24), (byte) (publicKeyBytes.length >>> 16), (byte) (publicKeyBytes.length >>> 8), (byte) (publicKeyBytes.length >>> 0) }; ByteArrayOutputStream keyOutputStream = new ByteArrayOutputStream( 4 + publicKeyBytes.length + privateKeyBytes.length); keyOutputStream.write(publicKeyBytes, 0, publicKeyBytes.length); keyOutputStream.write(privateKeyBytes, 0, privateKeyBytes.length); keyOutputStream.write(publicKeySize, 0, publicKeySize.length); // mess with people staring at the keys (store length at the end). displayByteHash(publicKeyBytes); // write out the file OutputStream outputStream = new FileOutputStream(wimpyKeyRawFile); keyOutputStream.writeTo(outputStream); Sys.close(outputStream); }
From source file:dorkbox.util.crypto.DsaTest.java
License:Apache License
@Test public void DsaJceSerializaion() throws IOException { AsymmetricCipherKeyPair generateKeyPair = CryptoDSA .generateKeyPair(new SecureRandom(entropySeed.getBytes()), 1024); DSAPrivateKeyParameters privateKey = (DSAPrivateKeyParameters) generateKeyPair.getPrivate(); DSAPublicKeyParameters publicKey = (DSAPublicKeyParameters) generateKeyPair.getPublic(); // public key as bytes. DSAParameters parameters = publicKey.getParameters(); byte[] bs = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(parameters.getP(), parameters.getQ(), parameters.getG()).toASN1Primitive()), new ASN1Integer(publicKey.getY())).getEncoded(); parameters = privateKey.getParameters(); byte[] bs2 = new PrivateKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, new DSAParameter(parameters.getP(), parameters.getQ(), parameters.getG()).toASN1Primitive()), new ASN1Integer(privateKey.getX())).getEncoded(); DSAPrivateKeyParameters privateKey2 = (DSAPrivateKeyParameters) PrivateKeyFactory.createKey(bs2); DSAPublicKeyParameters publicKey2 = (DSAPublicKeyParameters) PublicKeyFactory.createKey(bs); // test via signing byte[] bytes = "hello, my name is inigo montoya".getBytes(); BigInteger[] signature = CryptoDSA.generateSignature(privateKey, new SecureRandom(entropySeed.getBytes()), bytes);/*from w w w . j av a 2 s.co m*/ boolean verify1 = CryptoDSA.verifySignature(publicKey, bytes, signature); if (!verify1) { fail("failed signature verification"); } boolean verify2 = CryptoDSA.verifySignature(publicKey2, bytes, signature); if (!verify2) { fail("failed signature verification"); } // now reverse who signs what. BigInteger[] signatureB = CryptoDSA.generateSignature(privateKey2, new SecureRandom(entropySeed.getBytes()), bytes); boolean verifyB1 = CryptoDSA.verifySignature(publicKey, bytes, signatureB); if (!verifyB1) { fail("failed signature verification"); } boolean verifyB2 = CryptoDSA.verifySignature(publicKey2, bytes, signatureB); if (!verifyB2) { fail("failed signature verification"); } }
From source file:eu.betaas.taas.securitymanager.common.certificate.utils.PKCS12Utils.java
License:Apache License
/** * A method to create PKCS12 file that stores the certificates. * @param pfxOut: the output of pkcs12 file (in OutputStream) * @param key: private key that is associated with the credential * @param chain: chain of certificates (within the credential) * @param keyPasswd: key password/*from ww w .j av a 2 s. c o m*/ * @throws Exception */ public static void createPKCS12FileBc(OutputStream pfxOut, AsymmetricKeyParameter key, X509CertificateHolder[] chain, char[] keyPasswd) throws Exception { OutputEncryptor encOut = new BcPKCS12PBEOutputEncryptorBuilder( PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC, new CBCBlockCipher(new DESedeEngine())) .build(keyPasswd); PKCS12SafeBagBuilder taCertBagBuilder = null; PKCS12SafeBagBuilder caCertBagBuilder = null; PKCS12SafeBagBuilder eeCertBagBuilder = null; SubjectKeyIdentifier pubKeyId = null; // identify the type of certificate from the given certificate chain for (int i = 0; i < chain.length; i++) { Extensions exs = chain[i].getExtensions(); if (exs != null) { KeyUsage ku = KeyUsage.fromExtensions(exs); if (ku.toString().equals("KeyUsage: 0x" + Integer.toHexString(128 | 32))) { // end entity certificate eeCertBagBuilder = new PKCS12SafeBagBuilder(chain[i]); BcX509ExtensionUtils extUtils = new BcX509ExtensionUtils(); eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("Eric's Key")); pubKeyId = extUtils.createSubjectKeyIdentifier(chain[i].getSubjectPublicKeyInfo()); eeCertBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId); } else if (ku.toString().equals("KeyUsage: 0x" + Integer.toHexString(128 | 4 | 2))) { // intermediate certificate caCertBagBuilder = new PKCS12SafeBagBuilder(chain[i]); caCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("BETaaS Intermediate Certificate")); } } else { // root certificate taCertBagBuilder = new PKCS12SafeBagBuilder(chain[i]); taCertBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("BETaaS Primary Certificate")); } } // PKCS12SafeBagBuilder taCertBagBuilder = new PKCS12SafeBagBuilder(chain[2]); // PKCS12SafeBagBuilder caCertBagBuilder = new PKCS12SafeBagBuilder(chain[1]); // PKCS12SafeBagBuilder eeCertBagBuilder = new PKCS12SafeBagBuilder(chain[0]); // the ECPrivateKey, consists of the key itself and the ECParams BigInteger dPriv = ((ECPrivateKeyParameters) key).getD(); X9ECParameters ecParams = new X9ECParameters(((ECKeyParameters) key).getParameters().getCurve(), ((ECKeyParameters) key).getParameters().getG(), ((ECKeyParameters) key).getParameters().getN(), ((ECKeyParameters) key).getParameters().getH(), ((ECKeyParameters) key).getParameters().getSeed()); ECPrivateKey privParams = new ECPrivateKey(dPriv, ecParams); // include the ecParams AlgorithmIdentifier sigAlg = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, ecParams); // PrivateKeyInfo keyInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(key); PKCS12SafeBagBuilder keyBagBuilder = new PKCS12SafeBagBuilder(new PrivateKeyInfo(sigAlg, privParams), encOut); keyBagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString("Eric's Key")); if (pubKeyId != null) keyBagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId); PKCS12PfxPduBuilder builder = new PKCS12PfxPduBuilder(); builder.addData(keyBagBuilder.build()); // no need to insert SHA1Digest() because it is the default Digest algorithm // check each of the certbagbuilder if (caCertBagBuilder != null && taCertBagBuilder != null && eeCertBagBuilder != null) { // include all types of certificate in the file --> root own's credential builder.addEncryptedData( new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC, new CBCBlockCipher(new RC2Engine())).build(keyPasswd), new PKCS12SafeBag[] { eeCertBagBuilder.build(), caCertBagBuilder.build(), taCertBagBuilder.build() }); } else if (caCertBagBuilder != null && taCertBagBuilder != null && eeCertBagBuilder == null) { // only root and intermediate --> signer credential builder.addEncryptedData( new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC, new CBCBlockCipher(new RC2Engine())).build(keyPasswd), new PKCS12SafeBag[] { caCertBagBuilder.build(), taCertBagBuilder.build() }); } else if (caCertBagBuilder == null && taCertBagBuilder == null) { // only end entity --> e.g. application, user, etc builder.addEncryptedData( new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC, new CBCBlockCipher(new RC2Engine())).build(keyPasswd), new PKCS12SafeBag[] { eeCertBagBuilder.build() }); } else if (caCertBagBuilder != null && taCertBagBuilder == null && eeCertBagBuilder != null) { // only intermediate and end entity --> common GW certificate builder.addEncryptedData( new BcPKCS12PBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC, new CBCBlockCipher(new RC2Engine())).build(keyPasswd), new PKCS12SafeBag[] { eeCertBagBuilder.build(), caCertBagBuilder.build() }); } // PKCS12PfxPdu pfx = builder.build(new BcPKCS12MacCalculatorBuilder( // new SHA256Digest(), // new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)), keyPasswd); PKCS12PfxPdu pfx = builder.build(new BcPKCS12MacCalculatorBuilder(), keyPasswd); // make sure we don't include indefinite length encoding pfxOut.write(pfx.getEncoded(ASN1Encoding.DL)); pfxOut.close(); }
From source file:org.globus.cog.security.cert.request.BouncyCastleOpenSSLKey.java
License:Open Source License
protected PrivateKey getKey(String alg, byte[] data) throws GeneralSecurityException { if (alg.equals("RSA")) { try {/*from w ww . j a v a 2 s . c o m*/ ByteArrayInputStream bis = new ByteArrayInputStream(data); DERInputStream derin = new DERInputStream(bis); DERObject keyInfo = derin.readObject(); DERObjectIdentifier rsa_oid = PKCSObjectIdentifiers.rsaEncryption; AlgorithmIdentifier rsa = new AlgorithmIdentifier(rsa_oid); PrivateKeyInfo pkeyinfo = new PrivateKeyInfo(rsa, keyInfo); DERObject derkey = pkeyinfo.getDERObject(); byte[] keyData = BouncyCastleUtil.toByteArray(derkey); // The DER object needs to be mangled to // create a proper ProvateKeyInfo object PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyData); KeyFactory kfac = KeyFactory.getInstance("RSA"); return kfac.generatePrivate(spec); } catch (IOException e) { // that should never happen return null; } } else { return null; } }
From source file:org.globus.gsi.bc.BouncyCastleOpenSSLKey.java
License:Apache License
protected PrivateKey getKey(String alg, byte[] data) throws GeneralSecurityException { if (alg.equals("RSA")) { try {// w w w .jav a 2 s . c om if (data.length == 0) { throw new GeneralSecurityException("Cannot process empty byte stream."); } ByteArrayInputStream bis = new ByteArrayInputStream(data); ASN1InputStream derin = new ASN1InputStream(bis); ASN1Primitive keyInfo = derin.readObject(); ASN1ObjectIdentifier rsaOid = PKCSObjectIdentifiers.rsaEncryption; AlgorithmIdentifier rsa = new AlgorithmIdentifier(rsaOid); PrivateKeyInfo pkeyinfo = new PrivateKeyInfo(rsa, keyInfo); ASN1Primitive derkey = pkeyinfo.toASN1Primitive(); byte[] keyData = BouncyCastleUtil.toByteArray(derkey); // The DER object needs to be mangled to // create a proper ProvateKeyInfo object PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyData); KeyFactory kfac = KeyFactory.getInstance("RSA"); return kfac.generatePrivate(spec); } catch (IOException e) { // that should never happen return null; } } else { return null; } }
From source file:org.globus.security.bc.BouncyCastleOpenSSLKey.java
License:Apache License
protected PrivateKey getKey(String alg, byte[] data) throws GeneralSecurityException { if (alg.equals("RSA")) { try {// w w w.j av a 2 s .c om if (data.length == 0) { throw new GeneralSecurityException("Cannot process empty byte stream."); } ByteArrayInputStream bis = new ByteArrayInputStream(data); ASN1InputStream derin = new ASN1InputStream(bis); DERObject keyInfo = derin.readObject(); DERObjectIdentifier rsaOid = PKCSObjectIdentifiers.rsaEncryption; AlgorithmIdentifier rsa = new AlgorithmIdentifier(rsaOid); PrivateKeyInfo pkeyinfo = new PrivateKeyInfo(rsa, keyInfo); DERObject derkey = pkeyinfo.getDERObject(); byte[] keyData = BouncyCastleUtil.toByteArray(derkey); // The DER object needs to be mangled to // create a proper ProvateKeyInfo object PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyData); KeyFactory kfac = KeyFactory.getInstance("RSA"); return kfac.generatePrivate(spec); } catch (IOException e) { // that should never happen return null; } } else { return null; } }