Example usage for java.security.interfaces RSAPublicKey getPublicExponent

List of usage examples for java.security.interfaces RSAPublicKey getPublicExponent

Introduction

In this page you can find the example usage for java.security.interfaces RSAPublicKey getPublicExponent.

Prototype

public BigInteger getPublicExponent();

Source Link

Document

Returns the public exponent.

Usage

From source file:org.excalibur.core.util.SecurityUtils2.java

public static byte[] encode(RSAPublicKey key) throws IOException {
    try (ByteArrayOutputStream buf = new ByteArrayOutputStream()) {
        write(PUBLIC_KEY_SSH_RSA_NAME, buf);
        write(key.getPublicExponent().toByteArray(), buf);
        write(key.getModulus().toByteArray(), buf);

        return buf.toByteArray();
    }/*  w  ww  .j  a va 2 s.com*/
}

From source file:VerifyDescriptors.java

private static boolean verifySignature(String digest, String signature, String signingKey) throws Exception {
    byte[] signatureBytes = Base64.decodeBase64(signature.substring(0 + "-----BEGIN SIGNATURE-----\n".length(),
            signature.length() - "-----END SIGNATURE-----\n".length()).replaceAll("\n", ""));
    RSAPublicKey rsaSigningKey = (RSAPublicKey) new PEMReader(new StringReader(signingKey)).readObject();
    RSAKeyParameters rsakp = new RSAKeyParameters(false, rsaSigningKey.getModulus(),
            rsaSigningKey.getPublicExponent());
    PKCS1Encoding pe = new PKCS1Encoding(new RSAEngine());
    pe.init(false, rsakp);/*from  ww  w  .ja  va  2 s . c  om*/
    byte[] decryptedSignatureDigest = pe.processBlock(signatureBytes, 0, signatureBytes.length);
    String decryptedSignatureDigestString = Hex.encodeHexString(decryptedSignatureDigest);
    return decryptedSignatureDigestString.equalsIgnoreCase(digest);
}

From source file:tor.TorCrypto.java

public static byte[] publicKeyToASN1(RSAPublicKey pk) throws IOException {
    byte[] modulus = pk.getModulus().toByteArray();
    byte[] pubexp = pk.getPublicExponent().toByteArray();

    ByteBuffer inner = ByteBuffer.allocate(1024);
    inner.put((byte) 2); // Integer
    inner.put((byte) 0x81); // one byte size
    inner.put((byte) modulus.length); // one byte size
    inner.put(modulus);//from   www  .  j  av a 2 s .  com

    inner.put((byte) 2); // Integer
    //inner.put((byte)0x81); // one byte size
    inner.put((byte) pubexp.length); // one byte size
    inner.put(pubexp);
    inner.flip();

    ByteBuffer outer = ByteBuffer.allocate(1024);
    outer.put((byte) 0x30); // SEQUENCE
    outer.put((byte) 0x81); // one byte size
    outer.put((byte) inner.limit()); // one byte size
    outer.put(inner);
    outer.flip();

    byte asn[] = new byte[outer.limit()];
    outer.get(asn);
    return asn;
}

From source file:VerifyDescriptors.java

private static String determineKeyHash(String key) throws Exception {
    PEMReader pemReader = new PEMReader(new StringReader(key));
    RSAPublicKey dirIdentityKey = (RSAPublicKey) pemReader.readObject();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new ASN1OutputStream(baos)
            .writeObject(new org.bouncycastle.asn1.pkcs.RSAPublicKey(dirIdentityKey.getModulus(),
                    dirIdentityKey.getPublicExponent()).toASN1Primitive());
    byte[] pkcs = baos.toByteArray();
    byte[] dirIdentityKeyHashBytes = new byte[20];
    SHA1Digest sha1 = new SHA1Digest();
    sha1.update(pkcs, 0, pkcs.length);//from w w  w .j  a  v  a2s  . c o m
    sha1.doFinal(dirIdentityKeyHashBytes, 0);
    String keyHash = Hex.encodeHexString(dirIdentityKeyHashBytes);
    return keyHash;
}

From source file:de.pawlidi.openaletheia.generator.KeyGenerator.java

public static boolean flushPublicKeySpec(final String directory, RSAPublicKey publicKey) {
    if (StringUtils.isBlank(directory) || !new File(directory).isDirectory() || publicKey == null) {
        return false;
    }// www . ja  va 2  s .  co  m
    return writeKeySpec(new File(directory, PUBLIC_KEYSPEC_FILE), publicKey.getModulus(),
            publicKey.getPublicExponent());

}

From source file:net.adamcin.httpsig.testutil.KeyTestUtil.java

public static byte[] dumpKeyBlob(PublicKey publicKey) {
    ByteArrayOutputStream byteOs = new ByteArrayOutputStream();

    try {/*from w  w  w  .j  a v a  2s  .  com*/
        if (publicKey instanceof RSAPublicKey) {
            RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
            DataOutputStream dos = new DataOutputStream(byteOs);
            dos.writeInt("ssh-rsa".getBytes().length);
            dos.write("ssh-rsa".getBytes());
            dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length);
            dos.write(rsaPublicKey.getPublicExponent().toByteArray());
            dos.writeInt(rsaPublicKey.getModulus().toByteArray().length);
            dos.write(rsaPublicKey.getModulus().toByteArray());
        } else if (publicKey instanceof DSAPublicKey) {
            DSAPublicKey dsaPublicKey = (DSAPublicKey) publicKey;
            DSAParams dsaParams = dsaPublicKey.getParams();

            DataOutputStream dos = new DataOutputStream(byteOs);
            dos.writeInt("ssh-dss".getBytes().length);
            dos.write("ssh-dss".getBytes());
            dos.writeInt(dsaParams.getP().toByteArray().length);
            dos.write(dsaParams.getP().toByteArray());
            dos.writeInt(dsaParams.getQ().toByteArray().length);
            dos.write(dsaParams.getQ().toByteArray());
            dos.writeInt(dsaParams.getG().toByteArray().length);
            dos.write(dsaParams.getG().toByteArray());
            dos.writeInt(dsaPublicKey.getY().toByteArray().length);
            dos.write(dsaPublicKey.getY().toByteArray());
        } else {
            throw new IllegalArgumentException("Not a supported public key: " + publicKey);
        }
    } catch (IOException e) {
        // shouldn't happen
        LOGGER.error("failed to dump public key blob", e);
    }
    return byteOs.toByteArray();
}

From source file:com.github.aynu.mosir.core.standard.util.SecurityHelper.java

/**
 * RSA???//from  w  w w  . j a  va2s .  co m
 * <dl>
 * <dt>?
 * <dd>RSA??????2048??????
 * </dl>
 * @return RSA?
 */
public static KeyPair createKeyPair() {
    try {
        final KeyPairGenerator generator = KeyPairGenerator.getInstance(ALGO_KEY);
        generator.initialize(2048);
        final KeyPair pair = generator.generateKeyPair();
        if (LOG.isDebugEnabled()) {
            final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();
            final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate();
            LOG.debug("public-modulus={}", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
            LOG.debug("public-exponent={}",
                    Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));
            LOG.debug("private-modulus={}", Base64.encodeBase64String(privateKey.getModulus().toByteArray()));
            LOG.debug("private-exponent={}",
                    Base64.encodeBase64String(privateKey.getPrivateExponent().toByteArray()));
        }
        return pair;
    } catch (final NoSuchAlgorithmException e) {
        throw new StandardRuntimeException(e);
    }
}

From source file:VerifyDescriptors.java

private static void verifyConsensuses() throws Exception {
    File certsDirectory = new File("in/certs");
    File consensusDirectory = new File("in/consensuses");
    if (!certsDirectory.exists() || !consensusDirectory.exists()) {
        return;// ww  w .jav a  2s .co m
    }
    Map<String, String> signingKeys = new HashMap<String, String>();

    DescriptorReader certsReader = DescriptorSourceFactory.createDescriptorReader();
    certsReader.addDirectory(certsDirectory);
    Iterator<DescriptorFile> descriptorFiles = certsReader.readDescriptors();
    int processedCerts = 0, verifiedCerts = 0;
    while (descriptorFiles.hasNext()) {
        DescriptorFile descriptorFile = descriptorFiles.next();
        if (descriptorFile.getException() != null) {
            System.err.println("Could not read/parse descriptor file " + descriptorFile.getFileName() + ": "
                    + descriptorFile.getException().getMessage());
            continue;
        }
        if (descriptorFile.getDescriptors() == null) {
            continue;
        }
        for (Descriptor descriptor : descriptorFile.getDescriptors()) {
            if (!(descriptor instanceof DirectoryKeyCertificate)) {
                continue;
            }
            DirectoryKeyCertificate cert = (DirectoryKeyCertificate) descriptor;
            boolean isVerified = true;

            /* Verify that the contained fingerprint is a hash of the signing
             * key. */
            String dirIdentityKeyHashString = determineKeyHash(cert.getDirIdentityKey());
            String fingerprintString = cert.getFingerprint().toLowerCase();
            if (!dirIdentityKeyHashString.equals(fingerprintString)) {
                System.out.println("In " + descriptorFile.getFile()
                        + ", the calculated directory identity key hash " + dirIdentityKeyHashString
                        + " does not match the contained fingerprint " + fingerprintString + "!");
                isVerified = false;
            }

            /* Verify that the router signature was created using the signing
             * key. */
            if (!verifySignature(cert.getCertificateDigest(), cert.getDirKeyCertification(),
                    cert.getDirIdentityKey())) {
                System.out.println("In " + descriptorFile.getFile()
                        + ", the decrypted directory key certification does not "
                        + "match the certificate digest!");
                isVerified = false;
            }

            /* Determine the signing key digest and remember the signing key
             * to verify consensus signatures. */
            String dirSigningKeyString = cert.getDirSigningKey();
            PEMReader pemReader2 = new PEMReader(new StringReader(dirSigningKeyString));
            RSAPublicKey dirSigningKey = (RSAPublicKey) pemReader2.readObject();
            ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
            new ASN1OutputStream(baos2)
                    .writeObject(new org.bouncycastle.asn1.pkcs.RSAPublicKey(dirSigningKey.getModulus(),
                            dirSigningKey.getPublicExponent()).toASN1Primitive());
            byte[] pkcs2 = baos2.toByteArray();
            byte[] dirSigningKeyHashBytes = new byte[20];
            SHA1Digest sha1_2 = new SHA1Digest();
            sha1_2.update(pkcs2, 0, pkcs2.length);
            sha1_2.doFinal(dirSigningKeyHashBytes, 0);
            String dirSigningKeyHashString = Hex.encodeHexString(dirSigningKeyHashBytes).toUpperCase();
            signingKeys.put(dirSigningKeyHashString, cert.getDirSigningKey());

            processedCerts++;
            if (isVerified) {
                verifiedCerts++;
            }
        }
    }
    System.out.println("Verified " + verifiedCerts + "/" + processedCerts + " certs.");

    DescriptorReader consensusReader = DescriptorSourceFactory.createDescriptorReader();
    consensusReader.addDirectory(consensusDirectory);
    Iterator<DescriptorFile> consensusFiles = consensusReader.readDescriptors();
    int processedConsensuses = 0, verifiedConsensuses = 0;
    while (consensusFiles.hasNext()) {
        DescriptorFile consensusFile = consensusFiles.next();
        if (consensusFile.getException() != null) {
            System.err.println("Could not read/parse descriptor file " + consensusFile.getFileName() + ": "
                    + consensusFile.getException().getMessage());
            continue;
        }
        if (consensusFile.getDescriptors() == null) {
            continue;
        }
        for (Descriptor descriptor : consensusFile.getDescriptors()) {
            if (!(descriptor instanceof RelayNetworkStatusConsensus)) {
                continue;
            }
            RelayNetworkStatusConsensus consensus = (RelayNetworkStatusConsensus) descriptor;
            boolean isVerified = true;

            /* Verify all signatures using the corresponding certificates. */
            if (consensus.getDirectorySignatures().isEmpty()) {
                System.out.println(consensusFile.getFile() + " does not contain any signatures.");
                continue;
            }
            for (DirectorySignature signature : consensus.getDirectorySignatures().values()) {
                String signingKeyDigest = signature.getSigningKeyDigest();
                if (!signingKeys.containsKey(signingKeyDigest)) {
                    System.out.println("Cannot find signing key with digest " + signingKeyDigest + "!");
                }
                if (!verifySignature(consensus.getConsensusDigest(), signature.getSignature(),
                        signingKeys.get(signingKeyDigest))) {
                    System.out.println("In " + consensusFile.getFile()
                            + ", the decrypted signature digest does not match the " + "consensus digest!");
                    isVerified = false;
                }
            }
            processedConsensuses++;
            if (isVerified) {
                verifiedConsensuses++;
            }
        }
    }
    System.out.println("Verified " + verifiedConsensuses + "/" + processedConsensuses + " consensuses.");
}

From source file:com.github.aynu.yukar.framework.util.SecurityHelper.java

/**
 * RSA???//from  w w  w  .  j a  v a2  s.  c om
 * <dl>
 * <dt>?
 * <dd>RSA??????2048??????
 * </dl>
 * @return RSA?
 */
public static KeyPair createKeyPair() {
    try {
        final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048);
        final KeyPair pair = generator.generateKeyPair();
        if (LOG.isDebugEnabled()) {
            final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();
            final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate();
            LOG.debug("public-modulus={}", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
            LOG.debug("public-exponent={}",
                    Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));
            LOG.debug("private-modulus={}", Base64.encodeBase64String(privateKey.getModulus().toByteArray()));
            LOG.debug("private-exponent={}",
                    Base64.encodeBase64String(privateKey.getPrivateExponent().toByteArray()));
        }
        return pair;
    } catch (final NoSuchAlgorithmException e) {
        throw new StandardRuntimeException(e);
    }
}

From source file:uk.ac.ed.epcc.webapp.ssh.PublicKeyReaderUtil.java

/** format a key (of the types supported by the {@link #load(String)} method. 
 * //from  w  w  w  . j  a  v a 2s  .  co m
 * @param key
 * @return public key string
 * @throws PublicKeyParseException 
 * @throws IOException 
 */
public static String format(PublicKey key) throws PublicKeyParseException, IOException {
    StringBuilder sb = new StringBuilder();
    String alg = key.getAlgorithm();
    if (alg.equalsIgnoreCase("RSA")) {
        RSAPublicKey pub = (RSAPublicKey) key;
        sb.append(SSH2_RSA_KEY);
        sb.append(" ");
        SSH2ByteBuffer buf = new SSH2ByteBuffer();
        buf.writeString(SSH2_RSA_KEY);
        buf.writeMPint(pub.getPublicExponent());
        buf.writeMPint(pub.getModulus());
        sb.append(Base64.encodeBase64String(buf.toByteArray()));
    } else if (alg.equalsIgnoreCase("DSA")) {
        DSAPublicKey pub = (DSAPublicKey) key;
        sb.append(SSH2_DSA_KEY);
        sb.append(" ");
        SSH2ByteBuffer buf = new SSH2ByteBuffer();
        buf.writeString(SSH2_DSA_KEY);
        DSAParams params = pub.getParams();
        buf.writeMPint(params.getP());
        buf.writeMPint(params.getQ());
        buf.writeMPint(params.getG());
        buf.writeMPint(pub.getY());
        sb.append(Base64.encodeBase64String(buf.toByteArray()));
    } else {
        throw new PublicKeyParseException(ErrorCode.UNKNOWN_PUBLIC_KEY_FILE_FORMAT);
    }
    return sb.toString();
}