public void savePublicKey(SessionID sessionID, PublicKey pubKey) { if (sessionID == null) return; X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKey.getEncoded()); // if (!Address.hasResource(fullUserId)) // return; this.store.setProperty( sessionID.getRemoteUserId() + ".publicKey", x509EncodedKeySpec.getEncoded()); // Stash the associated fingerprint. This saves calculating it in the future // and is useful for transferring rosters to other apps. try { String fingerprintString = new OtrCryptoEngineImpl().getFingerprint(pubKey); String verifiedToken = buildPublicKeyVerifiedId(sessionID.getRemoteUserId(), fingerprintString.toLowerCase()); if (!this.store.hasProperty(verifiedToken)) this.store.setProperty(verifiedToken, false); this.store.setPropertyHex( sessionID.getRemoteUserId() + ".fingerprint", Hex.decode(fingerprintString)); store.save(); } catch (OtrCryptoException e) { e.printStackTrace(); } }
/** * create from an issuer certificate and the serial number of the certificate it signed. * * @exception OCSPException if any problems occur creating the id fields. */ public CertificateID( String hashAlgorithm, X509Certificate issuerCert, BigInteger number, String provider) throws OCSPException { try { MessageDigest digest = MessageDigest.getInstance(hashAlgorithm, provider); AlgorithmIdentifier hashAlg = new AlgorithmIdentifier(new DERObjectIdentifier(hashAlgorithm), new DERNull()); X509Principal issuerName = PrincipalUtil.getSubjectX509Principal(issuerCert); digest.update(issuerName.getEncoded()); ASN1OctetString issuerNameHash = new DEROctetString(digest.digest()); PublicKey issuerKey = issuerCert.getPublicKey(); ASN1InputStream aIn = new ASN1InputStream(issuerKey.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); digest.update(info.getPublicKeyData().getBytes()); ASN1OctetString issuerKeyHash = new DEROctetString(digest.digest()); DERInteger serialNumber = new DERInteger(number); this.id = new CertID(hashAlg, issuerNameHash, issuerKeyHash, serialNumber); } catch (Exception e) { throw new OCSPException("problem creating ID: " + e, e); } }
public static Message encrypt(PublicKey pubKey, byte[] input) throws CryptoException { Message message = new Message(); message.pubKey = pubKey.getEncoded(); KeyGenerator keyGen; try { keyGen = KeyGenerator.getInstance("AES"); } catch (NoSuchAlgorithmException e) { throw new CryptoException(e); } keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); try { Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsaCipher.init(Cipher.ENCRYPT_MODE, pubKey); message.sessionKey = rsaCipher.doFinal(secretKey.getEncoded()); Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); aesCipher.init(Cipher.ENCRYPT_MODE, secretKey); AlgorithmParameters params = aesCipher.getParameters(); message.iv = params.getParameterSpec(IvParameterSpec.class).getIV(); message.ciphertext = aesCipher.doFinal(input); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidParameterSpecException e) { throw new CryptoException(e); } return message; }
public boolean generateKeys() { PublicKey keyPub; PrivateKey keyPri; SecureRandom rand; Security.addProvider(new ABAProvider()); rand = new SecureRandom(); rand.setSeed(System.currentTimeMillis()); try { KeyPairGenerator fact; KeyPair keyPair; fact = KeyPairGenerator.getInstance("RSA", "ABA"); fact.initialize(1024, rand); keyPair = fact.generateKeyPair(); keyPub = keyPair.getPublic(); keyPri = keyPair.getPrivate(); pubKey = bytesToHexStr(keyPub.getEncoded()); priKey = bytesToHexStr(keyPri.getEncoded()); } catch (Exception e) { return false; } return true; }
protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException { CipherParameters param; if (publicKey instanceof ECPublicKey) { param = ECUtil.generatePublicKeyParameter(publicKey); } else if (publicKey instanceof GOST3410Key) { param = GOST3410Util.generatePublicKeyParameter(publicKey); } else { try { byte[] bytes = publicKey.getEncoded(); publicKey = BouncyCastleProvider.getPublicKey(SubjectPublicKeyInfo.getInstance(bytes)); if (publicKey instanceof ECPublicKey) { param = ECUtil.generatePublicKeyParameter(publicKey); } else { throw new InvalidKeyException("can't recognise key type in DSA based signer"); } } catch (Exception e) { throw new InvalidKeyException("can't recognise key type in DSA based signer"); } } digest.reset(); signer.init(false, param); }
@Test public void testKeygenToFileOutputStream() throws NoSuchAlgorithmException, NoSuchProviderException, IOException { final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); final SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(1024, random); KeyPair pair = keyGen.generateKeyPair(); final PrivateKey priv = pair.getPrivate(); final PublicKey pub = pair.getPublic(); // Write the private key to a file FileOutputStream privOS = new FileOutputStream("RSAPrivateKey.key"); Assert.assertNotNull(privOS); privOS.write(priv.getEncoded()); privOS.close(); // Write the private key to a file FileOutputStream publicOS = new FileOutputStream("RSAPublicKey.key"); Assert.assertNotNull(publicOS); publicOS.write(pub.getEncoded()); publicOS.close(); }
public X509Certificate create(String baseName, int months, KeyPair keyPair) throws Exception { final X509Principal newprincipal = new X509Principal("O=Auto,OU=" + baseName + ",CN=CA"); this.certGen.reset(); /* "The entity that created the certificate is responsible for assigning it a serial number to distinguish it from other certificates it issues. This information is used in numerous ways, for example when a certificate is revoked its serial number is placed in a Certificate Revocation List (CRL)" */ this.certGen.setSerialNumber(BigInteger.ZERO); final Calendar expires = Calendar.getInstance(); expires.add(Calendar.MONTH, months); this.certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000)); this.certGen.setNotAfter(expires.getTime()); this.certGen.setSubjectDN(newprincipal); this.certGen.setIssuerDN(newprincipal); this.certGen.setSignatureAlgorithm("SHA1withRSA"); final PublicKey pubkey = keyPair.getPublic(); this.certGen.setPublicKey(pubkey); // begin X509/BC security nastiness, not sure these are the very best // choices but it is working... final ByteArrayInputStream in = new ByteArrayInputStream(pubkey.getEncoded()); final SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream(in).readObject()); final SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki); final ByteArrayInputStream in2 = new ByteArrayInputStream(newprincipal.getEncoded()); final GeneralNames generalNames = new GeneralNames((ASN1Sequence) new DERInputStream(in2).readObject()); final AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(spki, generalNames, BigInteger.ZERO); this.certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); /* this.certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); */ this.certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski); this.certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki); this.certGen.addExtension( X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign)); return this.certGen.generateX509Certificate(keyPair.getPrivate()); }
private AuthorityKeyIdentifier createAuthorityKeyId(PublicKey publicKey) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(publicKey.getEncoded()); SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(bais).readObject()); return new AuthorityKeyIdentifier(info); }
public static void publicKey() throws Exception { CertificateFactory factory = CertificateFactory.getInstance("X.509"); Certificate cert = factory.generateCertificate(new FileInputStream(Constant.publickey)); PublicKey pubKey = cert.getPublicKey(); X509EncodedKeySpec ksp = new X509EncodedKeySpec(pubKey.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); publicKey = keyFactory.generatePublic(ksp); }
private static ASN1OctetString fromPublicKey(PublicKey pubKey) throws InvalidKeyException { try { SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(pubKey.getEncoded()); return (ASN1OctetString) (new SubjectKeyIdentifier(info).toASN1Object()); } catch (Exception e) { throw new InvalidKeyException("Exception extracting key details: " + e.toString()); } }
private static void dumpKeyPair(KeyPair keyPair) { PublicKey pub = keyPair.getPublic(); System.out.println("Public Key: " + getHexString(pub.getEncoded())); System.out.println( "Public Key: " + "30820222300d06092a864886f70d01010105000382020f003082020a0282020100d7d774dd8a5326b7e17d74796ae19b1ba0d7f905cc9074b4001bed78512bcdf9330b813bf70c5bcf0c389ddb557f6152e144ae0ee6b3b1a5c0a10fd93130ca5470473396e2ffb809e1743654017ed3646ce342f8bda2cb788c6f64b03ba75f9d6bf28bf039bb4c0ccb0c0921ae7f4ba4c6eb6d211fdbdc52677a9a6ef150ac7d15a44eafb510ad16229da438966fb1e9bc6425e67518f99ffadece69935f571f6d375e16fa930335c9656386525042e8c35b2c4286410267911960542ddef1c620d30a631c2d41f2be09bd6df0eaad3333987e8c94c42691d97695701ae2ac0e1e48ea925c86cbaf48ccdc8353a51ca6e95236a4de948028ffde2ffa44f5888a411fb02dfe6f77ea40057714b02a7f7a22173d6f09336bb39a2067ae67cdf26d5ab652850d897b31013a0dfae1a6b24c3713670b6ec45ecae586996f65e00d50a258d8d061e9b69cb61571c97ec5ceeb2c343f43e9c17d9ce1a6107ab241631f1ca556ae821f7a6c468f13bb6da0fc27a15189b8b58d43c5b9a5d3e06d2689d399ba3567a55f2de1440e035746c87bdcf0635588f9d000aeb3bd0122e233010b454a7e5131e2061f82ca1a5c81b54faf269afa2ef4aeb6ae5b2a79cbb1ac9e770ecd138b66178d0267232a379bcd191358ff4a3374a819a93966188708d3991605c5d5f89146086fb048600116268fab91867434ed0c599d643b7ce313a1a4450203010001"); PrivateKey priv = keyPair.getPrivate(); System.out.println("Private Key: " + getHexString(priv.getEncoded())); }
public static void writePublicKeyToFile(String filename, PublicKey key) throws CryptoException { byte[] pubKeyBytes = key.getEncoded(); EncodedKeySpec ks = new X509EncodedKeySpec(pubKeyBytes); try { writeFile(filename, ks.getEncoded()); } catch (IOException e) { throw new CryptoException(e); } }
public PKCS10CertificationRequest( String var1, X509Name var2, PublicKey var3, ASN1Set var4, PrivateKey var5, String var6) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException { String var7 = Strings.toUpperCase(var1); DERObjectIdentifier var8 = (DERObjectIdentifier) algorithms.get(var7); if (var8 == null) { throw new IllegalArgumentException("Unknown signature type requested"); } else if (var2 == null) { throw new IllegalArgumentException("subject must not be null"); } else if (var3 == null) { throw new IllegalArgumentException("public key must not be null"); } else { if (noParams.contains(var8)) { AlgorithmIdentifier var9 = new AlgorithmIdentifier(var8); this.sigAlgId = var9; } else if (params.containsKey(var7)) { DEREncodable var17 = (DEREncodable) params.get(var7); AlgorithmIdentifier var18 = new AlgorithmIdentifier(var8, var17); this.sigAlgId = var18; } else { AlgorithmIdentifier var19 = new AlgorithmIdentifier(var8, (DEREncodable) null); this.sigAlgId = var19; } try { ASN1Sequence var10 = (ASN1Sequence) ASN1Object.fromByteArray(var3.getEncoded()); SubjectPublicKeyInfo var11 = new SubjectPublicKeyInfo(var10); CertificationRequestInfo var12 = new CertificationRequestInfo(var2, var11, var4); this.reqInfo = var12; } catch (IOException var24) { throw new IllegalArgumentException("can\'t encode public key"); } Signature var13; if (var6 == null) { var13 = Signature.getInstance(var1); } else { var13 = Signature.getInstance(var1, var6); } var13.initSign(var5); try { byte[] var14 = this.reqInfo.getEncoded("DER"); var13.update(var14); } catch (Exception var23) { String var22 = "exception encoding TBS cert request - " + var23; throw new IllegalArgumentException(var22); } byte[] var15 = var13.sign(); DERBitString var16 = new DERBitString(var15); this.sigBits = var16; } }
/** * Stores the public key for a specified user from sessionID * * @param sessionID sessionID to identifiy the owner of the key * @param pubKey the key which should be stored */ public void savePublicKey(SessionID sessionID, PublicKey pubKey) { if (sessionID == null) return; X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(pubKey.getEncoded()); String userID = sessionID.getUserID(); this.store.setProperty(userID + ".publicKey", x509EncodedKeySpec.getEncoded()); this.store.removeProperty(userID + ".publicKey.verified"); }
public void setPublicKey(PublicKey key) { try { tbsGen.setSubjectPublicKeyInfo( new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(key.getEncoded())).readObject())); } catch (Exception e) { throw new IllegalArgumentException("unable to process key - " + e.toString()); } }
private byte[] getPublicKeyBytes(PublicKey publicKey) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { byte[] enc = publicKey.getEncoded(); ASN1InputStream ap = new ASN1InputStream(enc); DERSequence der = (DERSequence) ap.readObject(); DERBitString key = (DERBitString) der.getObjectAt(1); byte[] k = key.getBytes(); ap.close(); return k; }
private boolean foreceOverrideEntry(Number160 entryKey, PublicKey publicKey) { // we are in public key mode if (protectionEntryMode() == ProtectionMode.MASTER_PUBLIC_KEY && publicKey != null && publicKey.getEncoded() != null) { // if the hash of the public key is the same as the domain, we can // overwrite return isMine(entryKey, publicKey); } return false; }
private static ASN1Sequence fromKey(PublicKey pubKey) throws InvalidKeyException { try { SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(pubKey.getEncoded()).readObject()); return (ASN1Sequence) new AuthorityKeyIdentifier(info).toASN1Object(); } catch (Exception e) { throw new InvalidKeyException("can't process key: " + e); } }
protected static AlgorithmIdentifier getAlgorithmIdentifier(PublicKey key) throws CertPathValidatorException { try { ASN1InputStream aIn = new ASN1InputStream(key.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); return info.getAlgorithmId(); } catch (Exception e) { throw new ExtCertPathValidatorException("Subject public key cannot be decoded.", e); } }
public void rsaCypher(String rString, InputStream inputStream, File directory) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, IOException, BadPaddingException, IllegalBlockSizeException { kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); kp = kpg.genKeyPair(); privateKey = kp.getPrivate(); cipher = Cipher.getInstance("RSA"); File root = new File(Environment.getExternalStorageDirectory() + "/Notes/", "rsapublick.txt"); // Read text from file if (root.exists()) { StringBuilder text = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(root)); String line; while ((line = br.readLine()) != null) { text.append(line); text.append('\n'); } br.close(); byte[] keyBytes = Base64.decode(text.toString().getBytes("utf-8"), 0); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); publicKey = keyFactory.generatePublic(spec); } catch (IOException e) { // You'll need to add proper error handling here } catch (InvalidKeySpecException e) { e.printStackTrace(); } } else { publicKey = kp.getPublic(); byte[] pKbytes = Base64.encode(publicKey.getEncoded(), 0); String pK = new String(pKbytes); String pubKey = "-----BEGIN public KEY-----\n" + pK + "-----END public KEY-----\n"; System.out.println(pubKey); generateNoteOnSD("rsapublick.txt", pK, directorio); } this.cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] bytes = getBytesFromInputStream(inputStream); byte[] encrypted = blockCipher(bytes, Cipher.ENCRYPT_MODE); FileOutputStream fileOutputStream = new FileOutputStream(directory); fileOutputStream.write(encrypted); fileOutputStream.close(); System.out.println("Encryptado RSA Finalizado"); root = new File(Environment.getExternalStorageDirectory() + "/Notes/", "rsaOrivatek.txt"); if (!root.exists()) { byte[] pKbytes = Base64.encode(getPrivateKey().getEncoded(), 0); String pK = new String(pKbytes); String pubKey = "-----BEGIN private KEY-----\n" + pK + "-----END private KEY-----\n"; System.out.println(pubKey); generateNoteOnSD("rsaOrivatek.txt", pK, directorio); } }
protected static AlgorithmIdentifier getAlgorithmIdentifier(PublicKey key) throws CertPathValidatorException { try { ASN1InputStream aIn = new ASN1InputStream(key.getEncoded()); SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject()); return info.getAlgorithmId(); } catch (IOException e) { throw new CertPathValidatorException("exception processing public key"); } }
public static byte[] func_75895_a(String p_75895_0_, PublicKey p_75895_1_, SecretKey p_75895_2_) { try { return func_75893_a( "SHA-1", new byte[][] { p_75895_0_.getBytes("ISO_8859_1"), p_75895_2_.getEncoded(), p_75895_1_.getEncoded() }); } catch (UnsupportedEncodingException unsupportedencodingexception) { unsupportedencodingexception.printStackTrace(); } return null; }
public JceKeyAgreeRecipientInfoGenerator( ASN1ObjectIdentifier keyAgreementOID, PrivateKey senderPrivateKey, PublicKey senderPublicKey, ASN1ObjectIdentifier keyEncryptionOID) { super( keyAgreementOID, SubjectPublicKeyInfo.getInstance(senderPublicKey.getEncoded()), keyEncryptionOID); this.senderPublicKey = senderPublicKey; this.senderPrivateKey = senderPrivateKey; }
public boolean isPublicKeyBlackListed(PublicKey publicKey) { byte[] encoded = publicKey.getEncoded(); Digest digest = AndroidDigestFactory.getSHA1(); digest.update(encoded, 0, encoded.length); byte[] out = new byte[digest.getDigestSize()]; digest.doFinal(out, 0); for (byte[] blacklisted : pubkeyBlacklist) { if (Arrays.equals(blacklisted, Hex.encode(out))) { return true; } } return false; }
public static byte[] func_75895_a( String par0Str, PublicKey par1PublicKey, SecretKey par2SecretKey) { try { return func_75893_a( "SHA-1", new byte[][] { par0Str.getBytes("ISO_8859_1"), par2SecretKey.getEncoded(), par1PublicKey.getEncoded() }); } catch (UnsupportedEncodingException var4) { var4.printStackTrace(); return null; } }
private EncodedKeySpec getSpec(byte[] encodedKey, PublicKey pub) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { byte[] encc = pub.getEncoded(); ASN1InputStream ap = new ASN1InputStream(encc); DERSequence der = (DERSequence) ap.readObject(); DERSequence s1 = (DERSequence) der.getObjectAt(0); DERBitString bit = new DERBitString(encodedKey); DERSequence s2 = new DERSequence(new DERObject[] {s1, bit}); byte[] enc = s2.getEncoded(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(enc); ap.close(); return keySpec; }
private static void testPublic(KeyFactory kf, PublicKey key) throws Exception { System.out.println("Testing public key..."); PublicKey key2 = (PublicKey) kf.translateKey(key); KeySpec keySpec = kf.getKeySpec(key, ECPublicKeySpec.class); PublicKey key3 = kf.generatePublic(keySpec); KeySpec x509Spec = kf.getKeySpec(key, X509EncodedKeySpec.class); PublicKey key4 = kf.generatePublic(x509Spec); KeySpec x509Spec2 = new X509EncodedKeySpec(key.getEncoded()); PublicKey key5 = kf.generatePublic(x509Spec2); testKey(key, key); testKey(key, key2); testKey(key, key3); testKey(key, key4); testKey(key, key5); }
/** * Creates a SHA-1 hash for the public key. * * @param key to create hash for * @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); } }
/** * Initialise the builder using a PublicKey. * * @param issuer X500Name representing the issuer of this certificate. * @param serial the serial number for the certificate. * @param notBefore date before which the certificate is not valid. * @param notAfter date after which the certificate is not valid. * @param subject X500Name representing the subject of this certificate. * @param publicKey the public key to be associated with the certificate. */ public JcaX509v3CertificateBuilder( X500Name issuer, BigInteger serial, Date notBefore, Date notAfter, X500Name subject, PublicKey publicKey) { super( issuer, serial, notBefore, notAfter, subject, SubjectPublicKeyInfo.getInstance(publicKey.getEncoded())); }
public RSAKeyPair() { KeyPairGenerator keyGen = null; try { keyGen = KeyPairGenerator.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e); } keyGen.initialize(512); java.security.KeyPair keyPair = keyGen.genKeyPair(); privateKey = keyPair.getPrivate(); publicKey = keyPair.getPublic(); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded()); pubKeyStr = Base64.byteArrayToBase64(x509EncodedKeySpec.getEncoded()); }