Example usage for java.security PublicKey getEncoded

List of usage examples for java.security PublicKey getEncoded

Introduction

In this page you can find the example usage for java.security PublicKey getEncoded.

Prototype

public byte[] getEncoded();

Source Link

Document

Returns the key in its primary encoding format, or null if this key does not support encoding.

Usage

From source file:se.tillvaxtverket.ttsigvalws.ttwssigvalidation.pdf.PdfSignatureVerifier.java

License:asdf

/**
 * Retrieves Public key parameters from a public key
 *
 * @param pubKey The public key/*  w  ww.  j  a v a2 s  .  c  o m*/
 * @param sigResult The data object where result data are stored
 * @throws IOException
 */
public static void getPkParams(PublicKey pubKey, CMSSigVerifyResult sigResult) throws IOException {

    try {
        String pkStr = String.valueOf(Base64Coder.encode(pubKey.getEncoded()));

        ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded()));
        //ASN1Primitive pkObject = din.readObject();
        ASN1Sequence pkSeq = ASN1Sequence.getInstance(din.readObject());
        ASN1BitString keyBits = (ASN1BitString) pkSeq.getObjectAt(1);

        AlgorithmIdentifier algoId = AlgorithmIdentifier.getInstance(pkSeq.getObjectAt(0));
        PublicKeyType pkType = PublicKeyType.getTypeFromOid(algoId.getAlgorithm().getId());
        sigResult.setPkType(pkType);
        sigResult.setPkType(pkType);
        if (pkType.equals(PublicKeyType.EC)) {
            ASN1ObjectIdentifier curveOid = ASN1ObjectIdentifier.getInstance(algoId.getParameters());
            EcCurve curve = EcCurve.getEcCurveFromOid(curveOid.getId());
            sigResult.setEcCurve(curve);
            int totalKeyBits = getEcKeyLength(keyBits);
            sigResult.setKeyLength(totalKeyBits);
            return;
        }

        if (pkType.equals(PublicKeyType.RSA)) {
            ASN1InputStream keyIs = new ASN1InputStream(keyBits.getOctets());
            ASN1Sequence keyParamsSeq = ASN1Sequence.getInstance(keyIs.readObject());
            ASN1Integer modInt = ASN1Integer.getInstance(keyParamsSeq.getObjectAt(0));
            int modLen = getAsn1IntegerBitLength(modInt);
            sigResult.setKeyLength(modLen);
            return;
        }

    } catch (Exception e) {
        int asdf = 0;
    }

}

From source file:com.trsst.Common.java

/**
 * Hashes an elliptic curve public key into a shortened "satoshi-style"
 * string that we use for a publicly-readable account id. Borrowed from
 * bitsofproof./*from w w  w .ja v  a  2s  .  c o  m*/
 * 
 * @param key
 *            the account EC public key.
 * @return the account id
 */
public static String toFeedId(PublicKey key) {
    byte[] keyDigest = keyHash(key.getEncoded());
    byte[] addressBytes = new byte[keyDigest.length + 4];
    // note: now leaving out BTC's first byte identifier
    System.arraycopy(keyDigest, 0, addressBytes, 0, keyDigest.length);
    byte[] check = hash(addressBytes, 0, keyDigest.length);
    System.arraycopy(check, 0, addressBytes, keyDigest.length, 4);
    return toBase58(addressBytes);
}

From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java

/**
 * Creates a SHA-1 hash for the public key.
 * @param key to create hash for//from   ww  w.  j av  a2s.c o  m
 * @return Hex encoded hash
 */
public static String createKeyHash(PublicKey key) {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA1", "BC");
        final String res = new String(Hex.encode(md.digest(key.getEncoded())));
        return res;
    } catch (NoSuchProviderException ex) {
        final String message = "No such provider trying to hash public key";
        LOG.error(message, ex);
        throw new RuntimeException(message, ex);
    } catch (NoSuchAlgorithmException ex) {
        final String message = "No such algorithm trying to hash public key";
        LOG.error(message, ex);
        throw new RuntimeException(message, ex);
    }
}

From source file:test.integ.be.e_contract.sts.CXFSTSClientTest.java

private static X509Certificate getCertificate(PrivateKey privateKey, PublicKey publicKey) throws Exception {
    X500Name subjectName = new X500Name("CN=Test");
    X500Name issuerName = subjectName; // self-signed
    BigInteger serial = new BigInteger(128, new SecureRandom());
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuerName, serial,
            notBefore.toDate(), notAfter.toDate(), subjectName, publicKeyInfo);
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.createKey(privateKey.getEncoded());

    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(asymmetricKeyParameter);
    X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate = x509CertificateHolder.getEncoded();

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    return certificate;
}

From source file:strat.mining.stratum.proxy.Launcher.java

/**
 * Check that a valid SSl certificate already exists. If not, create a new
 * one./*from   ww  w  . j  a va2s  . c  o m*/
 * 
 * @throws Exception
 */
private static void checkCertificate() throws Exception {
    File storeFile = new File(ConfigurationManager.getInstance().getDatabaseDirectory(), KEYSTORE_FILE_NAME);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    if (!storeFile.exists()) {
        LOGGER.info("KeyStore does not exist. Create {}", storeFile.getAbsolutePath());
        storeFile.getParentFile().mkdirs();
        storeFile.createNewFile();
        keyStore.load(null, null);

        LOGGER.info("Generating new SSL certificate.");
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

        RSAKeyPairGenerator keyGenerator = new RSAKeyPairGenerator();
        keyGenerator
                .init(new RSAKeyGenerationParameters(BigInteger.valueOf(101), new SecureRandom(), 2048, 14));
        AsymmetricCipherKeyPair keysPair = keyGenerator.generateKeyPair();

        RSAKeyParameters rsaPrivateKey = (RSAKeyParameters) keysPair.getPrivate();
        RSAPrivateKeySpec rsaPrivSpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(),
                rsaPrivateKey.getExponent());
        RSAKeyParameters rsaPublicKey = (RSAKeyParameters) keysPair.getPublic();
        RSAPublicKeySpec rsaPublicSpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(),
                rsaPublicKey.getExponent());
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey rsaPriv = kf.generatePrivate(rsaPrivSpec);
        PublicKey rsaPub = kf.generatePublic(rsaPublicSpec);

        X500Name issuerDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None");
        Integer randomNumber = new SecureRandom().nextInt();
        BigInteger serialNumber = BigInteger.valueOf(randomNumber >= 0 ? randomNumber : randomNumber * -1);
        Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30);
        Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10));
        X500Name subjectDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None");
        byte[] publickeyb = rsaPub.getEncoded();
        ASN1Sequence sequence = (ASN1Sequence) ASN1Primitive.fromByteArray(publickeyb);
        SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(sequence);
        X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(issuerDN, serialNumber, notBefore,
                notAfter, subjectDN, subPubKeyInfo);

        ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
                .build(keysPair.getPrivate());
        X509CertificateHolder certificateHolder = v3CertGen.build(contentSigner);

        Certificate certificate = new CertificateFactory()
                .engineGenerateCertificate(new ByteBufferBackedInputStream(
                        ByteBuffer.wrap(certificateHolder.toASN1Structure().getEncoded())));

        LOGGER.info("Certificate generated.");

        keyStore.setKeyEntry(KEYSTORE_KEY_ENTRY_ALIAS, rsaPriv, KEYSTORE_PASSWORD.toCharArray(),
                new java.security.cert.Certificate[] { certificate });

        keyStore.store(new FileOutputStream(storeFile), KEYSTORE_PASSWORD.toCharArray());
    }
}

From source file:info.fcrp.keepitsafe.bean.UserBeanTest.java

private String generatePublicKey() throws NoSuchAlgorithmException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024, new SecureRandom());
    KeyPair kp = kpg.generateKeyPair();
    PublicKey pubKey = kp.getPublic();

    return Base64.encodeBase64String(pubKey.getEncoded());
}

From source file:org.apache.sshd.client.keyverifier.AcceptAllServerKeyVerifier.java

public boolean verifyServerKey(ClientSession sshClientSession, SocketAddress remoteAddress,
        PublicKey serverKey) {
    log.trace("Accepting key for " + remoteAddress + " key=" + BufferUtils.printHex(serverKey.getEncoded()));
    return true;//from  w ww .  j a v a  2  s. c  o m
}

From source file:com.streamsets.lib.security.util.DataSignature.java

public String encodePublicKey(PublicKey publicKey) {
    return Base64.encodeBase64String(publicKey.getEncoded());
}

From source file:be.fedict.eid.dss.model.bean.AdministratorManagerBean.java

private String getId(X509Certificate certificate) {
    PublicKey publicKey = certificate.getPublicKey();
    String id = DigestUtils.shaHex(publicKey.getEncoded());
    return id;//  ww  w.  j  a va 2  s . co  m
}

From source file:org.panbox.core.identitymgmt.UnknownContact.java

public UnknownContact(PublicKey key, String alias) {
    super();/*w w  w  . j a  v a2s  .  c  o  m*/
    this.key = key;
    this.fingerPrint = DigestUtils.sha256Hex(key.getEncoded());
    this.alias = alias;
}