question
stringlengths 11
28.2k
| answer
stringlengths 26
27.7k
| tag
stringclasses 130
values | question_id
int64 935
78.4M
| score
int64 10
5.49k
|
---|---|---|---|---|
I'm trying to restart the server and then wait, using this:
- name: Restart server
shell: reboot
- name: Wait for server to restart
wait_for:
port=22
delay=1
timeout=300
But I get this error:
TASK: [iptables | Wait for server to restart] *********************************
fatal: [example.com] => failed to transfer file to /root/.ansible/tmp/ansible-tmp-1401138291.69-222045017562709/wait_for:
sftp> put /tmp/tmpApPR8k /root/.ansible/tmp/ansible-tmp-1401138291.69-222045017562709/wait_for
Connected to example.com.
Connection closed
| Ansible >= 2.7 (released in Oct 2018)
Use the built-in reboot module:
- name: Wait for server to restart
reboot:
reboot_timeout: 3600
Ansible < 2.7
Restart as a task
- name: restart server
shell: 'sleep 1 && shutdown -r now "Reboot triggered by Ansible" && sleep 1'
async: 1
poll: 0
become: true
This runs the shell command as an asynchronous task, so Ansible will not wait for end of the command. Usually async param gives maximum time for the task but as poll is set to 0, Ansible will never poll if the command has finished - it will make this command a "fire and forget". Sleeps before and after shutdown are to prevent breaking the SSH connection during restart while Ansible is still connected to your remote host.
Wait as a task
You could just use:
- name: Wait for server to restart
local_action:
module: wait_for
host={{ inventory_hostname }}
port=22
delay=10
become: false
..but you may prefer to use {{ ansible_ssh_host }} variable as the hostname and/or {{ ansible_ssh_port }} as the SSH host and port if you use entries like:
hostname ansible_ssh_host=some.other.name.com ansible_ssh_port=2222
..in your inventory (Ansible hosts file).
This will run the wait_for task on the machine running Ansible. This task will wait for port 22 to become open on your remote host, starting after 10 seconds delay.
Restart and wait as handlers
But I suggest to use both of these as handlers, not tasks.
There are 2 main reason to do this:
code reuse - you can use a handler for many tasks. Example: trigger server restart after changing the timezone and after changing the kernel,
trigger only once - if you use a handler for a few tasks, and more than 1 of them will make some change => trigger the handler, then the thing that handler does will happen only once. Example: if you have a httpd restart handler attached to httpd config change and SSL certificate update, then in case both config and SSL certificate changes httpd will be restarted only once.
Read more about handlers here.
Restarting and waiting for the restart as handlers:
handlers:
- name: Restart server
command: 'sleep 1 && shutdown -r now "Reboot triggered by Ansible" && sleep 1'
async: 1
poll: 0
ignore_errors: true
become: true
- name: Wait for server to restart
local_action:
module: wait_for
host={{ inventory_hostname }}
port=22
delay=10
become: false
..and use it in your task in a sequence, like this, here paired with rebooting the server handler:
tasks:
- name: Set hostname
hostname: name=somename
notify:
- Restart server
- Wait for server to restart
Note that handlers are run in the order they are defined, not the order they are listed in notify!
| Ansible | 23,877,781 | 47 |
I have the following /etc/ansible/hosts:
[ESNodes]
isk-vsrv643
isk-vsrv644
isk-vsrv645
[PerfSetup]
isk-dsrv613
isk-dsrv614
I know there is an option to run a playbook on particular hosts with -l
Is there a way to run a playbook only on the PerfSetup group?
| Same way as you would do for hosts : -l PerfSetup
| Ansible | 22,129,422 | 47 |
I would expect this to be pretty simple. I'm using the lineinfile module like so:
- name: Update bashrc for PythonBrew for foo user
lineinfile:
dest=/home/foo/.bashrc
backup=yes
line="[[ -s ${pythonbrew.bashrc_path} ]] && source ${pythonbrew.bashrc_path}"
owner=foo
regexp='^'
state=present
insertafter=EOF
create=True
The problem I'm having is that it's replacing the last line in the file (which is fi) with my new line rather than appending the line. This produces a syntax error.
Do I have the parameters correct? I've tried setting regexp to both '^' and '' (blank). Is there another way to go about this?
I'm using Ansible 1.3.3.
| The Ansible discussion group helped get me sorted out on this. The problem is the regexp parameter.
Since I only want the line appended to the file once, I need the regexp to match the line as closely as possible. This is complicated in my case by the fact that my line includes variables. But, assuming the line started [[ -s $HOME/.pythonbrew, I found the following to be sufficient:
- name: Update bashrc for PythonBrew for foo user
lineinfile:
dest: /home/foo/.bashrc
line: "[[ -s ${pythonbrew.bashrc_path} ]] && source ${pythonbrew.bashrc_path}"
regexp: "^\[\[ -s \\$HOME/\.pythonbrew"
owner: foo
state: present
insertafter: EOF
create: True
| Ansible | 19,688,885 | 47 |
I want to setup a MySQL server on AWS, using Ansible for the configuration management.
I am using the default AMI from Amazon (ami-3275ee5b), which uses yum for package management.
When the Playbook below is executed, all goes well. But when I run it for a second time, the task Configure the root credentials fails, because the old password of MySQL doesn't match anymore, since it has been updated the last time I ran this Playbook.
This makes the Playbook non-idempotent, which I don't like. I want to be able to run the Playbook as many times as I want.
- hosts: staging_mysql
user: ec2-user
sudo: yes
tasks:
- name: Install MySQL
action: yum name=$item
with_items:
- MySQL-python
- mysql
- mysql-server
- name: Start the MySQL service
action: service name=mysqld state=started
- name: Configure the root credentials
action: command mysqladmin -u root -p $mysql_root_password
What would be the best way to solve this, which means make the Playbook idempotent? Thanks in advance!
| I posted about this on coderwall, but I'll reproduce dennisjac's improvement in the comments of my original post.
The trick to doing it idempotently is knowing that the mysql_user module will load a ~/.my.cnf file if it finds one.
I first change the password, then copy a .my.cnf file with the password credentials. When you try to run it a second time, the myqsl_user ansible module will find the .my.cnf and use the new password.
- hosts: staging_mysql
user: ec2-user
sudo: yes
tasks:
- name: Install MySQL
action: yum name={{ item }}
with_items:
- MySQL-python
- mysql
- mysql-server
- name: Start the MySQL service
action: service name=mysqld state=started
# 'localhost' needs to be the last item for idempotency, see
# http://ansible.cc/docs/modules.html#mysql-user
- name: update mysql root password for all root accounts
mysql_user: name=root host={{ item }} password={{ mysql_root_password }} priv=*.*:ALL,GRANT
with_items:
- "{{ ansible_hostname }}"
- 127.0.0.1
- ::1
- localhost
- name: copy .my.cnf file with root password credentials
template: src=templates/root/.my.cnf dest=/root/.my.cnf owner=root mode=0600
The .my.cnf template looks like this:
[client]
user=root
password={{ mysql_root_password }}
Edit: Added privileges as recommended by Dhananjay Nene in the comments, and changed variable interpolation to use braces instead of dollar sign.
| Ansible | 16,444,306 | 47 |
Say I have this dictionary
war_files:
server1:
- file1.war
- file2.war
server2:
- file1.war
- file2.war
- file3.war
and for now I just want to loop over each item (key), and then over each item in the key (value). I did this
- name: Loop over the dictionary
debug: msg="Key={{ item.key }} value={{ item.value }}"
with_dict: "{{ war_files }}"
And I get this. It is of course correct, but is NOT what I want.
ok: [localhost] => (item={'value': [u'file1.war', u'file2.war'], 'key': u'server1'}) => {
"item": {
"key": "server1",
"value": [
"file1.war",
"file2.war"
]
},
"msg": "Server=server1, WAR=[u'file1.war', u'file2.war']"
}
ok: [localhost] => (item={'value': [u'file1.war', u'file2.war', u'file3.war'], 'key': u'server2'}) => {
"item": {
"key": "server2",
"value": [
"file1.war",
"file2.war",
"file3.war"
]
},
"msg": "Server=server2, WAR=[u'file1.war', u'file2.war', u'file3.war']"
}
I want to get an output that says
"msg": "Server=server1, WAR=file1.war"
"msg": "Server=server1, WAR=file2.war"
"msg": "Server=server2, WAR=file1.war"
"msg": "Server=server2, WAR=file2.war"
"msg": "Server=server2, WAR=file3.war"
IOW, how can I write a task to iterates over the dictionary so it goes through each key, and then the items within each key? In essence, I have a nested array and want to iterate over it?
| Hows this
- hosts: localhost
vars:
war_files:
server1:
- file1.war
- file2.war
server2:
- file1.war
- file2.war
- file3.war
tasks:
- name: Loop over subelements of the dictionary
debug:
msg: "Key={{ item.0.key }} value={{ item.1 }}"
loop: "{{ war_files | dict2items | subelements('value') }}"
dict2items, subelements filters are coming in Ansible 2.6.
FYI, if a filter for your objective doesn't exist, you can write your own in python without having to resort to jinja2 hacks. Ansible is easily extendable; filters in filter_plugins/*.py are searched by default adjacent to your plays/roles and are automatically included - see Developing Plugins for details.
| Ansible | 42,167,747 | 46 |
I want to get the service status, such as redis-server by Ansible.
I know how to use Ansible service module to stop or start system service.
But how can I get the current service status?
| You can also use the service_facts module.
Example usage:
- name: collect facts about system services
service_facts:
register: services_state
- name: Debug
debug:
var: services_state
Example output:
TASK [Debug] ******************************************************
ok: [local] => {
"services_state": {
"ansible_facts": {
"services": {
"cloud-init-local.service": {
"name": "cloud-init-local.service",
"source": "systemd",
"state": "stopped"
},
"firewalld.service": {
"name": "firewalld.service",
"source": "systemd",
"state": "stopped"
}
}
}
}
}
| Ansible | 38,847,824 | 46 |
I am trying to write an Ansible playbook that only compiles Nginx if it's not already present and at the current version. However it compiles every time which is undesirable.
This is what I have:
- shell: /usr/local/nginx/sbin/nginx -v 2>&1
register: nginxVersion
- debug:
var=nginxVersion
- name: install nginx
shell: /var/local/ansible/nginx/makenginx.sh
when: "not nginxVersion == 'nginx version: nginx/1.8.0'"
become: yes
The script all works apart from the fact that it runs the shell script every time to compile Nginx. The debug output for nginxVersion is:
ok: [server] => {
"var": {
"nginxVersion": {
"changed": true,
"cmd": "/usr/local/nginx/sbin/nginx -v 2>&1",
"delta": "0:00:00.003752",
"end": "2015-09-25 16:45:26.500409",
"invocation": {
"module_args": "/usr/local/nginx/sbin/nginx -v 2>&1",
"module_name": "shell"
},
"rc": 0,
"start": "2015-09-25 16:45:26.496657",
"stderr": "",
"stdout": "nginx version: nginx/1.8.0",
"stdout_lines": [
"nginx version: nginx/1.8.0"
],
"warnings": []
}
}
}
According to the documentation I am on the right lines, what simple trick am I missing?
| Try:
when: nginxVersion.stdout != 'nginx version: nginx/1.8.0'
or
when: '"nginx version: nginx/1.8.0" not in nginxVersion.stdout'
| Ansible | 32,786,122 | 46 |
my inventory file's contents -
[webservers]
x.x.x.x ansible_ssh_user=ubuntu
[dbservers]
x.x.x.x ansible_ssh_user=ubuntu
in my tasks file which is in common role i.e. it will run on both hosts but I want to run a following task on host webservers not in dbservers which is defined in inventory file
- name: Install required packages
apt: name={{ item }} state=present
with_items:
- '{{ programs }}'
become: yes
tags: programs
is when module helpful or there is any other way? How could I do this ?
| If you want to run your role on all hosts but only a single task limited to the webservers group, then - like you already suggested - when is your friend.
You could define a condition like:
when: inventory_hostname in groups['webservers']
| Ansible | 31,912,748 | 46 |
Does anyone have an example of decrypting and uploading a file using ansible-vault.
I am thinking about keeping my ssl certificates encrypted in source control.
It seems something like the following should work.
---
- name: upload ssl crt
copy: src=../../vault/encrypted.crt dest=/usr/local/etc/ssl/domain.crt
| The copy module now does this seamlessly as of Ansible 2.1.x. Just encrypt your file with Ansible Vault and then issue the copy task on the file.
(For reference, here's the feature that added this: https://github.com/ansible/ansible/pull/15417)
| Ansible | 22,773,294 | 46 |
This seems like it should be really simple:
tasks:
- name: install python packages
pip: name=${item} virtualenv=~/buildbot-env
with_items: [ buildbot ]
- name: create buildbot master
command: buildbot create-master ~/buildbot creates=~/buildbot/buildbot.tac
However, the command will not succeed unless the virtualenv's activate script is sourced first, and there doesn't seem to be provision to do that in the Ansible command module.
I've experimented with sourcing the activate script in various of .profile, .bashrc, .bash_login, etc, with no luck. Alternatively, there's the shell command, but it seems like kind of an awkward hack:
- name: create buildbot master
shell: source ~/buildbot-env/bin/activate && \
buildbot create-master ~/buildbot \
creates=~/buildbot/buildbot.tac executable=/bin/bash
Is there a better way?
| The better way is to use the full path to installed script - it will run in its virtualenv automatically:
tasks:
- name: install python packages
pip: name={{ item }} virtualenv={{ venv }}
with_items: [ buildbot ]
- name: create buildbot master
command: "{{ venv }}/bin/buildbot create-master ~/buildbot
creates=~/buildbot/buildbot.tac"
| Ansible | 20,040,141 | 46 |
What is the difference between
vars_files directive
and
include_vars module
Which should be used when, is any of above deprecated, discouraged?
| Both vars_files and include_vars are labeled as stable interfaces so neither of them are deprecated. Both of them have some commonalities but they solve different purposes.
vars_files:
vars_file directive can only be used when defining a play to specify variable files. The variables from those files are included in the playbook. Since it is used in the start of the play, it most likely implies that some other play(before this play) created those vars files or they were created statically before running the configuration; means they were kind of configuration variables for the play.
include_vars:
vars_files serves one purpose of including the vars from a set of files but it cannot handle the cases if
the vars files were created dynamically and you want to include them in play
include vars in a limited scope.
You have multiple vars files and you want to include them based on certain criteria e.g. if the local database exists then include configuration of local database otherwise include configuration of a remotely hosted database.
include_vars have higher priority than vars_files so, it can be used to override default configuration(vars).
include_vars are evaluated lazily(evaluated at the time when they are used).
You want to include vars dynamically using a loop.
You want to read a file and put all those variables in a named dictionary instead of reading all variables in the global variable namespace.
You want to include all files in a directory or some subset of files in a directory(based on prefix or exclusion list) without knowing the exact names of the vars file(s).
These are some of the cases which I can think of and if you want to use any of the above cases then you need include_vars.
| Ansible | 53,253,879 | 45 |
In Ansible, there are several places where variables can be defined: in the inventory, in a playbook, in variable files, etc. Can anyone explain the following observations that I have made?
When defining a Boolean variable in an inventory, it MUST be capitalized (i.e., True/False), otherwise (i.e., true/false) it will not be interpreted as a Boolean but as a String.
In any of the YAML formatted files (playbooks, roles, etc.) both True/False and true/false are interpreted as Booleans.
For example, I defined two variables in an inventory:
abc=false
xyz=False
And when debugging the type of these variables inside a role...
- debug:
msg: "abc={{ abc | type_debug }} xyz={{ xyz | type_debug }}"
... then abc becomes unicode but xyz is interpreted as a bool:
ok: [localhost] => {
"msg": "abc=unicode xyz=bool"
}
However, when defining the same variables in a playbook, like this:
vars:
abc: false
xyz: False
... then both variables are recognized as bool.
I had to realize this the hard way after executing a playbook on production, running something that should not have run because of a variable set to 'false' instead of 'False' in an inventory. Thus, I'd really like to find a clear answer about how Ansible understands Booleans and how it depends on where/how the variable is defined. Should I simply always use capitalized True/False to be on the safe side? Is it valid to say that booleans in YAML files (with format key: value) are case-insensitive, while in properties files (with format key=value) they are case-sensitive? Any deeper insights would be highly appreciated.
| Variables defined in YAML files (playbooks, vars_files, YAML-format inventories)
YAML principles
Playbooks, vars_files, and inventory files written in YAML are processed by a YAML parser first. It allows several aliases for values which will be stored as Boolean type: yes/no, true/false, on/off, defined in several cases: true/True/TRUE (thus they are not truly case-insensitive).
YAML definition specifies possible values as:
y|Y|yes|Yes|YES|n|N|no|No|NO
|true|True|TRUE|false|False|FALSE
|on|On|ON|off|Off|OFF
Ansible docs confirm that:
You can also specify a boolean value (true/false) in several forms:
create_key: yes
needs_agent: no
knows_oop: True
likes_emacs: TRUE
uses_cvs: false
However, Ansible documentation now also states:
Use lowercase ‘true’ or ‘false’ for boolean values in dictionaries if you want to be compatible with default yamllint options.
So keep that in mind if you use tools like ansible-lint, that will not be happy by default (Truthy value should be one of [false, true])
Variables defined in INI-format inventory files
Python principles
When Ansible reads an INI-format inventory, it processes the variables using Python built-in types:
Values passed in using the key=value syntax are interpreted as Python literal structure (strings, numbers, tuples, lists, dicts, booleans, None), alternatively as string. For example var=FALSE would create a string equal to FALSE.
If the value specified matches string True or False (starting with a capital letter) the type is set to Boolean, otherwise it is treated as string (unless it matches another type).
Variables defined through --extra_vars CLI parameter
All strings
All variables passed as extra-vars in CLI are of string type. You can work around that by using JSON syntax. Example:
--extra-vars '{"abc": false}'
abc will then be of type bool.
| Ansible | 47,877,464 | 45 |
I'm trying insert a line in a property file using ansible.
I want to add some property if it does not exist, but not replace it if such property already exists in the file.
I add to my ansible role
- name: add couchbase host to properties
lineinfile: dest=/database.properties regexp="^couchbase.host" line="couchbase.host=127.0.0.1"
But this replaces the property value back to 127.0.0.1 if it exists already in the file.
What I'm doing wrong?
| The lineinfile module ensures the line as defined in line is present in the file and the line is identified by your regexp. So no matter what value your setting already has, it will be overridden by your new line.
If you don't want to override the line you first need to test the content and then apply that condition to the lineinfile module. There is no module for testing the content of a file so you probably need to run grep with a shell command and check the .stdout for content. Something like this (untested):
- name: Test for line
shell: grep -c "^couchbase.host" /database.properties || true
register: test_grep
And then apply the condition to your lineinfile task:
- name: add couchbase host to properties
lineinfile:
dest: /database.properties
line: couchbase.host=127.0.0.1
when: test_grep.stdout == "0"
The regexp then can be removed since you already made sure the line doesn't exist so it never would match.
But maybe you're doing things back to front. Where does that line in the file come from? When you manage your system with Ansible there should be no other mechanisms in place which interfere with the same config files. Maybe you can work around this by adding a default value to your role?
| Ansible | 29,075,287 | 45 |
How can I run a playbook in python script? What is the equivalent of the following using ansible module in python:
ansible -i hosts dbservers -m setup
ansible-playbook -i hosts -vvvv -k site.yml
I was looking at their documenation in http://docs.ansible.com/developing_api.html but they have very limited examples.
| Deprecation Notice: This post doesn't work as of Ansible 2. The API was changed.
This is covered in the Ansible documentation under "Python API."
For example, ansible -i hosts dbservers -m setup is implemented via:
import ansible.runner
runner = ansible.runner.Runner(
module_name='setup',
module_args='',
pattern='dbservers',
)
dbservers_get_facts = runner.run()
There are a bunch of non-documented parameters in the __init__ method of Runner (from ansible.runner). There's too many to list inline, but I've included some of the parameters in this post as a guess to what you're specifically looking for.
class Runner(object):
''' core API interface to ansible '''
# see bin/ansible for how this is used...
def __init__(self,
host_list=C.DEFAULT_HOST_LIST, # ex: /etc/ansible/hosts, legacy usage
module_path=None, # ex: /usr/share/ansible
module_name=C.DEFAULT_MODULE_NAME, # ex: copy
module_args=C.DEFAULT_MODULE_ARGS, # ex: "src=/tmp/a dest=/tmp/b"
...
pattern=C.DEFAULT_PATTERN, # which hosts? ex: 'all', 'acme.example.org'
remote_user=C.DEFAULT_REMOTE_USER, # ex: 'username'
remote_pass=C.DEFAULT_REMOTE_PASS, # ex: 'password123' or None if using key
remote_port=None, # if SSH on different ports
private_key_file=C.DEFAULT_PRIVATE_KEY_FILE, # if not using keys/passwords
sudo_pass=C.DEFAULT_SUDO_PASS, # ex: 'password123' or None
...
sudo=False, # whether to run sudo or not
sudo_user=C.DEFAULT_SUDO_USER, # ex: 'root'
module_vars=None, # a playbooks internals thing
play_vars=None, #
play_file_vars=None, #
role_vars=None, #
role_params=None, #
default_vars=None, #
extra_vars=None, # extra vars specified with he playbook(s)
is_playbook=False, # running from playbook or not?
inventory=None, # reference to Inventory object
...
su=False, # Are we running our command via su?
su_user=None, # User to su to when running command, ex: 'root'
su_pass=C.DEFAULT_SU_PASS,
vault_pass=None,
...
):
For instance, the above command that specifies a sudo user and pass would be:
runner = ansible.runner.Runner(
module_name='setup',
module_args='',
pattern='dbservers',
remote_user='some_user'
remote_pass='some_pass_or_python_expression_that_returns_a_string'
)
For playbooks, look into playbook.PlayBook, which takes a similar set of initializers:
class PlayBook(object):
'''
runs an ansible playbook, given as a datastructure or YAML filename.
...
'''
# *****************************************************
def __init__(self,
playbook = None,
host_list = C.DEFAULT_HOST_LIST,
module_path = None,
....
and can be executed with the .run() method. e.g.:
from ansible.playbook import PlayBook
pb = PlayBook(playbook='/path/to/book.yml, --other initializers--)
pb.run()
more robust usage can be found in the ansible-playbook file.
As far as I know, translating playbooks to Python modules is a bit more involved, but the documentation listed above should get you covered and you can reuse the YAML parser built into Ansible to convert playbooks to variables.
| Ansible | 27,590,039 | 45 |
Below is the jinja2 template that i wrote to use in ansible.
{% set port = 1234 %}
{% set server_ip = [] %}
{% for ip in host_ip %}
{% do server_ip.append({{ ip }}:{{ port }}) %}
{% endfor %}
{% server_ip|join(', ') %}
Below is the my desired output:
devices = 192.168.56.14:1234,192.168.56.13:1234,192.168.56.10:1234
But when i am running the ansible playbook, it is throwing the error as below:
"AnsibleError: teme templating string: Encountered unknown tag 'do'. Jinja was looking for th: 'endfor' or 'else'
Any help would be appreciated..
| Try below code:
{% set port = '1234' %}
{% set server_ip = [] %}
{% for ip in host_ip %}
{{ server_ip.append( ip+":"+port ) }}
{% endfor %}
{{ server_ip|join(',') }}
You ll get:
192.168.56.14:1234,192.168.56.13:1234,192.168.56.10:1234
| Ansible | 49,619,445 | 44 |
I'm working on automating a task which needs to append the latest version of software to a file. I don't want it to do this multiple times for the same version.
It looks at the following example file:
var software releases = new Array(
"4.3.0",
"4.4.0",
"4.5.0",
"4.7.0",
"4.8.0",
"4.11.0",
"4.12.1",
"4.14.0",
"4.15.0",
"4.16.0",
);
the defaults main.yml would pass in something like
VERSION: 4.16.2
code
- name: register version check
shell: cat /root/versions.js | grep -q {{VERSION}}
register: current_version
- debug: msg="The registered variable output is {{ current_version.rc }}"
- name: append to versions.js
lineinfile:
dest: /root/versions.js
regexp: '^\);'
insertbefore: '^#\);'
line: " \"{{VERSION}}\",\n);"
owner: root
state: present
when: current_version.rc == 1
problem: the debug message is evaluating current_version.rc and showing me boolean values based on the grep commands output, but I can't re-use this in the when conditional to determine if the task should be run.
Edit: the output:
PLAY [localhost] **************************************************************
GATHERING FACTS ***************************************************************
ok: [localhost]
TASK: [test | register version check] *****************************************
failed: [localhost] => {"changed": true, "cmd": "cat /root/versions.js | grep -q 3.19.2", "delta": "0:00:00.003570", "end": "2015-12-17 00:24:49.729078", "rc": 1, "start": "2015-12-17 00:24:49.725508", "warnings": []}
FATAL: all hosts have already failed -- aborting
PLAY RECAP ********************************************************************
to retry, use: --limit @/root/site.retry
localhost : ok=1 changed=0 unreachable=0 failed=1
| As nikobelia pointed out in the comments, grep returns an exit code of 1 when it doesn't match any lines. Ansible then interprets this (actually any status code other than 0 from a shell/command task) as an error and so promptly fails.
You can tell Ansible to ignore the response code from the shell/command task by using ignore_errors. Although with grep this will ignore actual errors (given by a return code of 2) so instead you might want to use failed_when like this:
- name: register version check
shell: cat /root/versions.js | grep -q {{VERSION}}
register: current_version
failed_when: current_version.rc == 2
| Ansible | 34,340,562 | 44 |
Is it possible to call a role multiple times in a loop like this:
vars:
my_array:
- foo
- bar
- baz
roles:
- role: foobar
with_items: my_array
How can we do this?
| Now supported as of Ansible 2.3.0:
- name: myrole
with_items:
- "aone"
- "atwo"
include_role:
name: myrole
vars:
thing: "{{ item }}"
| Ansible | 33,415,992 | 44 |
is it possible to append a variable list to a static list in ansible?
I can define the whole list as a variable:
my_list:
- 1
- 2
- 3
and then use it in a playbook as
something: {{my_list}}
But I cannot seem to find how to do this (pseudo code):
list_to_append:
- 3
- 4
and then in the playbook:
something:
- 1
- 2
- {{append: list_to_append}}
If that is in fact impossible, what would you suggest for my use case?
I have a list of items in a parameter, but some of them are optional and should be modifiable using variables.
In other words: I have default values + optional values that could or could not be added via variables.
The optional values are not known in advance, I could add 1, 2 or 100 of them, so they are not static.
I basically have a default static list ++ a configurable variable list to append.
edit:
I found this but it's only for with_items and I need it in a normal parameter:
with_flattened:
- "{{list1}}"
- "{{list2}}"
| If you really want to append to content, you will need to use the set_fact module. But if you just want to use the merged lists it is as easy as this:
{{ list1 + list2 }}
With set_fact it would look like this:
- set_fact:
list_merged: "{{ list1 + list2 }}"
NOTE: If you need to do additional operations on the concatenated lists be sure to group them like so:
- set_fact:
list_merged: "{{ (list1 + list2) | ... }}"
| Ansible | 31,045,106 | 44 |
I'd like to see the actual git commit changes in the ansible vault file.
Is there an easy way how to achieve this?
| You can do this very neatly, so that the normal git tools like git log and git diff can see inside the vaulted files, using a custom git diff driver and .gitattributes.
Make sure that your vault password is in .vault_password and that that file is not committed - you should also add it to .gitignore.
Add a .gitattributes file that matches any files in your repository that are encrypted with ansible-vault and give them the attribute diff=ansible-vault. For example, I have:
env_vars/production.yml diff=ansible-vault merge=binary
env_vars/staging.yml diff=ansible-vault merge=binary
You can also use wildcarded patterns - the first element of each line, the pattern, follows the same rules as .gitignore files. The merge=binary option tells git not to attempt to do a three-way merge of these files.
Then you have to set the diff driver for files with attribute diff=ansible-vault to ansible-vault view:
git config --global diff.ansible-vault.textconv "ansible-vault view"
And that should be it - when git is calculating diffs of the files your pattern matches, it'll decrypt them first.
| Ansible | 29,937,195 | 44 |
Based on extra vars parameter I Need to write variable value in ansible playbook
ansible-playbook playbook.yml -e "param1=value1 param2=value2 param3=value3"
If only param1 passed
myvariable: 'param1'
If only param1,param2 passed
myvariable: 'param1,param2'
If param1,param2,param3 are passed then variable value will be
myvariable: 'param1,param2,param3'
When I try to create variable dynamically through template then my playbook always takes previous variable value. But inside dest=roles/myrole/vars/main.yml its writing correct value.
What I make a try here
- hosts: local
user: roop
gather_facts: yes
connection: local
tasks:
- template: src=roles/myrole/templates/myvar.j2 dest=roles/myrole/vars/main.yml
- debug: var=myvariable
roles:
- { role: myrole }
So inside myrole directory I have created template and vars
- roles
- myrole
- vars/main.yml
- templates/myvar.j2
templates/myvar.j2
{% if param1 is defined and param2 is defined and param3 is defined %}
myvariable: 'param1,param2,param3'
{% elif param1 is defined and param2 is defined %}
myvariable: 'param1,param2'
{% elif param1 is defined %}
myvariable: 'param1'
{% else %}
myvariable: 'default-param'
{% endif %}
As I know if only two condition then I can do this using inline expression like below
{{ 'param1,param2' if param1 is defined and param2 is defined else 'default-param' }}
<do something> if <something is true> else <do something else>
Is it possible if - elif - else in inline expression like above. Or any other way to assign value dynamically in ansible playbook?
| I am sure there is a smarter way for doing what you want but this should work:
- name : Test var
hosts : all
gather_facts : no
vars:
myvariable : false
tasks:
- name: param1
set_fact:
myvariable: "{{param1}}"
when: param1 is defined
- name: param2
set_fact:
myvariable: "{{ param2 if not myvariable else myvariable + ',' + param2 }}"
when: param2 is defined
- name: param3
set_fact:
myvariable: "{{ param3 if not myvariable else myvariable + ',' + param3 }}"
when: param3 is defined
- name: default
set_fact:
myvariable: "default"
when: not myvariable
- debug:
var=myvariable
Hope that helps. I am not sure if you can construct variables dynamically and do this in an iterator. But you could also write a small python code or any other language and plug it into ansible
| Ansible | 23,264,226 | 44 |
If any Ansible task fails, there is error output, the playbook will display it newlines escaped '\n'. For tracebacks, spanning multiple lines, this make it very hard to read.
Is there a way to make ansible-playbook to display unescaped error output from shell, pip, gitand other similar tasks?
| Add stdout_callback=debug and stderr_callback=debug in the defaults section of your ansible.cfg file.
[defaults]
(...)
stdout_callback=debug
stderr_callback=debug
This is supported by ansible > 2.0
| Ansible | 37,171,966 | 43 |
I am running an ansible-playbook which have many tasks listed. All of them use to get run one by one, but I want to pause the playbook after a particular tasks to asks the user if he wants to continue running the rest of the tasks or exit. I have seen the pause module of ansible but couldn't see any example which asks users for yes or no which in turn continue or exit the ansible-playbook accordingly.
| The pause module actually does exactly that. But it does not give you an option to answer yes or no. Instead it expects the user to press Ctrl+C and then a for abort. To continue the user simply needs to press Enter.
Since this is not perfectly obvious to the user you can describe it in the prompt parameter.
- name: Exterminate mankind
pause:
prompt: Please confirm you want to exterminate mankind! Press return to continue. Press Ctrl+c and then "a" to abort
| Ansible | 34,290,525 | 43 |
I've created an Ansible playbook that creates a cloud instance and then installs some programs on the instance. I want to run this playbook multiple times (without using a bash script). Is it possible to use a loop to loop over those two tasks together (I.E. One loop for two tasks?). All I've been able to find so far is one loop for each individual task
| An update:
In 2.0 you are able to use with_ loops and task includes (but not playbook includes), this adds the ability to loop over the set of tasks in one shot. There are a couple of things that you need to keep in mind, a included task that has it’s own with_ loop will overwrite the value of the special item variable. So if you want access to both the include’s item and the current task’s item you should use set_fact to create a alias to the outer one.:
- include_tasks: test.yml
with_items:
- 1
- 2
- 3
in test.yml:
- set_fact: outer_loop="{{item}}"
- debug: msg="outer item={{outer_loop}} inner item={{item}}"
with_items:
- a
- b
- c
Source: Ansible Docs
| Ansible | 30,785,281 | 43 |
Is it possible to set a fact containing a list in Ansible using set_fact? What's the correct syntax for it?
| Yes, this is possible. As mentioned in another answer, you can set an array using double quotes, like so:
- name: set foo fact to a list
set_fact:
foo: "[ 'one', 'two', 'three' ]"
However, I thought I'd create another answer to indicate that it's also possible to add to an existing array, like so:
- name: add items to foo list fact
set_fact:
foo: "{{ foo + ['four'] }}"
Combining these and adding debugging as a playbook (which I'm calling facts.yml) like so:
---
- name: test playbook
gather_facts: false
hosts: localhost
tasks:
- name: set foo fact to an array
set_fact:
foo: "[ 'one', 'two', 'three' ]"
- debug:
var: foo
- name: add items to foo array fact
set_fact:
foo: "{{ foo + [ 'four' ] }}"
- debug:
var: foo
Produces (via ansible-playbook facts.yml) the following:
PLAY [test playbook] ********************************************************
TASK: [set foo fact to an array] ********************************************
ok: [localhost]
TASK: [debug var=foo] *******************************************************
ok: [localhost] => {
"foo": [
"one",
"two",
"three"
]
}
TASK: [add items to foo array fact] *****************************************
ok: [localhost]
TASK: [debug var=foo] *******************************************************
ok: [localhost] => {
"foo": [
"one",
"two",
"three",
"four"
]
}
PLAY RECAP ******************************************************************
localhost : ok=4 changed=0 unreachable=0 failed=0
| Ansible | 23,507,589 | 43 |
I'm just trying to write a basic playbook, and keep getting the error below.
Tried a tonne of things but still can't get it right. I know it must be a syntax thing but no idea where.
This is the code I have:
---
# This playbook runs a basic DF command.
- hosts: nagios
#remote_user: root
tasks:
- name: find disk space available.
command: df -hPT
This is the error I get:
> ERROR! 'command' is not a valid attribute for a Play
>
> The error appears to have been in '/root/playbooks/df.yml': line 4,
> column 3, but may be elsewhere in the file depending on the exact
> syntax problem.
>
> The offending line appears to be:
>
>
> - hosts: nagios
^ here
Ansible ver: 2.4.2.0
It's driving me insane. I've looked at some axamples from the Ansible docs, and it looks the same.
No idea...
Anyone know?
| The problem is that without the indentation of the command line, the command directive is part of the overall play, and not the task block.i.e. the command should be part of the task block.
---
# This playbook runs a basic DF command.
- hosts: nagios
#remote_user: root
tasks:
- name: find disk space available.
command: df -hPT
| Ansible | 49,246,837 | 42 |
Sometimes, ansible doesn't do what you want. And increasing verbosity doesn't help. For example, I'm now trying to start coturn server, which comes with init script on systemd OS (Debian Jessie). Ansible considers it running, but it's not. How do I look into what's happening under the hood? Which commands are executed, and what output/exit code?
| Debugging modules
The most basic way is to run ansible/ansible-playbook with an increased verbosity level by adding -vvv to the execution line.
The most thorough way for the modules written in Python (Linux/Unix) is to run ansible/ansible-playbook with an environment variable ANSIBLE_KEEP_REMOTE_FILES set to 1 (on the control machine).
It causes Ansible to leave the exact copy of the Python scripts it executed (either successfully or not) on the target machine.
The path to the scripts is printed in the Ansible log and for regular tasks they are stored under the SSH user's home directory: ~/.ansible/tmp/.
The exact logic is embedded in the scripts and depends on each module. Some are using Python with standard or external libraries, some are calling external commands.
Debugging playbooks
Similarly to debugging modules increasing verbosity level with -vvv parameter causes more data to be printed to the Ansible log
Since Ansible 2.1 a Playbook Debugger allows to debug interactively failed tasks: check, modify the data; re-run the task.
Debugging connections
Adding -vvvv parameter to the ansible/ansible-playbook call causes the log to include the debugging information for the connections.
| Ansible | 42,417,079 | 42 |
I noticed Ansible removes the temporary script using a semi-colon to separate the bash commands.
Here is an example command:
EXEC ssh -C -tt -v -o ControlMaster=auto -o ControlPersist=60s -o
ControlPath="/Users/devuser/.ansible/cp/ansible-ssh-%h-%p-%r" -o
KbdInteractiveAuthentication=no -o
PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey
-o PasswordAuthentication=no -o ConnectTimeout=10 build /bin/sh -c
'LANG=en_US.UTF-8 LC_CTYPE=en_US.UTF-8 /usr/bin/python
/home/ec2-user/.ansible/tmp/ansible-tmp-1430847489.81-75617096172775/docker;
rm -rf
/home/ec2-user/.ansible/tmp/ansible-tmp-1430847489.81-75617096172775/
>/dev/null 2>&1'
Is there a way to tell ansible to replace the semi-colon with a double ampersand or to tell it to save the script or output the contents when running ansible-playbook?
I'm trying to debug an error in this script and right now the only thing that appears is this:
failed: [build] => {"changed": false, "failed": true}
msg: ConnectionError(ProtocolError('Connection aborted.', error(2, 'No such file or directory')),)
| I found the environment variable -
export ANSIBLE_KEEP_REMOTE_FILES=1
Set this, then re-run ansible-playbook, and then ssh and cd over to ~/.ansible/tmp/ to find the files.
| Ansible | 30,060,164 | 42 |
I have two ansible tasks as follows
tasks:
- shell: ifconfig -a | sed 's/[ \t].*//;/^\(lo\|\)$/d'
register: var1
- debug: var=var1
- shell: ethtool -i {{ item }} | grep bus-info | cut -b 16-22
with_items: var1.stdout_lines
register: var2
- debug: var=var2
which is used to get a list of interfaces in a machine (linux) and get the bus address for each. I have one more task as follows in tha same playbook
- name: Binding the interfaces
shell: echo {{ item.item }}
with_flattened: var2.results
register: var3
which I expect to iterate over value from var2 and then print the bus numbers.
var2.results is as follows
"var2": {
"changed": true,
"msg": "All items completed",
"results": [
{
"changed": true,
"cmd": "ethtool -i br0: | grep bus-info | cut -b 16-22",
"delta": "0:00:00.005778",
"end": "2015-04-14 20:29:47.122203",
"invocation": {
"module_args": "ethtool -i br0: | grep bus-info | cut -b 16-22",
"module_name": "shell"
},
"item": "br0:",
"rc": 0,
"start": "2015-04-14 20:29:47.116425",
"stderr": "",
"stdout": "",
"warnings": []
},
{
"changed": true,
"cmd": "ethtool -i enp13s0: | grep bus-info | cut -b 16-22",
"delta": "0:00:00.005862",
"end": "2015-04-14 20:29:47.359749",
"invocation": {
"module_args": "ethtool -i enp13s0: | grep bus-info | cut -b 16-22",
"module_name": "shell"
},
"item": "enp13s0:",
"rc": 0,
"start": "2015-04-14 20:29:47.353887",
"stderr": "",
"stdout": "0d:00.0",
"warnings": []
},
{
"changed": true,
"cmd": "ethtool -i enp14s0: | grep bus-info | cut -b 16-22",
"delta": "0:00:00.005805",
"end": "2015-04-14 20:29:47.576674",
"invocation": {
"module_args": "ethtool -i enp14s0: | grep bus-info | cut -b 16-22",
"module_name": "shell"
},
"item": "enp14s0:",
"rc": 0,
"start": "2015-04-14 20:29:47.570869",
"stderr": "",
"stdout": "0e:00.0",
"warnings": []
},
{
"changed": true,
"cmd": "ethtool -i enp15s0: | grep bus-info | cut -b 16-22",
"delta": "0:00:00.005873",
"end": "2015-04-14 20:29:47.875058",
"invocation": {
"module_args": "ethtool -i enp15s0: | grep bus-info | cut -b 16-22",
"module_name": "shell"
},
"item": "enp15s0:",
"rc": 0,
"start": "2015-04-14 20:29:47.869185",
"stderr": "",
"stdout": "0f:00.0",
"warnings": []
},
{
"changed": true,
"cmd": "ethtool -i enp5s0f1: | grep bus-info | cut -b 16-22",
"delta": "0:00:00.005870",
"end": "2015-04-14 20:29:48.112027",
"invocation": {
"module_args": "ethtool -i enp5s0f1: | grep bus-info | cut -b 16-22",
"module_name": "shell"
},
"item": "enp5s0f1:",
"rc": 0,
"start": "2015-04-14 20:29:48.106157",
"stderr": "",
"stdout": "05:00.1",
"warnings": []
},
{
"changed": true,
"cmd": "ethtool -i enp5s0f2: | grep bus-info | cut -b 16-22",
"delta": "0:00:00.005863",
"end": "2015-04-14 20:29:48.355733",
"invocation": {
"module_args": "ethtool -i enp5s0f2: | grep bus-info | cut -b 16-22",
"module_name": "shell"
},
"item": "enp5s0f2:",
"rc": 0,
"start": "2015-04-14 20:29:48.349870",
"stderr": "",
"stdout": "05:00.2",
"warnings": []
},
{
"changed": true,
"cmd": "ethtool -i enp5s0f3: | grep bus-info | cut -b 16-22",
"delta": "0:00:00.005829",
"end": "2015-04-14 20:29:48.591244",
"invocation": {
"module_args": "ethtool -i enp5s0f3: | grep bus-info | cut -b 16-22",
"module_name": "shell"
},
"item": "enp5s0f3:",
"rc": 0,
"start": "2015-04-14 20:29:48.585415",
"stderr": "",
"stdout": "05:00.3",
"warnings": []
},
{
"changed": true,
"cmd": "ethtool -i enp9s0f0: | grep bus-info | cut -b 16-22",
"delta": "0:00:00.005943",
"end": "2015-04-14 20:29:48.910992",
"invocation": {
"module_args": "ethtool -i enp9s0f0: | grep bus-info | cut -b 16-22",
"module_name": "shell"
},
"item": "enp9s0f0:",
"rc": 0,
"start": "2015-04-14 20:29:48.905049",
"stderr": "",
"stdout": "09:00.0",
"warnings": []
},
{
"changed": true,
"cmd": "ethtool -i enp9s0f1: | grep bus-info | cut -b 16-22",
"delta": "0:00:00.005863",
"end": "2015-04-14 20:29:49.143706",
"invocation": {
"module_args": "ethtool -i enp9s0f1: | grep bus-info | cut -b 16-22",
"module_name": "shell"
},
"item": "enp9s0f1:",
"rc": 0,
"start": "2015-04-14 20:29:49.137843",
"stderr": "",
"stdout": "09:00.1",
"warnings": []
},
{
"changed": true,
"cmd": "ethtool -i lo: | grep bus-info | cut -b 16-22",
"delta": "0:00:00.005856",
"end": "2015-04-14 20:29:49.386044",
"invocation": {
"module_args": "ethtool -i lo: | grep bus-info | cut -b 16-22",
"module_name": "shell"
},
"item": "lo:",
"rc": 0,
"start": "2015-04-14 20:29:49.380188",
"stderr": "Cannot get driver information: Operation not supported",
"stdout": "",
"warnings": []
},
{
"changed": true,
"cmd": "ethtool -i virbr0: | grep bus-info | cut -b 16-22",
"delta": "0:00:00.005859",
"end": "2015-04-14 20:29:49.632356",
"invocation": {
"module_args": "ethtool -i virbr0: | grep bus-info | cut -b 16-22",
"module_name": "shell"
},
"item": "virbr0:",
"rc": 0,
"start": "2015-04-14 20:29:49.626497",
"stderr": "",
"stdout": "",
"warnings": []
},
{
"changed": true,
"cmd": "ethtool -i virbr0-nic: | grep bus-info | cut -b 16-22",
"delta": "0:00:00.024850",
"end": "2015-04-14 20:29:49.901539",
"invocation": {
"module_args": "ethtool -i virbr0-nic: | grep bus-info | cut -b 16-22",
"module_name": "shell"
},
"item": "virbr0-nic:",
"rc": 0,
"start": "2015-04-14 20:29:49.876689",
"stderr": "",
"stdout": "",
"warnings": []
}
]
My objective is to get the value of stdout in each item above for example ("stdout": "09:00.0") . I tried giving something like
- name: Binding the interfaces
shell: echo {{ item.item.stdout}}
with_flattened: var2.results
# with_indexed_items: var2.results
register: var3
But this is not giving the bus values in stdout correctly. Appreciate help in listing the variable of variable value in task as given below when the second variable is and indexed list. I am trying to avoid direct index numbering such as item[0] because the number of interfaces are dynamic and direct indexing may result in unexpected outcomes.
Thanks
| Is this what you're looking for:
Variables registered for a task that has with_items have different format, they contain results for all items.
- hosts: localhost
tags: s21
gather_facts: no
vars:
images:
- foo
- bar
tasks:
- shell: "echo result-{{item}}"
register: "r"
with_items: "{{images}}"
- debug: var=r
- debug: msg="item.item={{item.item}}, item.stdout={{item.stdout}}, item.changed={{item.changed}}"
with_items: "{{r.results}}"
- debug: msg="Gets printed only if this item changed - {{item}}"
when: "{{item.changed == true}}"
with_items: "{{r.results}}"
Source: Register variables in with_items loop in Ansible playbook
| Ansible | 29,635,627 | 42 |
I have an ansible variable passed in on the command line as such:
ansible-playbook -e environment=staging ansible/make_server.yml
I want to load in some variables in my role dependeing on the value of environment. I have tried a lot of different methods such as:
- include_vars: staging_vars.yml
when: environment | staging
and
- include_vars: staging_vars.yml
when: "{{environment}} == "staging"
and
- include_vars: staging_vars.yml
when: "{{environment}} | match('staging')"
but nothing seems to work. How do I do this?
Details:
I am using ansible 1.7.2
| Be careful with a variable called environment, it can cause problems because Ansible uses it internally. I can't remember if it's in the docs, but here's a mailing list thread:
https://groups.google.com/forum/#!topic/ansible-project/fP0hX2Za4I0
We use a variable called stage.
It looks like you'll end up with a bunch of these in a row:
- include_vars: testing_vars.yml
when: stage == "testing"
- include_vars: staging_vars.yml
when: stage == "staging"
- include_vars: production_vars.yml
when: stage == "production"
But you could also just include your environment:
- include_vars: "{{ stage }}_vars.yml"
Or, use the vars_files on a playbook level:
vars_files:
- vars/{{ stage }}_vars.yml
| Ansible | 27,335,204 | 42 |
I would like to be able to prompt for my super secure password variable if it is not already in the environment variables. (I'm thinking that I might not want to put the definition into .bash_profile or one of the other spots.)
This is not working. It always prompts me.
vars:
THISUSER: "{{ lookup('env','LOGNAME') }}"
SSHPWD: "{{ lookup('env','MY_PWD') }}"
vars_prompt:
- name: "release_version"
prompt: "Product release version"
default: "1.0"
when: SSHPWD == null
NOTE: I'm on a Mac, but I'd like for any solutions to be platform-independent.
| According to the replies from the devs and a quick test I've done with the latest version, the vars_prompt is run before "GATHERING FACTS". This means that the env var SSHPWD is always null at the time of your check with when.
Unfortunately it seems there is no way of allowing the vars_prompt statement at task level.
Michael DeHaan's reasoning for this is that allowing prompts at the task-level would open up the doors to roles asking a lot of questions. This would make using Ansible Galaxy roles which do this difficult:
There's been a decided emphasis in automation in Ansible and asking questions at task level is not something we really want to do.
However, you can still ask vars_prompt questions at play level and use those variables throughout tasks. You just can't ask questions in roles.
And really, that's what I would like to enforce -- if a lot of Galaxy roles start asking questions, I can see that being annoying :)
| Ansible | 25,466,675 | 42 |
I'm working on a project where having swap memory on my servers is a needed to avoid some python long running processes to go out of memory and realized for the first time that my ubuntu vagrant boxes and AWS ubuntu instances didn't already have one set up.
In https://github.com/ansible/ansible/issues/5241 a possible built in solution was discussed but never implemented, so I'm guessing this should be a pretty common task to automatize.
How would you set up a file based swap memory with ansible in an idempotent way? What modules or variables does ansible provide help with this setup (like ansible_swaptotal_mb variable) ?
| This is my current solution:
- name: Create swap file
command: dd if=/dev/zero of={{ swap_file_path }} bs=1024 count={{ swap_file_size_mb }}k
creates="{{ swap_file_path }}"
tags:
- swap.file.create
- name: Change swap file permissions
file: path="{{ swap_file_path }}"
owner=root
group=root
mode=0600
tags:
- swap.file.permissions
- name: "Check swap file type"
command: file {{ swap_file_path }}
register: swapfile
tags:
- swap.file.mkswap
- name: Make swap file
command: "sudo mkswap {{ swap_file_path }}"
when: swapfile.stdout.find('swap file') == -1
tags:
- swap.file.mkswap
- name: Write swap entry in fstab
mount: name=none
src={{ swap_file_path }}
fstype=swap
opts=sw
passno=0
dump=0
state=present
tags:
- swap.fstab
- name: Mount swap
command: "swapon {{ swap_file_path }}"
when: ansible_swaptotal_mb < 1
tags:
- swap.file.swapon
| Ansible | 24,765,930 | 42 |
Having an inventory file like:
[my_hosts]
my_host ansible_ssh_host=123.123.123.123
my_host2 ansible_ssh_host=234.234.234.234
I want to gather some debug information in my templates.
How do I acces the alias variable in a playbook/template?
I.e.:
debug: msg=Myhost is {{ ansible_host_alias }}
# Myhost is my_host
# Myhost is myhost2
I tried to gather facts using ansible -m setup my_host . The variables ansible_hostname , HOSTNAME and HOST contain the machine's hostname, i.e. echo $HOSTNAME which differs from my ansible alias.
| The variable I was searching for is a built in feature: inventory_hostname
Ansible documentation about inventory_hostname and inventory_hostname_short is found from chapter Magic Variables, and How To Access Information About Other Hosts.
Original question: https://groups.google.com/forum/#!topic/ansible-project/Oa5YXjHecIw
| Ansible | 22,983,484 | 42 |
I have a simple file at /etc/foo.txt. The file contains the following:
#bar
I have the following ansible playbook task to uncomment the line above:
- name: test lineinfile
lineinfile: backup=yes state=present dest=/etc/foo.txt
regexp='^#bar'
line='bar'
When I first run ansible-playbook, the line gets uncommented and the /etc/foo.txt now contains the following:
bar
However, if I run ansible-playbook again, I get the following:
bar
bar
If I run it yet again, then the /etc/foo.txt file will look like this:
bar
bar
bar
How to avoid this duplications of lines? I just want to uncomment the '#bar' and be done with it.
| You need to add backrefs=yes if you don't want to change your regular expression.
- name: test lineinfile
lineinfile: backup=yes state=present dest=/etc/foo.txt
regexp='^#bar' backrefs=yes
line='bar'
This changes the behavior of lineinfile from:
find
if found
replace line found
else
add line
to:
find
if found
replace line found
In other words, this makes operation idempotent.
| Ansible | 19,390,600 | 42 |
I have this Ansible as a String:
FUBAR={{ PREFIX }}_{{ CNAME }}{{ VERSION }}
I want to replace all . in the concatenated string with '', like this:
FUBAR={{ {{ PREFIX }}_{{ CNAME }}{{ VERSION }} | replace('.','') }}
I get the message:
expected token ':', got '}'
Could anyone give me a suggestion what's wrong?
| FUBAR="{{ ( PREFIX + '_' + CNAME + VERSION ) | replace('.','') }}"
Resolving a few problems:
too many '{{}}'s
need quotes around the whole expression
the replace will only act on the last element unless it is all surrounded by '()'s
| Ansible | 53,671,030 | 41 |
In the best practices page, there is an example that uses hosts.yml for hosts files:
In the docs, however, I can only find the INI syntax for writing hosts files.
What is the syntax for the inventory files in YAML?
| Yes.
It's been deprecated in version 0.6 in 2012 and reintroduced in a commit first included in version 2.1 in 2016.
The example file on GitHub contains the guidelines and examples:
Comments begin with the '#' character
Blank lines are ignored
Top level entries are assumed to be groups
Hosts must be specified in a group's hosts: and they must be a key (: terminated)
groups can have children, hosts and vars keys
Anything defined under a hosts is assumed to be a var
You can enter hostnames or ip addresses
A hostname/ip can be a member of multiple groups
Ex 1: Ungrouped hosts, put in 'ungrouped' group
ungrouped:
hosts:
green.example.com:
ansible_ssh_host: 191.168.100.32
blue.example.com:
192.168.100.1:
192.168.100.10:
Ex 2: A collection of hosts belonging to the 'webservers' group
webservers:
hosts:
alpha.example.org:
beta.example.org:
192.168.1.100:
192.168.1.110:
Ex 3: You can create hosts using ranges and add children groups and vars to a group.
The child group can define anything you would normally add to a group
testing:
hosts:
www[001:006].example.com:
vars:
testing1: value1
children:
webservers:
hosts:
beta.example.org:
| Ansible | 41,094,864 | 41 |
I'm trying to run ansible role on multiple servers, but i get an error:
fatal: [192.168.0.10]: UNREACHABLE! => {"changed": false, "msg":
"Failed to connect to the host via ssh.", "unreachable": true}
My /etc/ansible/hosts file looks like this:
192.168.0.10 ansible_sudo_pass='passphrase' ansible_ssh_user=user
192.168.0.11 ansible_sudo_pass='passphrase' ansible_ssh_user=user
192.168.0.12 ansible_sudo_pass='passphrase' ansible_ssh_user=user
I have no idea what's going on - everything looks fine - I can login via SSH, but ansible ping returns the same error.
The log from verbose execution:
<192.168.0.10> ESTABLISH SSH CONNECTION FOR USER: user <192.168.0.10>
SSH: EXEC ssh -C -vvv -o ControlMaster=auto -o ControlPersist=60s -o
KbdInteractiveAuthentication=no -o
PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey
-o PasswordAuthentication=no -o User=user -o ConnectTimeout=10 -o ControlPath=/root/.ansible/cp/ansible-ssh-%h-%p-%r 192.168.0.10
'/bin/sh -c '"'"'( umask 22 && mkdir -p "echo
$HOME/.ansible/tmp/ansible-tmp-1463151813.31-156630225033829" &&
echo "echo
$HOME/.ansible/tmp/ansible-tmp-1463151813.31-156630225033829"
)'"'"''
Can you help me somehow? If I have to use ansible in local mode (-c local), then it's useless.
I've tried to delete ansible_sudo_pass and ansible_ssh_user, but it did'nt help.
| You need to change the ansible_ssh_pass as well or ssh key, for example I am using this in my inventory file:
192.168.33.100 ansible_ssh_pass=vagrant ansible_ssh_user=vagrant
After that I can connect to the remote host:
ansible all -i tests -m ping
With the following result:
192.168.33.100 | SUCCESS => {
"changed": false,
"ping": "pong"
}
Hope that help you.
EDIT: ansible_ssh_pass & ansible_ssh_user don't work in the latest version of Ansible. It has changed to ansible_user & ansible_pass
| Ansible | 37,213,551 | 41 |
As far as i know, ansible has an option named --list-hosts for listing hosts. Is there any option for listing host groups? Or any other way to come through?
| You can simply inspect the groups variable using the debug module:
ansible localhost -m debug -a 'var=groups.keys()'
The above is using groups.keys() to get just the list of groups. You could drop the .keys() part to see group membership as well:
ansible localhost -m debug -a 'var=groups'
| Ansible | 33,363,023 | 41 |
As a safeguard against using an outdated playbook, I'd like to ensure that I have an updated copy of the git checkout before Ansible is allowed to modify anything on the servers.
This is how I've attempted to do it. This action is located in a file included by all play books:
- name: Ensure local git repository is up-to-date
local_action: git pull
register: command_result
failed_when: "'Updating' in command_result.stdout"
The problem is that this command is run once for each node Ansible connects to, instead of only once for each playbook run. How can I avoid that?
| Updated
When I fist wrote my answer (2014-02-27), Ansible had no built-in support for running a task only once per playbook, not once per affected host that the playbook was run on. However, as tlo writes, support for this was introduced with run_once: true in Ansible version 1.7.0 (released on 2014-08-06). With this feature, the example task definition from the question should be changed to
- name: Ensure local git repository is up-to-date
local_action: git pull
run_once: true
register: command_result
failed_when: "'Updating' in command_result.stdout"
to accomplish what is asked for.
Original Answer
[The following answer was my suggested solution for the particular problem of making sure that the local git branch is updated before Ansible runs the tasks of a playbook.]
I wrote the following Ansible callback plugin that will avoid playbook execution if the current git branch is out of sync (is either behind or has diverged) with the remote branch. To use it, place the following code in a file like callback_plugins/require_updated_git_branch.py in your top-level Ansible playbook directory:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import subprocess
import sys
from ansible.callbacks import display, banner
class CallbackModule(object):
"""Makes Ansible require that the current git branch is up to date.
"""
env_var_name = 'IGNORE_OUTDATED_GIT_BRANCH'
msg = 'OUTDATED GIT BRANCH: Your git branch is out of sync with the ' \
'remote branch. Please update your branch (git pull) before ' \
'continuing, or skip this test by setting the environment ' \
'variable {0}=yes.'.format(env_var_name)
out_of_sync_re = re.compile(r'Your branch (is behind|and .* have diverged)',
re.MULTILINE)
def __init__(self, *args, **kwargs):
if os.getenv(self.env_var_name, 'no') == 'yes':
self.disabled = True
def playbook_on_start(self):
subprocess.call(['git', 'fetch'])
if self.out_of_sync_re.search(subprocess.check_output([
'git', 'status', '--untracked-files=no'])):
display(banner(self.msg), color='bright purple')
sys.exit(1)
For example, when the local branch is behind the remote branch, the command ansible-playbook site.yml halts early with the following output:
__________________________________________________________
/ OUTDATED GIT BRANCH: Your git branch is out of sync with \
| the remote branch. Please update your branch (git pull) |
| before continuing, or skip this test by setting the |
\ environment variable IGNORE_OUTDATED_GIT_BRANCH=yes. /
----------------------------------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
And, as the cow suggests, to turn off this check you can run the command like:
$ IGNORE_OUTDATED_GIT_BRANCH=yes ansible-playbook site.yml
This solution does not solve the general problem of avoiding to run any Ansible task more than once regardless of the number of hosts involved, but it ensures that outdated playbooks are not executed, and it handles the concern that you mentioned regarding my alias-based suggestion.
| Ansible | 22,070,232 | 41 |
I have this task in Ansible:
- name: Install mongodb
yum:
name:
- "mongodb-org-{{ mongodb_version }}"
- "mongodb-org-server-{{ mongodb_version }}"
- "mongodb-org-mongos-{{ mongodb_version }}"
- "mongodb-org-shell-{{ mongodb_version }}"
- "mongodb-org-tools-{{ mongodb_version }}"
state: present
notify: Restart mongodb
Is there a way I can indicate the version without having to use a loop like this? What is a more "elegant" way of writing this?
- name: Install mongodb
yum:
name: "{{ item }}-{{ mongodb_version }}"
state: present
loop:
- mongodb-org-server
- mongodb-org-mongos
- mongodb-org-shell
- mongodb-org-tools
notify: Restart mongodb
| To my surprise I didn't find the simplest solution in all the answers, so here it is. Referring to the question title Installing multiple packages in Ansible this is (using the yum module):
- name: Install MongoDB
yum:
name:
- mongodb-org-server
- mongodb-org-mongos
- mongodb-org-shell
- mongodb-org-tools
state: latest
update_cache: true
Or with the apt module:
- name: Install MongoDB
apt:
pkg:
- mongodb-org-server
- mongodb-org-mongos
- mongodb-org-shell
- mongodb-org-tools
state: latest
update_cache: true
Both modules support inline lists!
The second part of your question is how to integrate specific version numbers into the package lists. No problem - simply remove the state: latest (since using specific version numbers together with state: latest would raise errors) and add the version numbers to the package names using a preceding = like this:
- name: Install MongoDB
yum:
name:
- mongodb-org-server=1:3.6.3-0centos1.1
- mongodb-org-mongos=1:3.6.3-0centos1.1
- mongodb-org-shell=1:3.6.3-0centos1.1
- mongodb-org-tools=1:3.6.3-0centos1.1
update_cache: true
You could also optimize further and template the version numbers. In this case don't forget to add quotation marks :)
| Ansible | 54,944,080 | 40 |
Goal:
Create multiple directories if they don't exist.
Don't change permissions of existing folder
Current playbook:
- name: stat directories if they exist
stat:
path: "{{ item }}"
loop:
- /data/directory
- /data/another
register: myvar
- debug:
msg: "{{ myvar.results }}"
- name: create directory if they don't exist
file:
path: "{{ item.invocation.module_args.path }}"
state: directory
owner: root
group: root
mode: 0775
loop: "{{ stat.results }}"
when: not myvar.results.stat.exists
The when statement is wrong.
I looked at the example provided. But this only works for a single folder.
| Using Ansible modules, you don't need to check if something exist or not, you just describe the desired state, so:
- name: create directory if they don't exist
file:
path: "{{ item }}"
state: directory
owner: root
group: root
mode: 0775
loop:
- /data/directory
- /data/another
| Ansible | 42,186,301 | 40 |
I've got a dictionary with different names like
vars:
images:
- foo
- bar
Now, I want to checkout repositories and afterwards build docker images only when the source has changed.
Since getting the source and building the image is the same for all items except the name I created the tasks with with_items: images
and try to register the result with:
register: "{{ item }}"
and also tried
register: "src_{{ item }}"
Then I tried the following condition
when: "{{ item }}|changed"
and
when: "{{ src_item }}|changed"
This always results in fatal: [piggy] => |changed expects a dictionary
So how can I properly save the results of the operations in variable names based on the list I iterate over?
Update: I would like to have something like that:
- hosts: all
vars:
images:
- foo
- bar
tasks:
- name: get src
git:
repo: [email protected]/repo.git
dest: /tmp/repo
register: "{{ item }}_src"
with_items: images
- name: build image
shell: "docker build -t repo ."
args:
chdir: /tmp/repo
when: "{{ item }}_src"|changed
register: "{{ item }}_image"
with_items: images
- name: push image
shell: "docker push repo"
when: "{{ item }}_image"|changed
with_items: images
|
So how can I properly save the results of the operations in variable names based on the list I iterate over?
You don't need to. Variables registered for a task that has with_items have different format, they contain results for all items.
- hosts: localhost
gather_facts: no
vars:
images:
- foo
- bar
tasks:
- shell: "echo result-{{item}}"
register: "r"
with_items: "{{ images }}"
- debug: var=r
- debug: msg="item.item={{item.item}}, item.stdout={{item.stdout}}, item.changed={{item.changed}}"
with_items: "{{r.results}}"
- debug: msg="Gets printed only if this item changed - {{item}}"
when: item.changed == true
with_items: "{{r.results}}"
| Ansible | 29,512,443 | 40 |
How do I use the when statement based on the standard output of register: result? If standard output exists I want somecommand to run if no standard output exists I want someothercommand to run.
- hosts: myhosts
tasks:
- name: echo hello
command: echo hello
register: result
- command: somecommand {{ result.stdout }}
when: result|success
- command: someothercommand
when: result|failed
| Try checking to see it if equals a blank string or not?
- hosts: myhosts
tasks:
- name: echo hello
command: echo hello
register: result
- command: somecommand {{ result.stdout }}
when: result.stdout != ""
- command: someothercommand
when: result.stdout == ""
| Ansible | 26,142,343 | 40 |
I am using Ansible's shell module to find a particular string and store it in a variable. But if grep did not find anything I am getting an error.
Example:
- name: Get the http_status
shell: grep "http_status=" /var/httpd.txt
register: cmdln
check_mode: no
When I run this Ansible playbook if http_status string is not there, playbook is stopped. I am not getting stderr.
How can I make Ansible run without interruption even if the string is not found?
| grep by design returns code 1 if the given string was not found. Ansible by design stops execution if the return code is different from 0. Your system is working properly.
To prevent Ansible from stopping playbook execution on this error, you can:
add ignore_errors: yes parameter to the task
use failed_when: parameter with a proper condition
Because grep returns error code 2 for exceptions, the second method seems more appropriate, so:
- name: Get the http_status
shell: grep "http_status=" /var/httpd.txt
register: cmdln
failed_when: "cmdln.rc == 2"
check_mode: no
You might also consider adding changed_when: false so that the task won't be reported as "changed" every single time.
All options are described in the Error Handling In Playbooks document.
| Ansible | 41,010,378 | 39 |
I am trying to start filebeat (or for that matter any other process which will run continuously on demand) process on multiple hosts using ansible. I don't want ansible to wait till the process keeps on running. I want ansible to fire and forget and come out and keep remote process running in back ground.
I've tried using below options:
---
- hosts: filebeat
tasks:
- name: start filebeat
option a) command: filebeat -c filebeat.yml &
option b) command: nohup filebeat -c filebeat.yml &
option c) shell: filebeat -c filebeat.yml &
async: 0 //Tried without as well. If its > 0 then it only waits for that much of time and terminates the filebeat process on remote host and comes out.
poll: 0
| Simplified answer from link I mentioned in the comment:
---
- hosts: centos-target
gather_facts: no
tasks:
- shell: "(cd /; python -mSimpleHTTPServer >/dev/null 2>&1 &)"
async: 10
poll: 0
Note subshell parentheses.
Update: actually, you should be fine without async, just don't forget to redirect stdout:
- name: start simple http server in background
shell: cd /tmp/www; nohup python -mSimpleHTTPServer </dev/null >/dev/null 2>&1 &
| Ansible | 39,347,379 | 39 |
I am trying to shrink several chunks of similar code which looks like:
- ... multiple things is going here
register: list_register
- name: Generating list
set_fact: my_list="{{ list_register.results | map(attribute='ansible_facts.list_item') | list }}"
# the same code repeats...
The only difference between them is list name instead of my_list.
In fact, I want to do this:
set_fact:
"{{ some var }}" : "{{ some value }}"
I came across this post but didn't find any answer here.
Is it possible to do so or is there any workaround?
| take a look at this sample playbook:
---
- hosts: localhost
vars:
iter:
- key: abc
val: xyz
- key: efg
val: uvw
tasks:
- set_fact: {"{{ item.key }}":"{{ item.val }}"}
with_items: "{{iter}}"
- debug: msg="key={{item.key}}, hostvar={{hostvars['localhost'][item.key]}}"
with_items: "{{iter}}"
| Ansible | 38,143,647 | 39 |
Some ansible commands produce json output that's barely readable for humans. It distracts people when they need to check if playbook executed correctly and causes confusion.
Example commands are shell and replace - they generate a lot of useless noise. How can I prevent this? Simple ok | changed | failed is enough. I don't need the whole JSON.
| Use no_log: true on those tasks where you want to suppress all further output.
- shell: whatever
no_log: true
I believe the only mention of this feature is within the FAQ.
Example playbook:
- hosts:
- localhost
gather_facts: no
vars:
test_list:
- a
- b
- c
tasks:
- name: Test with output
shell: echo "{{ item }}"
with_items: test_list
- name: Test w/o output
shell: echo "{{ item }}"
no_log: true
with_items: test_list
Example output:
TASK: [Test with output] ******************************************************
changed: [localhost] => (item=a)
changed: [localhost] => (item=b)
changed: [localhost] => (item=c)
TASK: [Test w/o output] *******************************************************
changed: [localhost]
changed: [localhost]
changed: [localhost]
| Ansible | 32,475,881 | 39 |
Imagine this ansible playbook:
- name: debug foo
debug: msg=foo
tags:
- foo
- name: debug bar
debug: msg=bar
tags:
- bar
- name: debug baz
debug: msg=baz
tags:
- foo
- bar
How can I run only the debug baz task? I want to say only run tasks which are tagged with foo AND bar. Is that possible?
I tried this, but it will run all 3 tasks:
ansible-playbook foo.yml -t foo,bar
| Ansible tags use "or" not "and" as a comparison. Your solution to create yet another tag is the appropriate one.
| Ansible | 30,036,126 | 39 |
I have a custom SSH config file that I typically use as follows
ssh -F ~/.ssh/client_1_config amazon-server-01
Is it possible to assign Ansible to use this config for certain groups? It already has the keys and ports and users all set up. I have this sort of config for multiple clients, and would like to keep the config separate if possible.
| You can set ssh arguments globally in the ansible.cfg:
[ssh_connection]
ssh_args = -F ~/.ssh/client_1_config
Via behavioral inventory parameters you can set it per host or group
amazon-server-01 ansible_ssh_common_args=~/.ssh/client_1_config
| Ansible | 28,553,307 | 39 |
I'm trying to include a file only if it exists. This allows for custom "tasks/roles" between existing "tasks/roles" if needed by the user of my role. I found this:
- include: ...
when: condition
But the Ansible docs state that:
"All the tasks get evaluated, but the conditional is applied to each and every task" - http://docs.ansible.com/playbooks_conditionals.html#applying-when-to-roles-and-includes
So
- stat: path=/home/user/optional/file.yml
register: optional_file
- include: /home/user/optional/file.yml
when: optional_file.stat.exists
Will fail if the file being included doesn't exist. I guess there might be another mechanism for allowing a user to add tasks to an existing recipe. I can't let the user to add a role after mine, because they wouldn't have control of the order: their role will be executed after mine.
| The with_first_found conditional can accomplish this without a stat or local_action. This conditional will go through a list of local files and execute the task with item set to the path of the first file that exists.
Including skip: true on the with_first_found options will prevent it from failing if the file does not exist.
Example:
- hosts: localhost
connection: local
gather_facts: false
tasks:
- include: "{{ item }}"
with_first_found:
- files:
- /home/user/optional/file.yml
skip: true
| Ansible | 28,119,521 | 39 |
Is there exists some way to print on console gathered facts ?
I mean gatering facts using setup module. I would like to print gathered facts. Is it possible ? If it is possible can someone show example?
| Use setup module as ad-hoc command:
ansible myhost -m setup
| Ansible | 49,677,591 | 38 |
I am a newbie to ansible and I am using a very simple playbook to issue sudo apt-get update and sudo apt-get upgrade on a couple of servers.
This is the playbook I am using:
---
- name: Update Servers
hosts: my-servers
become: yes
become_user: root
tasks:
- name: update packages
apt: update_cache=yes
- name: upgrade packages
apt: upgrade=dist
and this is an extract from my ~/.ansible/inventory/hosts file:
[my-servers]
san-francisco ansible_host=san-francisco ansible_ssh_user=user ansible_become_pass=<my_sudo_password_for_user_on_san-francisco>
san-diego ansible_host=san-diego ansible_ssh_user=user ansible_become_pass=<my_sudo_password_for_user_on_san-diego>
This is what I get if I launch the playbook:
$ ansible-playbook update-servers-playbook.yml
PLAY [Update Servers] **********************************************************
TASK [setup] *******************************************************************
ok: [san-francisco]
ok: [san-diego]
TASK [update packages] *********************************************************
ok: [san-francisco]
ok: [san-diego]
TASK [upgrade packages] ********************************************************
ok: [san-francisco]
ok: [san-diego]
PLAY RECAP *********************************************************************
san-francisco : ok=3 changed=0 unreachable=0 failed=0
san-diego : ok=3 changed=0 unreachable=0 failed=0
What is bothering me is the fact that I have the password for my user user stored in plaintext in my ~/.ansible/inventory/hosts file.
I have read about vaults, I have also read about the best practices for variables and vaults but I do not understand how to apply this to my very minimal use case.
I also tried to use lookups. While in general they also work in the inventory file, and I am able to do something like this:
[my-servers]
san-francisco ansible_host=san-francisco ansible_ssh_user=user ansible_become_pass="{{ lookup('env', 'ANSIBLE_BECOME_PASSWORD_SAN_FRANCISCO') }}"
where this case the password would be stored in an environment variable called ANSIBLE_BECOME_PASSWORD_SAN_FRANCISCO; there is no way to look up variables in vaults as far as I know.
So, how could I organize my file such that I would be able to lookup up my passwords from somewhere and have them safely stored?
| You need to create some vaulted variable files and then either include them in your playbooks or on the command line.
If you change your inventory file to use a variable for the become pass this variable can be vaulted:
[my-servers]
san-francisco ansible_host=san-francisco ansible_ssh_user=user ansible_become_pass='{{ sanfrancisco_become_pass }}'
san-diego ansible_host=san-diego ansible_ssh_user=user ansible_become_pass='{{ sandiego_become_pass }}'
Then use ansible-vault create vaulted_vars.yml to create a vaulted file with the following contents:
sanfrancisco_become_pass: <my_sudo_password_for_user_on_san-francisco>
sandiego_become_pass : <my_sudo_password_for_user_on_san-diego>
Then either include the vaulted file as extra vars like this:
ansible-playbook -i ~/.ansible/inventory/hosts playbook.yml --ask-vault-pass -e@~/.ansible/inventory/vault_vars
Or include the vars file in your playbook with an include_vars task:
- name : include vaulted variables
include_vars: ~/.ansible/inventory/vault_vars
| Ansible | 37,297,249 | 38 |
I have a task:
- name: uploads docker configuration file
template:
src: 'docker.systemd.j2'
dest: '/etc/systemd/system/docker.service'
notify:
- daemon reload
- restart docker
in Ansible playbook's documentation, there is a sentence:
Notify handlers are always run in the order written.
So, it is expected, that daemon reload will be ran before restart docker, but in logs, i have:
TASK [swarm/docker : uploads docker configuration file] ************************
…
NOTIFIED HANDLER daemon reload
NOTIFIED HANDLER restart docker
…
RUNNING HANDLER [swarm/docker : restart docker] ********************************
…
RUNNING HANDLER [swarm/docker : daemon reload] *********************************
…
There are no more "NOTIFIED HANDLER" in logs. Can anyone explain, what i'm doing wrong? :(
| I think you may have “restart docker” listed before “daemon reload” in your handlers file.
That part of the ansible documentation is a bit misleading. It means that handlers are executed in the order they are written in the handlers file, not the order they are notified.
This is little more clear in the documentation:
Handlers always run in the order they are defined, not in the order listed in the notify-statement. This is also the case for handlers using listen.
| Ansible | 35,130,051 | 38 |
I'm looking for the way how to make Ansible to analyze playbooks for required and mandatory variables before run playbook's execution like:
- name: create remote app directory hierarchy
file:
path: "/opt/{{ app_name | required }}/"
state: directory
owner: "{{ app_user | required }}"
group: "{{ app_user_group | required }}"
...
and rise error message if variable is undefined, like:
please set "app_name" variable before run (file XXX/main.yml:99)
| As Arbab Nazar mentioned, you can use {{ variable | mandatory }} (see Forcing variables to be defined) inside Ansible task.
But I think it looks nicer to add this as first task, it checks is app_name, app_user and app_user_group exist:
- name: 'Check mandatory variables are defined'
assert:
that:
- app_name is defined
- app_user is defined
- app_user_group is defined
| Ansible | 45,013,306 | 37 |
I am trying to convert a string that has been parsed using a regex into a number so I can multiply it, using Jinja2. This file is a template to be used within an ansible script.
I have a series of items which all take the form of <word><number> such as aaa01, aaa141, bbb05.
The idea was to parse the word and number(ignoring leading zeros) and use them later in the template.
I wanted to manipulate the number by multiplication and use it. Below is what I have done so far
```
{% macro get_host_number() -%}
{{ item | regex_replace('^\D*[0]?(\d*)$', '\\1') }}
{%- endmacro %}
{% macro get_host_name() -%}
{{ item | regex_replace('^(\D*)\d*$', '\\1') }}
{%- endmacro %}
{% macro get_host_range(name, number) -%}
{% if name=='aaa' %}
{{ ((number*5)+100) | int | abs }}
{% elif name=='bbb' %}
{{ ((number*5)+200) | int | abs }}
{% else %}
{{ ((number*5)+300) | int | abs }}
{% endif %}
{%- endmacro %}
{% set number = get_host_number() %}
{% set name = get_host_name() %}
{% set value = get_host_range(name, number) %}
Name: {{ name }}
Number: {{ number }}
Type: {{ value }}
With the above template I am getting an error coercing to Unicode: need string or buffer, int found which i think is telling me it cannot convert the string to integer, however i do not understand why. I have seen examples doing this and working.
| You need to cast string to int after regex'ing number:
{% set number = get_host_number() | int %}
And then there is no need in | int inside get_host_range macro.
| Ansible | 39,938,323 | 37 |
Consider if I want to check something quickly. Something that doesn't really need connecting to a host (to check how ansible itself works, like, including of handlers or something). Or localhost will do. I'd probably give up on this, but man page says:
-i PATH, --inventory=PATH
The PATH to the inventory, which defaults to /etc/ansible/hosts. Alternatively, you can use a comma-separated
list of hosts or a single host with a trailing comma host,.
And when I run ansible-playbook without inventory, it says:
[WARNING]: provided hosts list is empty, only localhost is available
Is there an easy way to run playbook against no host, or probably localhost?
| Prerequisites. You need to have ssh server running on the host (ssh localhost should let you in).
Then if you want to use password authentication (do note the trailing comma):
$ ansible-playbook playbook.yml -i localhost, -k
In this case you also need sshpass.
In case of public key authentication:
$ ansible-playbook playbook.yml -i localhost,
And the test playbook, to get you started:
- hosts: all
tasks:
- debug: msg=test
You need to have a comma in the localhost, option argument, because otherwise it would be treated as a path to an inventory. The inventory plugin responsible for parsing the value can be found here.
| Ansible | 38,187,557 | 37 |
I have an ansible file (my_file.yml) that looks something like this:
---
- name: The name
hosts: all
tasks:
- include:my_tasks.yml
vars:
my_var: "{{ my_var }}"
my_tasks.yml looks like this:
- name: Install Curl
apt: pkg=curl state=installed
- name: My task
command: bash -c "curl -sSL http://x.com/file-{{ my_var }} > /tmp/file.deb"
I'd like to pass my_var as a command-line argument to ansible so I do like this:
ansible-playbook my_file.yml --extra-vars "my_var=1.2.3"
But I end up with the following error:
... Failed to template {{ my_var }}: Failed to template {{ my_var }}: recursive loop detected in template string: {{ my_var }}
If I the vars in my_file.yml to look like this:
- include:my_tasks.yml
vars:
my_var: "1.2.3"
it works! I've also tried changing the variable name to something that is not equal to my_var, for example:
- include:my_tasks.yml
vars:
my_var: "{{ my_var0 }}"
but then I end up with an error. It seems to me that the variable is not expanded and instead the string "{{ my_var }}" or {{ my_var0 }} is passed to my_tasks.yml. How do I solve this?
| Faced the same issue in my project. It turns out that the variable name in the playbook and the task have to be different.
---
- name: The name
hosts: all
vars:
my_var_play: "I need to send this value to the task"
some_other_var: "This is directly accessible in task"
tasks:
- include:my_tasks.yml
vars:
my_var: "{{ my_var_play }}"
Also on a sidenote, all the variables in the playbook is accessible in the task. Just use {{ some_other_var }} in task and it should work fine.
| Ansible | 32,232,221 | 37 |
I have written a simple playbook to print java process ID and other information of that PID
[root@server thebigone]# cat check_java_pid.yaml
---
- hosts: all
gather_facts: no
tasks:
- name: Check PID of existing Java process
shell: "ps -ef | grep [j]ava"
register: java_status
- debug: var=java_status.stdout
And when I am calling this with ansible-playbook check_java_pid.yamlit's working fine.
Now I am trying to call the above playbook from another one but only for a specific host. So I have written the 2nd playbook as below
[root@server thebigone]# cat instance_restart.yaml
---
- hosts: instance_1
gather_facts: no
tasks:
- include: check_java_pid.yaml
But while doing ansible-playbook instance_restart.yaml, I am getting below errors
ERROR! no action detected in task. This often indicates a misspelled
module name, or incorrect module path.
The error appears to have been in
'/home/root/ansible/thebigone/check_java_pid.yaml': line 2, column 3, but
may be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
---
- hosts: all
^ here
The error appears to have been in
'/home/root/ansible/thebigone/check_java_pid.yaml': line 2, column 3,
but may be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
---
- hosts: all
^ here
Its saying syntax error but there isn't one really AFAIK as I have executed Playbook check_java_pid.yaml without any issues.
Requesting your help on understanding this issue.
| Here you have examples in official documentation.
https://docs.ansible.com/ansible/2.4/playbooks_reuse_includes.html
I had same error as yours after applying the aproved answer. I resolved problem by creating master playbook like this:
---
- import_playbook: master-okd.yml
- import_playbook: infra-okd.yml
- import_playbook: compute-okd.yml
| Ansible | 43,609,132 | 36 |
I'm trying to run a python script from an ansible script. I would think this would be an easy thing to do, but I can't figure it out. I've got a project structure like this:
playbook-folder
roles
stagecode
files
mypythonscript.py
tasks
main.yml
release.yml
I'm trying to run mypythonscript.py within a task in main.yml (which is a role used in release.yml). Here's the task:
- name: run my script!
command: ./roles/stagecode/files/mypythonscript.py
args:
chdir: /dir/to/be/run/in
delegate_to: 127.0.0.1
run_once: true
I've also tried ../files/mypythonscript.py. I thought the path for ansible would be relative to the playbook, but I guess not?
I also tried debugging to figure out where I am in the middle of the script, but no luck there either.
- name: figure out where we are
stat: path=.
delegate_to: 127.0.0.1
run_once: true
register: righthere
- name: print where we are
debug: msg="{{righthere.stat.path}}"
delegate_to: 127.0.0.1
run_once: true
That just prints out ".". So helpful ...
| try to use script directive, it works for me
my main.yml
---
- name: execute install script
script: get-pip.py
and get-pip.py file should be in files in the same role
| Ansible | 35,139,711 | 36 |
I am looking for something that would be similar to with_items: but that would get the list of items from a file instead of having to include it in the playbook file.
How can I do this in ansible?
| Latest Ansible recommends loop instead of with_something. It can be used in combination with lookup and splitlines(), as Ikar Pohorský pointed out:
- debug: msg="{{item}}"
loop: "{{ lookup('file', 'files/branches.txt').splitlines() }}"
files/branches.txt should be relative to the playbook
| Ansible | 33,541,870 | 36 |
I have an object like that
objs:
- { key1: value1, key2: [value2, value3] }
- { key1: value4, key2: [value5, value6] }
And I'd like to create the following files
value1/value2
value1/value3
value4/value5
value4/value6
but I have no idea how to do a double loop using with_items
| Take a look at with_subelements in Ansible's docs for loops.
You need to create directories:
Iterate though objs and create files:
Here is an example:
---
- hosts: localhost
gather_facts: no
vars:
objs:
- { key1: value1, key2: [ value2, value3] }
- { key1: value4, key2: [ value5, value6] }
tasks:
- name: create directories
file: path="{{ item.key1 }}" state=directory
with_items:
objs
- name: create files
file: path="{{ item.0.key1 }}/{{ item.1 }}" state=touch
with_subelements:
- objs
- key2
An output is pretty self explanatory, the second loop iterates through the values the way you need it:
PLAY [localhost] **************************************************************
TASK: [create files] **********************************************************
changed: [localhost] => (item={'key2': ['value2', 'value3'], 'key1': 'value1'})
changed: [localhost] => (item={'key2': ['value5', 'value6'], 'key1': 'value4'})
TASK: [create files] **********************************************************
changed: [localhost] => (item=({'key1': 'value1'}, 'value2'))
changed: [localhost] => (item=({'key1': 'value1'}, 'value3'))
changed: [localhost] => (item=({'key1': 'value4'}, 'value5'))
changed: [localhost] => (item=({'key1': 'value4'}, 'value6'))
PLAY RECAP ********************************************************************
localhost : ok=2 changed=2 unreachable=0 failed=0
| Ansible | 31,566,568 | 36 |
I am trying to install Bundler on my VPS using Ansible.
I already have rbenv set up and the global ruby is 2.1.0.
If I SSH as root into the server and run gem install bundler, it installs perfectly.
I have tried the following three ways of using Ansible to install the Bundler gem and all three produce no errors, but when I SSH in and run gem list, Bundler is nowhere to be seen.
Attempt 1:
---
- name: Install Bundler
shell: gem install bundler
Attempt 2:
---
- name: Install Bundler
shell: gem install bundler
Attempt 3:
---
- name: Install Bundler
gem: name=bundler
state=latest
I have also tried the last attempt with user_install=yes and also with user_install=no and neither make any difference.
Any ideas how I can get it to install Bundler correctly via Ansible?
I've been working on this for a little while now and I have 1 ruby version installed: 2.1.0 and ahve found that the shims directory for rbenv does not contain a shim for bundle.
Should a shim for bundle be in there? I'm just getting confused as to why capistrano cannot find the bundle command as it's listed when I run sudo gem list but NOT when I run gem list?
root@weepingangel:/usr/local/rbenv/shims# echo $PATH
/usr/local/rbenv/shims:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
root@weepingangel:/usr/local/rbenv/shims# gem environment
RubyGems Environment:
- RUBYGEMS VERSION: 2.2.0
- RUBY VERSION: 2.1.0 (2013-12-25 patchlevel 0) [x86_64-linux]
- INSTALLATION DIRECTORY: /usr/local/rbenv/versions/2.1.0/lib/ruby/gems/2.1.0
- RUBY EXECUTABLE: /usr/local/rbenv/versions/2.1.0/bin/ruby
- EXECUTABLE DIRECTORY: /usr/local/rbenv/versions/2.1.0/bin
- SPEC CACHE DIRECTORY: /root/.gem/specs
- RUBYGEMS PLATFORMS:
- ruby
- x86_64-linux
- GEM PATHS:
- /usr/local/rbenv/versions/2.1.0/lib/ruby/gems/2.1.0
- /root/.gem/ruby/2.1.0
- GEM CONFIGURATION:
- :update_sources => true
- :verbose => true
- :backtrace => false
- :bulk_threshold => 1000
- :sources => ["http://gems.rubyforge.org", "http://gems.github.com"]
- "gem" => "--no-ri --no-rdoc"
- REMOTE SOURCES:
- http://gems.rubyforge.org
- http://gems.github.com
- SHELL PATH:
- /usr/local/rbenv/versions/2.1.0/bin
- /usr/local/rbenv/libexec
- /usr/local/rbenv/shims
- /usr/local/sbin
- /usr/local/bin
- /usr/sbin
- /usr/bin
- /sbin
- /bin
- /usr/games
Any ideas?
So, I think the two main problems I have:
Why is bundler only visible when I run sudo gem list?
My deploy is saying:
INFO [18d5838c] Running /usr/bin/env bundle install --binstubs
/var/rails_apps/neiltonge/shared/bin --path
/var/rails_apps/neiltonge/shared/bundle --without development test
--deployment --quiet on 188.226.159.96 DEBUG [18d5838c] Command: cd /var/rails_apps/neiltonge/releases/20140301205432 && ( PATH=$PATH
/usr/bin/env bundle install --binstubs
/var/rails_apps/neiltonge/shared/bin --path
/var/rails_apps/neiltonge/shared/bundle --without development test
--deployment --quiet ) DEBUG [18d5838c] /usr/bin/env: bundle: No such file or directory
and this is my $PATH:
/usr/local/rbenv/shims:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
Why can't bundle be located?
| The problem is that, when running gem install bundler via ansible, you're not initializing rbenv properly, since rbenv init is run in .bashrc or .bash_profile. So the gem command used is the system one, not the one installed as a rbenv shim. So whenever you install a gem, it is installed system-wide, not in your rbenv environment.
To have rbenv initialized properly, you must execute bash itself and explicitely state that it's a login shell, so it reads it's initialization files :
ansible your_host -m command -a 'bash -lc "gem install bundler"' -u your_rbenv_user
Leave the -u your_rbenv_user part if you really want to do this as root.
If the above command works, you can easily turn it into a playbook action :
- name: Install Bundler
become_user: your_rbenv_user
command: bash -lc "gem install bundler"
It's cumbersome, but it's the only way I found so far.
| Ansible | 22,115,936 | 36 |
In some ansible roles (e.g. roles/my-role/) I've got quite some big default variables files (defaults/main.yml). I'd like to split the main.yml into several smaller files. Is it possible to do that?
I've tried creating the files defaults/1.yml and defaults/2.yml, but they aren't loaded by ansible.
| The feature I'm describing below has been available since Ansible 2.6, but got a bugfix in v2.6.2 and another (minor) one in v2.7.
To see a solution for older versions, see Paul's answer.
defaults/main/
Instead of creating defaults/main.yml, create a directory — defaults/main/ — and place all YAML files in there.
defaults/main.yml → defaults/main/*.yml
Ansible will load any *.yml file inside that directory, so you can name your files like roles/my-role/defaults/main/{1,2}.yml.
Furthermore, it's even possible to create sub-directories like roles/my-role/defaults/main/subdir_1/foo.yml.
Note, the old file — defaults/main.yml — must not exist. See this Github comment.
vars/main/
By the way, the above solution also works for vars/:
vars/main.yml → vars/main/*.yml
further details
The feature has been introduced in v2.6 — git commit, Pull Request, main Github issue.
There have been two bugfixes:
v2.7 fix: git commit, Pull Request — backported to v2.6.2: commit, Pull Request
v2.7 fix: git commit, Pull Request, bug discussion
| Ansible | 51,818,264 | 35 |
What is the difference between using with_items vs loops in ansilbe?
| Update: The most recent Documentation lists down the differences as below
The with_ keywords rely on Lookup Plugins - even items is a lookup.
The loop keyword is equivalent to with_list, and is the best choice for simple loops.
The loop keyword will not accept a string as input, see Ensuring list input for loop: query vs. lookup.
Generally speaking, any use of with_* covered in Migrating from with_X to loop can be updated to use loop.
Be careful when changing with_items to loop, as with_items performed implicit single-level flattening. You may need to use
flatten(1) with loop to match the exact outcome.
Old answer
As per the docs,
Before 2.5 Ansible mainly used the with_ keywords to create loops, the loop keyword is basically analogous to with_list.
So basically they are pretty much the same, only the newer version uses loop in its syntax. And as of version 2.7.12 both work as expected but using the loop keyword is encouraged for future compatibility.
| Ansible | 50,456,997 | 35 |
I want to pip install with --upgrade, using Ansible.
What's the syntax?
| - name: install the package, force upgrade
pip:
name: <your package name>
state: latest
Or with:
- name: install the package, force reinstall to the latest version
pip:
name: <your package name>
state: forcereinstall
| Ansible | 47,632,103 | 35 |
I have a problem to find a working solution to loop over my inventory.
I start my playbook with linking a intentory file:
ansible-playbook -i inventory/dev.yml playbook.yml
My playbook looks like this:
---
- hosts: localhost
tasks:
- name: Create VM if enviro == true
include_role:
name: local_vm_creator
when: enviro == 'dev'
So when loading the playbook the variable enviro is read from host_vars and sets the when condition to dev. The inventory file dev.yml looks like this:
[local_vm]
192.168.99.100
192.168.99.101
192.168.99.102
[local_vm_manager_1]
192.168.99.103
[local_vm_manager_2]
192.168.99.104
[local-all:children]
local_vm
local_vm_manager_1
local_vm_manager_2
My main.yml in my role local_vm_creator looks like this:
---
- name: Create test host
local_action: shell docker-machine create -d virtualbox {{ item }}
with_items:
- node-1
- node-2
- node-3
- node-4
- node-5
- debug: msg="host is {{item}}"
with_items: groups['local_vm']
And the problem is that i can't get the listed servers from the dev.yml inventory file.
it just returns:
ok: [localhost] => (item=groups['local_vm']) => {
"item": "groups['local_vm']",
"msg": "host is groups['local_vm']" }
| If the only problem is with_items loop, replace it with:
with_items: "{{ groups['local_vm'] }}"
and you are good to go. Bare variables are not supported in with_ any more.
| Ansible | 43,140,086 | 35 |
Is there a way to render Ansible template into the fact? I tried to find a solution but it looks like temp file is the the only way.
| I think you might be just looking for the template lookup plugin:
- set_fact:
rendered_template: "{{ lookup('template', './template.j2') }}"
Usage example:
template.j2
Hello {{ value_for_template }}
playbook.yml
---
- hosts: localhost
gather_facts: no
connection: local
vars:
value_for_template: world
tasks:
- debug:
var: rendered_template
vars:
rendered_template: "{{ lookup('template', './template.j2') }}"
The result:
TASK [debug] *******************************************************************
ok: [localhost] => {
"rendered_template": "Hello world\n"
}
| Ansible | 41,424,999 | 35 |
I found this blockinfile issue, where a user suggested adding a number after the "|" in the "block: |" line, but gives a syntax error. Basically, I want to use blockinfile module to add a block of lines in a file, but I want the block to be indented 6 spaces in the file. Here's the task
- name: Added a block of lines in the file
blockinfile:
dest: /path/some_file.yml
insertafter: 'authc:'
block: |
line0
line1
line2
line3
line4
I expect
authc:
line0
line1
line2
line3
line4
but get
authc:
line0
line1
line2
line3
line4
Adding spaces in the beginning of the lines does not do it. How can I accomplish this?
| You can use a YAML feature called "Block Indentation Indicator":
- name: Added a block of lines in the file
blockinfile:
dest: /path/some_file.yml
insertafter: 'authc:'
block: |2
line0
line1
line2
line3
line4
It's all about the 2 after the |
References:
https://groups.google.com/forum/#!topic/ansible-project/mmXvhTh6Omo
How do I break a string in YAML over multiple lines?
http://www.yaml.org/spec/1.2/spec.html#id2793979
Update:
As Dave correctly pointed out, this does not work anymore in the current version 2.14.2 of ansible :( I'd suggest using the comment workaround from the next answer
| Ansible | 39,731,999 | 35 |
Is it possible to check if a string exists in a file using Ansible?
I want to check is a user has access to a server. This can be done on the server using cat /etc/passwd | grep username, but I want Ansible to stop if the user is not there.
I have tried to use the lineinfile but can't seem to get it to return.
- name: find
lineinfile:
dest: /etc/passwd
regexp: [user]
state: present
line: "user"
The code above adds user to the file if he is not there. All I want to do is check. I don't want to modify the file in any way, is this possible.
| It's a tricky one. the lineinfile module is specifically intended for modifying the content of a file, but you can use it for a validation check as well.
- name: find
lineinfile:
dest: /etc/passwd
line: "user"
check_mode: yes
register: presence
failed_when: presence.changed
check_mode ensures it never updates the file.
register saves the variable as noted.
failed_when allows you to set the failure condition i.e. by adding the user because it was not found in the file.
There are multiple iterations of this that you can use based on what you want the behavior to be. lineinfile docs particular related to state and regexp should allow you to determine whether or not presence or absence is failure etc, or you can do the not presence.changed etc.
| Ansible | 38,461,920 | 35 |
I configured nginx installation and configuration (together with setup SSL certificates for https site) via ansible. SSL certificates are under passphrases.
I want to write ansilbe task which is restarting nginx. The problem is the following.
Normally, nginx with https site inside asks for PEM pass phrase during restart. Ansible doesn't ask for that passphrase during execution of playbook.
There is solution with storing decrypted cert and key in some private directory. But I don't really want to leave my cert and key somewhere unencrypted.
How to pass password to nginx (or to openssl) during restart via ansible? Perfect scenario is following:
Ansible is asking for SSL password (via vars_promt). Another option is to use ansible vault.
Ansible is restarting nginx, and when nginx is asking for PEM pass phrase, ansible is passing password to nginx.
Is it possible?
| Nginx has ssl_password_file parameter.
Specifies a file with passphrases for secret keys where each passphrase is specified on a separate line. Passphrases are tried in turn when loading the key.
Example:
http {
ssl_password_file /etc/keys/global.pass;
...
server {
server_name www1.example.com;
ssl_certificate_key /etc/keys/first.key;
}
server {
server_name www2.example.com;
# named pipe can also be used instead of a file
ssl_password_file /etc/keys/fifo;
ssl_certificate_key /etc/keys/second.key;
}
}
What you could do is keep that ssl_password_file in ansible-vault, copy it over, restart nginx and then if successful delete it.
I have no first-hand experience if it'll actually work or what other side-effects this might have(for example manual service nginx restart will probably fail), but it seems like a logical approach to me.
| Ansible | 33,084,347 | 35 |
By looking around here as well as the internet in general, I have found Bouncy Castle. I want to use Bouncy Castle (or some other freely available utility) to generate a SHA-256 Hash of a String in Java. Looking at their documentation I can't seem to find any good examples of what I want to do. Can anybody here help me out?
| To hash a string, use the built-in MessageDigest class:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;
import java.math.BigInteger;
public class CryptoHash {
public static void main(String[] args) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
String text = "Text to hash, cryptographically.";
// Change this to UTF-16 if needed
md.update(text.getBytes(StandardCharsets.UTF_8));
byte[] digest = md.digest();
String hex = String.format("%064x", new BigInteger(1, digest));
System.out.println(hex);
}
}
In the snippet above, digest contains the hashed string and hex contains a hexadecimal ASCII string with left zero padding.
| Bouncy Castle | 3,103,652 | 120 |
What is the best method of performing an scp transfer via the Java programming language? It seems I may be able to perform this via JSSE, JSch or the bouncy castle java libraries. None of these solutions seem to have an easy answer.
| I ended up using Jsch- it was pretty straightforward, and seemed to scale up pretty well (I was grabbing a few thousand files every few minutes).
| Bouncy Castle | 199,624 | 86 |
I need to export private key from Windows store. What should I do if the key is marked as non-exportable? I know that it is possible, program jailbreak can export this key.
To export key I use Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair() that exports key from (RSACryptoServiceProvider)cryptoProv.ExportParameters(true). Exported key I use in Org.BouncyCastle.Cms.CmsSignedDataGenerator for CMS signature.
I need solution for .Net, but any solution will be useful. Thank you.
| You're right, no API at all that I'm aware to export PrivateKey marked as non-exportable.
But if you patch (in memory) normal APIs, you can use the normal way to export :)
There is a new version of mimikatz that also support CNG Export (Windows Vista / 7 / 2008 ...)
download (and launch with administrative privileges) : http://blog.gentilkiwi.com/mimikatz (trunk version or last version)
Run it and enter the following commands in its prompt:
privilege::debug (unless you already have it or target only CryptoApi)
crypto::patchcng (nt 6) and/or crypto::patchcapi (nt 5 & 6)
crypto::exportCertificates and/or crypto::exportCertificates CERT_SYSTEM_STORE_LOCAL_MACHINE
The exported .pfx files are password protected with the password "mimikatz"
| Bouncy Castle | 3,914,882 | 69 |
I searched around, but I didn't find a clear example.
I want to create a self-signed (self-)trusted certificate programmatically (C#), following these steps:
STEP 1:
Create a root CA certificate on the fly and add it to the certificate store in the folder "Trusted Root certification Authorities"
I want to do exactly what this command line tool does:
makecert.exe -sk RootCA -sky signature -pe -n CN=MY_CA -r -sr LocalMachine -ss Root MyCA.cer
STEP 2:
Create a certificate based on the previously created root CA certificate and put it in the certificate store, in the folder "Personal"
I want to do exactly what this command line tool does:
makecert.exe -sk server -sky exchange -pe -n CN=127.0.0.1 -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyCertificate.cer
I want to obtain this:
I did that (see the following code - STEP 1). How do I make STEP 2? Target machines is Windows XP/7.
I tried both a pure .NET approach and Bouncy Castle library.
// STEP 1
mycerRoot = generateRootCertV1("MY_CA"); // Tried also generateRootCertV2(BouncyCastle)
addCertToStore(mycerRoot, StoreName.Root, StoreLocation.LocalMachine);
// STEP 2
mycer = generateCert("127.0.0.1", mycerRoot); // ?????? <-- Something like that How to implement generateCert??
addCertToStore(mycer, StoreName.My, StoreLocation.LocalMachine);
public static Org.BouncyCastle.X509.X509Certificate generateRootCertV2(string certName)
{
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
X509Name CN = new X509Name("CN=" + certName);
RsaKeyPairGenerator keypairgen = new RsaKeyPairGenerator();
keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));
AsymmetricCipherKeyPair keypair = keypairgen.GenerateKeyPair();
certGen.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
certGen.SetIssuerDN(CN);
certGen.SetNotAfter(DateTime.MaxValue);
certGen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
certGen.SetSubjectDN(CN);
certGen.SetPublicKey(keypair.Public);
certGen.SetSignatureAlgorithm("MD5WithRSA");
Org.BouncyCastle.X509.X509Certificate newCert = certGen.Generate(keypair.Private);
return newCert;
}
public static X509Certificate2 GenerateRootCertV1(string HostNameOrIP_or_CertName)
{
X509Certificate2 cert = null;
try
{
using (CryptContext ctx = new CryptContext())
{
ctx.Open();
cert = ctx.CreateSelfSignedCertificate(
new SelfSignedCertProperties
{
IsPrivateKeyExportable = true,
KeyBitLength = 4096,
Name = new X500DistinguishedName("cn=" + HostNameOrIP_or_CertName),
ValidFrom = DateTime.Today.AddDays(-1),
ValidTo = DateTime.Today.AddYears(20),
});
}
}
catch (Exception ex)
{
}
return cert;
}
public static bool addCertToStore(X509Certificate2 cert, StoreName st, StoreLocation sl)
{
bool bRet = false;
try
{
X509Store store = new X509Store(st, sl);
store.Open(OpenFlags.ReadWrite);
if (cert != null)
{
byte[] pfx = cert.Export(X509ContentType.Pfx);
cert = new X509Certificate2(pfx, (string)null, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
if (!certExists(store, cert.SubjectName.Name))
{
store.Add(cert);
bRet = true;
}
}
store.Close();
}
catch
{
}
return bRet;
}
| I edited the answer to do the root certificate first and then issue an end entity certificate.
Here is some example of generating a self-signed certificate through Bouncy Castle:
public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength = 2048)
{
// Generating Random Numbers
var randomGenerator = new CryptoApiRandomGenerator();
var random = new SecureRandom(randomGenerator);
// The Certificate Generator
var certificateGenerator = new X509V3CertificateGenerator();
// Serial Number
var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
certificateGenerator.SetSerialNumber(serialNumber);
// Signature Algorithm
const string signatureAlgorithm = "SHA256WithRSA";
certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
// Issuer and Subject Name
var subjectDN = new X509Name(subjectName);
var issuerDN = new X509Name(issuerName);
certificateGenerator.SetIssuerDN(issuerDN);
certificateGenerator.SetSubjectDN(subjectDN);
// Valid For
var notBefore = DateTime.UtcNow.Date;
var notAfter = notBefore.AddYears(2);
certificateGenerator.SetNotBefore(notBefore);
certificateGenerator.SetNotAfter(notAfter);
// Subject Public Key
AsymmetricCipherKeyPair subjectKeyPair;
var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
var keyPairGenerator = new RsaKeyPairGenerator();
keyPairGenerator.Init(keyGenerationParameters);
subjectKeyPair = keyPairGenerator.GenerateKeyPair();
certificateGenerator.SetPublicKey(subjectKeyPair.Public);
// Generating the Certificate
var issuerKeyPair = subjectKeyPair;
// Selfsign certificate
var certificate = certificateGenerator.Generate(issuerPrivKey, random);
// Corresponding private key
PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
// Merge into X509Certificate2
var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
if (seq.Count != 9)
throw new PemException("malformed sequence in RSA private key");
var rsa = new RsaPrivateKeyStructure(seq);
RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);
x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
return x509;
}
public static AsymmetricKeyParameter GenerateCACertificate(string subjectName, int keyStrength = 2048)
{
// Generating Random Numbers
var randomGenerator = new CryptoApiRandomGenerator();
var random = new SecureRandom(randomGenerator);
// The Certificate Generator
var certificateGenerator = new X509V3CertificateGenerator();
// Serial Number
var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
certificateGenerator.SetSerialNumber(serialNumber);
// Signature Algorithm
const string signatureAlgorithm = "SHA256WithRSA";
certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
// Issuer and Subject Name
var subjectDN = new X509Name(subjectName);
var issuerDN = subjectDN;
certificateGenerator.SetIssuerDN(issuerDN);
certificateGenerator.SetSubjectDN(subjectDN);
// Valid For
var notBefore = DateTime.UtcNow.Date;
var notAfter = notBefore.AddYears(2);
certificateGenerator.SetNotBefore(notBefore);
certificateGenerator.SetNotAfter(notAfter);
// Subject Public Key
AsymmetricCipherKeyPair subjectKeyPair;
var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
var keyPairGenerator = new RsaKeyPairGenerator();
keyPairGenerator.Init(keyGenerationParameters);
subjectKeyPair = keyPairGenerator.GenerateKeyPair();
certificateGenerator.SetPublicKey(subjectKeyPair.Public);
// Generating the Certificate
var issuerKeyPair = subjectKeyPair;
// Selfsign certificate
var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);
var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
// Add CA certificate to Root store
addCertToStore(cert, StoreName.Root, StoreLocation.CurrentUser);
return issuerKeyPair.Private;
}
And add to the store (your code slightly modified):
public static bool addCertToStore(System.Security.Cryptography.X509Certificates.X509Certificate2 cert, System.Security.Cryptography.X509Certificates.StoreName st, System.Security.Cryptography.X509Certificates.StoreLocation sl)
{
bool bRet = false;
try
{
X509Store store = new X509Store(st, sl);
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
store.Close();
}
catch
{
}
return bRet;
}
And usage:
var caPrivKey = GenerateCACertificate("CN=root ca");
var cert = GenerateSelfSignedCertificate("CN=127.0.01", "CN=root ca", caPrivKey);
addCertToStore(cert, StoreName.My, StoreLocation.CurrentUser);
I have not compiled this example code after @wakeupneo comments. @wakeupneo, you might have to slightly edit the code and add proper extensions to each certificate.
| Bouncy Castle | 22,230,745 | 54 |
In versions prior to r146 it was possible to create X509Certificate objects directly.
Now that API is deprecated and the new one only deliveres a X509CertificateHolder object.
I cannot find a way to transform a X509CertificateHolder to X509Certificate.
How can this be done?
| I will answer to my own questions, but not delete it, in case someone else got the same problems:
return new JcaX509CertificateConverter().getCertificate(certificateHolder);
And for attribute certificates:
return new X509V2AttributeCertificate(attributeCertificateHolder.getEncoded());
Not nice, as it is encoding and decoding, but it works.
| Bouncy Castle | 6,370,368 | 50 |
My application will take a set of files and sign them. (I'm not trying to sign an assembly.) There is a .p12 file that I get the private key from.
This is the code I was trying to use, but I get a System.Security.Cryptography.CryptographicException "Invalid algorithm specified.".
X509Certificate pXCert = new X509Certificate2(@"keyStore.p12", "password");
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)pXCert.PrivateKey;
string id = CryptoConfig.MapNameToOID("SHA256");
return csp.SignData(File.ReadAllBytes(filePath), id);
According to this answer it can't be done (the RSACryptoServiceProvider does not support SHA-256), but I was hoping that it might be possible using a different library, like Bouncy Castle.
I'm new to this stuff and I'm finding Bouncy Castle to be very confusing. I'm porting a Java app to C# and I have to use the same type of encryption to sign the files, so I am stuck with RSA + SHA256.
How can I do this using Bouncy Castle, OpenSSL.NET, Security.Cryptography, or another 3rd party library I haven't heard of? I'm assuming, if it can be done in Java then it can be done in C#.
UPDATE:
this is what I got from the link in poupou's anwser
X509Certificate2 cert = new X509Certificate2(KeyStoreFile, password);
RSACryptoServiceProvider rsacsp = (RSACryptoServiceProvider)cert.PrivateKey;
CspParameters cspParam = new CspParameters();
cspParam.KeyContainerName = rsacsp.CspKeyContainerInfo.KeyContainerName;
cspParam.KeyNumber = rsacsp.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2;
RSACryptoServiceProvider aescsp = new RSACryptoServiceProvider(cspParam);
aescsp.PersistKeyInCsp = false;
byte[] signed = aescsp.SignData(File.ReadAllBytes(file), "SHA256");
bool isValid = aescsp.VerifyData(File.ReadAllBytes(file), "SHA256", signed);
The problem is that I'm not getting the same results as I got with the original tool. As far as I can tell from reading the code the CryptoServiceProvider that does the actual signing is not using the PrivateKey from key store file. Is that Correct?
| RSA + SHA256 can and will work...
Your later example may not work all the time, it should use the hash algorithm's OID, rather than it's name. As per your first example, this is obtained from a call to CryptoConfig.MapNameToOID(AlgorithmName) where AlgorithmName is what you are providing (i.e. "SHA256").
First you are going to need is the certificate with the private key. I normally read mine from the LocalMachine or CurrentUser store by using a public key file (.cer) to identify the private key, and then enumerate the certificates and match on the hash...
X509Certificate2 publicCert = new X509Certificate2(@"C:\mycertificate.cer");
//Fetch private key from the local machine store
X509Certificate2 privateCert = null;
X509Store store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
foreach( X509Certificate2 cert in store.Certificates)
{
if (cert.GetCertHashString() == publicCert.GetCertHashString())
privateCert = cert;
}
However you get there, once you've obtained a certificate with a private key we need to reconstruct it. This may be required due to the way the certificate creates it's private key, but I'm not really sure why. Anyway, we do this by first exporting the key and then re-importing it using whatever intermediate format you like, the easiest is xml:
//Round-trip the key to XML and back, there might be a better way but this works
RSACryptoServiceProvider key = new RSACryptoServiceProvider();
key.FromXmlString(privateCert.PrivateKey.ToXmlString(true));
Once that is done we can now sign a piece of data as follows:
//Create some data to sign
byte[] data = new byte[1024];
//Sign the data
byte[] sig = key.SignData(data, CryptoConfig.MapNameToOID("SHA256"));
Lastly, the verification can be done directly with the certificate's public key without need for the reconstruction as we did with the private key:
key = (RSACryptoServiceProvider)publicCert.PublicKey.Key;
if (!key.VerifyData(data, CryptoConfig.MapNameToOID("SHA256"), sig))
throw new CryptographicException();
| Bouncy Castle | 7,444,586 | 50 |
I was trying to extract RES public key from the file below
-----BEGIN CERTIFICATE-----
MIIGwTCCBamgAwIBAgIQDlV4zznmQiVeF45Ipc0k7DANBgkqhkiG9w0BAQUFADBmMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSUwIwYDVQQDExxEaWdpQ2VydCBIaWdoIEFzc3VyYW5jZSBDQS0zMB4XDTEyMTAzMDAwMDAwMFoXDTE1MTEwNDEyMDAwMFowgYIxCzAJBgNVBAYTAlVTMQ4wDAYDVQQIEwVUZXhhczEQMA4GA1UEBxMHSG91c3RvbjEpMCcGA1UEChMgVmFsZXJ1cyBDb21wcmVzc2lvbiBTZXJ2aWNlcywgTFAxCzAJBgNVBAsTAklUMRkwFwYDVQQDDBAqLnZhbGVydXMtY28uY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1GR2NKV9GwVHBtpvgBUdVVbd6qeh6aKOS/r5TIKFd3vFBGjC7cWYwF26F0YFvrAP262Yu+oDRTeuSKwyHmegD7aTSOyCTOva69WcnKYRmNfHsnnGRa5z4v9EKc1RbNcwIrDUz8zcdHdP6AO8JJgLreWyBl15WXdxAr3yNbwoyJTbWk2ToC64LASP+8SQQTRszg762FIbhZ8xda8KKGAyC29/FOcLIttoBANT4hEwvcRLKOxAA8tg322Dla1XU2gnxWP2dSuLEflGRcEovPjGqxCzuGe0aN8Lg7aKwgCR1OYXmGiKCNHupHkN7A+QrD8zrxKUFd1UiyLcIovYhadcdQIDAQABo4IDTDCCA0gwHwYDVR0jBBgwFoAUUOpzidsp+xCPnuUBINTeeZlIg/cwHQYDVR0OBBYEFKKX1d9m6kHUjxQ1OpzXgNRbNGR4MCsGA1UdEQQkMCKCECoudmFsZXJ1cy1jby5jb22CDnZhbGVydXMtY28uY29tMA4GA1UdDwEB/wQEAwIFoDATBgNVHSUEDDAKBggrBgEFBQcDATBhBgNVHR8EWjBYMCqgKKAmhiRodHRwOi8vY3JsMy5kaWdpY2VydC5jb20vY2EzLWcxNi5jcmwwKqAooCaGJGh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9jYTMtZzE2LmNybDCCAcQGA1UdIASCAbswggG3MIIBswYJYIZIAYb9bAEBMIIBpDA6BggrBgEFBQcCARYuaHR0cDovL3d3dy5kaWdpY2VydC5jb20vc3NsLWNwcy1yZXBvc2l0b3J5Lmh0bTCCAWQGCCsGAQUFBwICMIIBVh6CAVIAQQBuAHkAIAB1AHMAZQAgAG8AZgAgAHQAaABpAHMAIABDAGUAcgB0AGkAZgBpAGMAYQB0AGUAIABjAG8AbgBzAHQAaQB0AHUAdABlAHMAIABhAGMAYwBlAHAAdABhAG4AYwBlACAAbwBmACAAdABoAGUAIABEAGkAZwBpAEMAZQByAHQAIABDAFAALwBDAFAAUwAgAGEAbgBkACAAdABoAGUAIABSAGUAbAB5AGkAbgBnACAAUABhAHIAdAB5ACAAQQBnAHIAZQBlAG0AZQBuAHQAIAB3AGgAaQBjAGgAIABsAGkAbQBpAHQAIABsAGkAYQBiAGkAbABpAHQAeQAgAGEAbgBkACAAYQByAGUAIABpAG4AYwBvAHIAcABvAHIAYQB0AGUAZAAgAGgAZQByAGUAaQBuACAAYgB5ACAAcgBlAGYAZQByAGUAbgBjAGUALjB7BggrBgEFBQcBAQRvMG0wJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBFBggrBgEFBQcwAoY5aHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0SGlnaEFzc3VyYW5jZUNBLTMuY3J0MAwGA1UdEwEB/wQCMAAwDQYJKoZIhvcNAQEFBQADggEBALdCoLlXX4Sg8pKcqlT8l1MHbS2rsnw03R8lVQBQqcJimE9VZqDdoLfEPASIEMQbl40T6RHb4tFuZNjP2y4Fy3jMAYf1yajZAtAd5OLOMU39cgZQY2J8QCeEVKt8qbH6P32/2yyuh4hcNL4Vz8G0MTzwVUjz8WVmUBHAQSpS0T9oDKkwvmrkPGJFVuBxCRDKYb/23O8EKKzSTiO37VbCaeFUrTuWc8tGP8XDqRdj2yefiVqcNp4xr2tq9ZhJcISWODqO4fzt6vPOwgdnY3fbPLeH2tZoZTSCPURAadoNOAIC6fCLFlHjLuRGkxWIHMX3QnrrVD8pC7FnDO09q/aADew=
-----END CERTIFICATE-----
Here is the code i did..
public static PublicKey loadPublicKeyFromFile(File publicKeyFile) throws Exception {
FileReader file = new FileReader(publicKeyFile);
PemReader reader = new PemReader(file);
X509EncodedKeySpec caKeySpec = new X509EncodedKeySpec(reader.readPemObject().getContent());
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey caKey = kf.generatePublic(caKeySpec);
return caKey;
}
But It throws out
java.security.InvalidKeyException: IOException: ObjectIdentifier() -- data isn't an object ID
What's the appropriate way to extract RES Public key from a file..
| An X.509 certificate and an X509EncodedKeySpec are quite different structures, and trying to parse a cert as a key won't work.
Java's X509EncodedKeySpec is actually SubjectPublicKeyInfo from X.509 or equivalent and more convenient PKIX also linked from Key, which is only a small part of a certificate.
What you need to do is read and parse the cert and then extract the pubkey from the cert.
Standard SunJCE CertificateFactory can do it
(and can read either PEM or DER to boot) like this:
CertificateFactory fact = CertificateFactory.getInstance("X.509");
FileInputStream is = new FileInputStream (args[0]);
X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
PublicKey key = cer.getPublicKey();
is.close();
// add error handling as appropriate, try-with-resources is often good
If you have BouncyCastle you can use its provider the same way (just add a second argument to .getInstance or set the default provider list order), or you can use PEMParser with JcaX509CertificateConverter -- which effectively does the same thing, internally running the data through a CertificateFactory.
| Bouncy Castle | 24,137,463 | 49 |
I need to encrypt a stream with pgp using the bouncycastle provider. All of the examples I can find are about taking a plain text file and encrypting that however I won't have a file and it's important that the plain text never be written to disk.
Most of the methods I've seen are using
PGPUtil.writeFileToLiteralData which wants the plaintext passed in. I'd rather passin a byte[] or an inputStream.
Can someone point me to an example that
starts from string/byte[]/inputstream
encrypts said string/byte[] to an outputStrem that I can write to a file
decrypts from an inputStream
In case anyone else stumbles upon this and wants the full solution
package com.common.security.pgp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Date;
import java.util.Iterator;
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPCompressedData;
import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedData;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataList;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPLiteralDataGenerator;
import org.bouncycastle.openpgp.PGPObjectFactory;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.PGPSecretKey;
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPUtil;
/**
* Simple routine to encrypt and decrypt using a Public and Private key with passphrase. This service
* routine provides the basic PGP services between byte arrays.
*
*/
public class PgpEncryption {
private static PGPPrivateKey findSecretKey(
PGPSecretKeyRingCollection pgpSec, long keyID, char[] pass)
throws PGPException, NoSuchProviderException {
PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
if (pgpSecKey == null) {
return null;
}
return pgpSecKey.extractPrivateKey(pass, "BC");
}
/**
* decrypt the passed in message stream
*
* @param encrypted
* The message to be decrypted.
* @param passPhrase
* Pass phrase (key)
*
* @return Clear text as a byte array. I18N considerations are not handled
* by this routine
* @exception IOException
* @exception PGPException
* @exception NoSuchProviderException
*/
public static byte[] decrypt(byte[] encrypted, InputStream keyIn, char[] password)
throws IOException, PGPException, NoSuchProviderException {
InputStream in = new ByteArrayInputStream(encrypted);
in = PGPUtil.getDecoderStream(in);
PGPObjectFactory pgpF = new PGPObjectFactory(in);
PGPEncryptedDataList enc = null;
Object o = pgpF.nextObject();
//
// the first object might be a PGP marker packet.
//
if (o instanceof PGPEncryptedDataList) {
enc = (PGPEncryptedDataList) o;
} else {
enc = (PGPEncryptedDataList) pgpF.nextObject();
}
//
// find the secret key
//
Iterator it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
PGPUtil.getDecoderStream(keyIn));
while (sKey == null && it.hasNext()) {
pbe = (PGPPublicKeyEncryptedData) it.next();
sKey = findSecretKey(pgpSec, pbe.getKeyID(), password);
}
if (sKey == null) {
throw new IllegalArgumentException(
"secret key for message not found.");
}
InputStream clear = pbe.getDataStream(sKey, "BC");
PGPObjectFactory pgpFact = new PGPObjectFactory(clear);
PGPCompressedData cData = (PGPCompressedData) pgpFact.nextObject();
pgpFact = new PGPObjectFactory(cData.getDataStream());
PGPLiteralData ld = (PGPLiteralData) pgpFact.nextObject();
InputStream unc = ld.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int ch;
while ((ch = unc.read()) >= 0) {
out.write(ch);
}
byte[] returnBytes = out.toByteArray();
out.close();
return returnBytes;
}
/**
* Simple PGP encryptor between byte[].
*
* @param clearData
* The test to be encrypted
* @param passPhrase
* The pass phrase (key). This method assumes that the key is a
* simple pass phrase, and does not yet support RSA or more
* sophisiticated keying.
* @param fileName
* File name. This is used in the Literal Data Packet (tag 11)
* which is really inly important if the data is to be related to
* a file to be recovered later. Because this routine does not
* know the source of the information, the caller can set
* something here for file name use that will be carried. If this
* routine is being used to encrypt SOAP MIME bodies, for
* example, use the file name from the MIME type, if applicable.
* Or anything else appropriate.
*
* @param armor
*
* @return encrypted data.
* @exception IOException
* @exception PGPException
* @exception NoSuchProviderException
*/
public static byte[] encrypt(byte[] clearData, PGPPublicKey encKey,
String fileName,boolean withIntegrityCheck, boolean armor)
throws IOException, PGPException, NoSuchProviderException {
if (fileName == null) {
fileName = PGPLiteralData.CONSOLE;
}
ByteArrayOutputStream encOut = new ByteArrayOutputStream();
OutputStream out = encOut;
if (armor) {
out = new ArmoredOutputStream(out);
}
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(
PGPCompressedDataGenerator.ZIP);
OutputStream cos = comData.open(bOut); // open it with the final
// destination
PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
// we want to generate compressed data. This might be a user option
// later,
// in which case we would pass in bOut.
OutputStream pOut = lData.open(cos, // the compressed output stream
PGPLiteralData.BINARY, fileName, // "filename" to store
clearData.length, // length of clear data
new Date() // current time
);
pOut.write(clearData);
lData.close();
comData.close();
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
PGPEncryptedData.CAST5, withIntegrityCheck, new SecureRandom(),
"BC");
cPk.addMethod(encKey);
byte[] bytes = bOut.toByteArray();
OutputStream cOut = cPk.open(out, bytes.length);
cOut.write(bytes); // obtain the actual bytes from the compressed stream
cOut.close();
out.close();
return encOut.toByteArray();
}
private static PGPPublicKey readPublicKey(InputStream in)
throws IOException, PGPException {
in = PGPUtil.getDecoderStream(in);
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in);
//
// we just loop through the collection till we find a key suitable for
// encryption, in the real
// world you would probably want to be a bit smarter about this.
//
//
// iterate through the key rings.
//
Iterator rIt = pgpPub.getKeyRings();
while (rIt.hasNext()) {
PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next();
Iterator kIt = kRing.getPublicKeys();
while (kIt.hasNext()) {
PGPPublicKey k = (PGPPublicKey) kIt.next();
if (k.isEncryptionKey()) {
return k;
}
}
}
throw new IllegalArgumentException(
"Can't find encryption key in key ring.");
}
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
byte[] original = "Hello world".getBytes();
System.out.println("Starting PGP test");
FileInputStream pubKey = new FileInputStream("/Users/me/pub.key");
byte[] encrypted = encrypt(original, readPublicKey(pubKey), null,
true, true);
FileOutputStream dfis = new FileOutputStream("/Users/me/enc.asc");
dfis.write(encrypted);
dfis.close();
byte[] encFromFile = getBytesFromFile(new File("/Users/me/enc.asc"));
FileInputStream secKey = new FileInputStream("/Users/me/sec.key");
System.out.println("\nencrypted data = '" + new String(encrypted) + "'");
byte[] decrypted = decrypt(encFromFile, secKey, "passphrase".toCharArray());
System.out.println("\ndecrypted data = '" + new String(decrypted) + "'");
}
}
| Looking at the source of PGPUtil you can see what API to call when working with streams or arrays directly:
public static void writeFileToLiteralData(OutputStream out,
char fileType, File file, byte[] buffer) throws IOException {
PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
OutputStream pOut = lData.open(out, fileType, file.getName(),
new Date(file.lastModified()), buffer);
FileInputStream in = new FileInputStream(file);
byte[] buf = new byte[buffer.length];
int len;
while ((len = in.read(buf)) > 0) {
pOut.write(buf, 0, len);
}
lData.close();
in.close();
}
| Bouncy Castle | 3,939,447 | 45 |
I'm trying to securely store a password in a database and for that I chose to store its hash generated using the PBKDF2 function. I want to do this using the bouncy castle library but I don't know why I cannot get it to work by using the JCE interface...
The problem is that generating the hash in 3 different modes:
1. using the PBKDF2WithHmacSHA1 secret key factory provided by sun
2. using the bouncy castle api directly
3. using the bouncy castle through JCE
results in 2 distinct values: one common to the first two and one for the third.
Here is my code:
//Mode 1
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec keyspec = new PBEKeySpec("password".toCharArray(), salt, 1000, 128);
Key key = factory.generateSecret(keyspec);
System.out.println(key.getClass().getName());
System.out.println(Arrays.toString(key.getEncoded()));
//Mode 2
PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(("password").toCharArray()), salt, 1000);
KeyParameter params = (KeyParameter)generator.generateDerivedParameters(128);
System.out.println(Arrays.toString(params.getKey()));
//Mode 3
SecretKeyFactory factorybc = SecretKeyFactory.getInstance("PBEWITHHMACSHA1", "BC");
KeySpec keyspecbc = new PBEKeySpec("password".toCharArray(), salt, 1000, 128);
Key keybc = factorybc.generateSecret(keyspecbc);
System.out.println(keybc.getClass().getName());
System.out.println(Arrays.toString(keybc.getEncoded()));
System.out.println(keybc.getAlgorithm());
I know that PBKDF2 is implemented using HMAC SHA1 so that is why i chose as algorithm in the last method the "PBEWITHHMACSHA1" which i took from the bouncy castle java docs.
The output is the following:
com.sun.crypto.provider.SunJCE_ae
[-53, 29, 113, -110, -25, 76, 115, -127, -64, 74, -63, 102, 75, 81, -21, 74]
[-53, 29, 113, -110, -25, 76, 115, -127, -64, 74, -63, 102, 75, 81, -21, 74]
org.bouncycastle.jce.provider.JCEPBEKey
[14, -47, -87, -16, -117, -31, 91, -121, 90, -68, -82, -31, -27, 5, -93, -67, 30, -34, -64, -40]
PBEwithHmacSHA
Any ideas?
| In short, the reason for the difference is that PBKDF2 algorithm in modes #1 and #2 uses PKCS #5 v2 scheme 2 (PKCS5S2) for iterative key generation, but the BouncyCastle provider for "PBEWITHHMACSHA1" in mode #3 uses the PKCS #12 v1 (PKCS12) algorithm instead. These are completely different key-generation algorithms, so you get different results.
More detail on why this is so and why you get different sized results is explained below.
First, when you're constructing a JCE KeySpec, the keyLength parameter only expresses "a preference" to the provider what key size you want. From the API docs:
Note: this is used to indicate the preference on key length for variable-key-size ciphers. The actual key size depends on each provider's implementation.
The Bouncy Castle providers don't appear to respect this parameter, judging from the source of JCEPBEKey, so you should expect to get a 160-bit key back from any BC provider which uses SHA-1 when using the JCE API.
You can confirm this by programmatically accessing the getKeySize() method on the returned keybc variable in your test code:
Key keybc = factorybc.generateSecret(keyspecbc);
// ...
Method getKeySize = JCEPBEKey.class.getDeclaredMethod("getKeySize");
getKeySize.setAccessible(true);
System.out.println(getKeySize.invoke(keybc)); // prints '160'
Now, to understand what the "PBEWITHHMACSHA1" provider corresponds to, you can find the following in the source for BouncyCastleProvider:
put("SecretKeyFactory.PBEWITHHMACSHA1",
"org.bouncycastle.jce.provider.JCESecretKeyFactory$PBEWithSHA");
And the implementation of JCESecretKeyFactory.PBEWithSHA looks like this:
public static class PBEWithSHA
extends PBEKeyFactory
{
public PBEWithSHA()
{
super("PBEwithHmacSHA", null, false, PKCS12, SHA1, 160, 0);
}
}
You can see above that this key factory uses the PKCS #12 v1 (PKCS12) algorithm for iterative key generation. But the PBKDF2 algorithm that you want to use for password hashing uses PKCS #5 v2 scheme 2 (PKCS5S2) instead. This is why you're getting different results.
I had a quick look through the JCE providers registered in BouncyCastleProvider, but couldn't see any key generation algorithms that used PKCS5S2 at all, let alone one which also uses it with HMAC-SHA-1.
So I guess you're stuck with either using the Sun implementation (mode #1 above) and losing portability on other JVMs, or using the Bouncy Castle classes directly (mode #2 above) and requiring the BC library at runtime.
Either way, you should probably switch to 160-bit keys, so you aren't truncating the generated SHA-1 hash unnecessarily.
| Bouncy Castle | 8,674,018 | 41 |
We're trying to generate an X509 certificate (including the private key) programmatically using C# and the BouncyCastle library. We've tried using some of the code from this sample by Felix Kollmann but the private key part of the certificate returns null. Code and unit test are as below:
using System;
using System.Collections;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Prng;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
namespace MyApp
{
public class CertificateGenerator
{
/// <summary>
///
/// </summary>
/// <remarks>Based on <see cref="http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx"/></remarks>
/// <param name="subjectName"></param>
/// <returns></returns>
public static byte[] GenerateCertificate(string subjectName)
{
var kpgen = new RsaKeyPairGenerator();
kpgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));
var kp = kpgen.GenerateKeyPair();
var gen = new X509V3CertificateGenerator();
var certName = new X509Name("CN=" + subjectName);
var serialNo = BigInteger.ProbablePrime(120, new Random());
gen.SetSerialNumber(serialNo);
gen.SetSubjectDN(certName);
gen.SetIssuerDN(certName);
gen.SetNotAfter(DateTime.Now.AddYears(100));
gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
gen.SetSignatureAlgorithm("MD5WithRSA");
gen.SetPublicKey(kp.Public);
gen.AddExtension(
X509Extensions.AuthorityKeyIdentifier.Id,
false,
new AuthorityKeyIdentifier(
SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public),
new GeneralNames(new GeneralName(certName)),
serialNo));
gen.AddExtension(
X509Extensions.ExtendedKeyUsage.Id,
false,
new ExtendedKeyUsage(new ArrayList() { new DerObjectIdentifier("1.3.6.1.5.5.7.3.1") }));
var newCert = gen.Generate(kp.Private);
return DotNetUtilities.ToX509Certificate(newCert).Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, "password");
}
}
}
Unit test:
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MyApp
{
[TestClass]
public class CertificateGeneratorTests
{
[TestMethod]
public void GenerateCertificate_Test_ValidCertificate()
{
// Arrange
string subjectName = "test";
// Act
byte[] actual = CertificateGenerator.GenerateCertificate(subjectName);
// Assert
var cert = new X509Certificate2(actual, "password");
Assert.AreEqual("CN=" + subjectName, cert.Subject);
Assert.IsInstanceOfType(cert.PrivateKey, typeof(RSACryptoServiceProvider));
}
}
}
| Just to clarify, an X.509 certificate does not contain the private key. The word certificate is sometimes misused to represent the combination of the certificate and the private key, but they are two distinct entities. The whole point of using certificates is to send them more or less openly, without sending the private key, which must be kept secret. An X509Certificate2 object may have a private key associated with it (via its PrivateKey property), but that's only a convenience as part of the design of this class.
In your first BouncyCastle code example, newCert is really just the certificate and DotNetUtilities.ToX509Certificate(newCert) is built from the certificate only.
Considering that the PKCS#12 format requires the presence of a private key, I'm quite surprised that the following part even works (considering you're calling it on a certificate which can't possibly know the private key):
.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12,
"password");
(gen.Generate(kp.Private) signs the certificate using the private key, but doesn't put the private key in the certificate, which wouldn't make sense.)
If you want your method to return both the certificate and the private key you could either:
Return an X509Certificate2 object in which you've initialized the PrivateKey property
Build a PKCS#12 store and returns its byte[] content (as if it was a file). Step 3 in the link you've sent (mirror) explains how to build a PKCS#12 store.
Returning the byte[] (DER) structure for the X.509 certificate itself will not contain the private key.
If your main concern (according to your test case) is to check that the certificate was built from an RSA key-pair, you can check the type of its public key instead.
| Bouncy Castle | 3,770,233 | 40 |
What is the difference between compute a signature with the following two methods?
Compute a signature with Signature.getInstance("SHA256withRSA")
Compute SHA256 with MessageDigest.getInstance("SHA-256") and compute the digest with Signature.getInstance("RSA"); to get the signature?
If they are different, is there a way to modify the method 2 so that both methods give the same output?
I tried the following code:
package mysha.mysha;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Security;
import java.security.Signature;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class MySHA256 {
public static void main(String[] args) throws Exception {
//compute SHA256 first
Security.addProvider(new BouncyCastleProvider());
String s = "1234";
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(s.getBytes());
byte[] outputDigest = messageDigest.digest();
//sign SHA256 with RSA
PrivateKey privateKey = Share.loadPk8("D:/key.pk8");
Signature rsaSignature = Signature.getInstance("RSA");
rsaSignature.initSign(privateKey);
rsaSignature.update(outputDigest);
byte[] signed = rsaSignature.sign();
System.out.println(bytesToHex(signed));
//compute SHA256withRSA as a single step
Signature rsaSha256Signature = Signature.getInstance("SHA256withRSA");
rsaSha256Signature.initSign(privateKey);
rsaSha256Signature.update(s.getBytes());
byte[] signed2 = rsaSha256Signature.sign();
System.out.println(bytesToHex(signed2));
}
public static String bytesToHex(byte[] bytes) {
final char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
Nevertheless, the outputs are not the same.
The following is the sample output with my test key:
method 1: 61427B2A2CF1902A4B15F80156AEB09D8096BA1271F89F1919C78B18D0BABA08AA043A0037934B5AE3FC0EB7702898AC5AE96517AFD93433DF540353BCCE72A470CFA4B765D5835E7EA77743F3C4A0ABB11414B0141EF7ECCD2D5285A69728D0D0709C2537D6A772418A928B0E168F81C99B538FD25BDA7496AE8E185AC46F39
method 2: BA9039B75CA8A40DC9A7AED51E174E2B3365B2D6A1CF94DF70A00D898074A51FDD9973672DDE95CBAC39EBE4F3BA529C538ED0FF9F0A3F9A8CE203F1DFFA907DC508643906AA86DA54DFF8A90B00F5F116D13A53731384C1C5C9C4E75A3E41DAF88F74D2F1BCCF818764A4AB144A081B641C1C488AC8B194EB14BC9D1928E4EA
Update 1:
According to mkl's answer, I modify my code but still cannot get it right. Do I still miss something?
package mysha.mysha;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Security;
import java.security.Signature;
import org.bouncycastle.asn1.DEROutputStream;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.DigestInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class MySHA256 {
public static void main(String[] args) throws Exception {
//compute SHA256 first
Security.addProvider(new BouncyCastleProvider());
String s = "1234";
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(s.getBytes());
byte[] outputDigest = messageDigest.digest();
AlgorithmIdentifier sha256Aid = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, null);
DigestInfo di = new DigestInfo(sha256Aid, outputDigest);
//sign SHA256 with RSA
PrivateKey privateKey = Share.loadPk8("D:/key.pk8");
Signature rsaSignature = Signature.getInstance("RSA");
rsaSignature.initSign(privateKey);
rsaSignature.update(di.toASN1Primitive().getEncoded());
byte[] signed = rsaSignature.sign();
System.out.println("method 1: "+bytesToHex(signed));
//compute SHA256withRSA as a single step
Signature rsaSha256Signature = Signature.getInstance("SHA256withRSA");
rsaSha256Signature.initSign(privateKey);
rsaSha256Signature.update(s.getBytes());
byte[] signed2 = rsaSha256Signature.sign();
System.out.println("method 2: "+bytesToHex(signed2));
}
public static String bytesToHex(byte[] bytes) {
final char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
method 1:
675D868546777C5A9B5E74988E0CD41A46A929C1D0890B32B1FBE34F12D68F1FDB56E623294DB903F6AC60A2ADA61976B27C66056A16F5790A78168803AD2C685F9B4CF983C939305A9819CBA9D95441CD7214D40D06A98B4DDF9692A7D300DD51E808A6722A0D7C288DBD476DF4DEEBB3DAF41CFC0978F24424960F86F0284E
method 2:
BA9039B75CA8A40DC9A7AED51E174E2B3365B2D6A1CF94DF70A00D898074A51FDD9973672DDE95CBAC39EBE4F3BA529C538ED0FF9F0A3F9A8CE203F1DFFA907DC508643906AA86DA54DFF8A90B00F5F116D13A53731384C1C5C9C4E75A3E41DAF88F74D2F1BCCF818764A4AB144A081B641C1C488AC8B194EB14BC9D1928E4EA
| The difference
The difference between signing with "SHA256withRSA" and computing the SHA256 hash and signing it with "RSA" (= "NONEwithRSA") is foremost that in the former case the calculated SHA-256 hash value is first encapsulated in a DigestInfo structure
DigestInfo ::= SEQUENCE {
digestAlgorithm DigestAlgorithm,
digest OCTET STRING
}
before being padded and then encrypted while in the latter case the naked SHA256 hash value is padded and encrypted.
If they are different, is there a way to modify the method 2 so that both methods give the same output?
First and foremost you will have to encapsulate the hash value in a DigestInfo structure before signing using "NONEwithRSA".
RFC 3447 Section 9.2 helps here by stating in Note 1 that
1. For the six hash functions mentioned in Appendix B.1, the DER
encoding T of the DigestInfo value is equal to the following:
...
SHA-256: (0x)30 31 30 0d 06 09 60 86 48 01 65 03 04 02 01 05 00
04 20 || H.
Making it work
In response to the section above the OP updated his question with the updated code. Unfortunately, though, it did not yet work for him. Thus,
The OP's code
I executed the OP's code (SignInSteps.java). As he didn't provide the private key, I used a test key of my own (demo-rsa2048.p12). The result:
GreenhandOriginal:
1B9557B6A076226FA4C26A9370A0E9E91B627F14204D427B03294EC4BFC346FDEEFB3A483B1E5A0593F26E9DE87F9202E1064F4D75B24B8FA355B23A560AF263361BB94B2339C3A01952C447CAC862AA9DCAB64B09ABAA0AD50232CDB299D1E4B5F7138F448A87ED32BFF4B5B66F35FFA08F13FD98DFCEC7114710282E463245311DA7A56CBEA958D88137A8B507D8601464535978EFE36EE37EF721260DB7112484F244409F0BD64C823ACFB13D06ABA84A9A0C5AB207E19231D6A71CC80F07FDA2A9654F0F609C2C3396D6DFFBBB10EF4C3D4B5ADFC72EACC044E81F252B699F095CFEF8630B284B1F6BD7201367BD5FDF2BB4C20BD07B9CC20B214D86C729
4B9ECA6DD47C1B230D972E7DA026165F1CE743EC96825E4C13DFE2C6437FE673A13CA622047EE7D2F7C5280198D81550A1CBD17F8E8A3C4C2D53A746FA6464AA5194FC2782527B014F017008D89BB2C80B7FA367C74FE01369986B56BCE7DC573A11ED884511F0CB12160CA5E42D488451AA8961BF5A9F71E6A5E89F19BC8EFAC26DDE989A0369667EE74372F6E558887FE2561EA926B441AB8F0FD3DEDD608A671011313372084B059CAD7E4807AC852C0873C57F216349422771C089678BAC3021D054C4427EADE70219E251617B83E68640DD7D03C3F99E47F79EB71C124F59EDEA724496A4552F2E9E1F90DDE550745E85483D823F146982C6D2008FE9AA
GreenhandUpdated:
method 1: 4B9ECA6DD47C1B230D972E7DA026165F1CE743EC96825E4C13DFE2C6437FE673A13CA622047EE7D2F7C5280198D81550A1CBD17F8E8A3C4C2D53A746FA6464AA5194FC2782527B014F017008D89BB2C80B7FA367C74FE01369986B56BCE7DC573A11ED884511F0CB12160CA5E42D488451AA8961BF5A9F71E6A5E89F19BC8EFAC26DDE989A0369667EE74372F6E558887FE2561EA926B441AB8F0FD3DEDD608A671011313372084B059CAD7E4807AC852C0873C57F216349422771C089678BAC3021D054C4427EADE70219E251617B83E68640DD7D03C3F99E47F79EB71C124F59EDEA724496A4552F2E9E1F90DDE550745E85483D823F146982C6D2008FE9AA
method 2: 4B9ECA6DD47C1B230D972E7DA026165F1CE743EC96825E4C13DFE2C6437FE673A13CA622047EE7D2F7C5280198D81550A1CBD17F8E8A3C4C2D53A746FA6464AA5194FC2782527B014F017008D89BB2C80B7FA367C74FE01369986B56BCE7DC573A11ED884511F0CB12160CA5E42D488451AA8961BF5A9F71E6A5E89F19BC8EFAC26DDE989A0369667EE74372F6E558887FE2561EA926B441AB8F0FD3DEDD608A671011313372084B059CAD7E4807AC852C0873C57F216349422771C089678BAC3021D054C4427EADE70219E251617B83E68640DD7D03C3F99E47F79EB71C124F59EDEA724496A4552F2E9E1F90DDE550745E85483D823F146982C6D2008FE9AA
Thus, in contrast to the OP's observations, signatures equal in case of the updated code.
Not assuming copy&paste errors, there still might be other differences involved.
The environment
I tested using Java 8 (1.8.0_20) with unlimited jurisdiction files added and BouncyCastle 1.52, 1.49, and 1.46 (with a small test code modification due to the BC API changes).
The OP mentioned in a comment:
The Java is JRE 8 update 66. The BouncyCastle is bcprov-jdk15on-153.jar.
Thus I updated Java, still no difference.
Then I updated BouncyCastle to 1.53. And indeed, suddenly the results differed:
GreenhandOriginal:
1B9557B6A076226FA4C26A9370A0E9E91B627F14204D427B03294EC4BFC346FDEEFB3A483B1E5A0593F26E9DE87F9202E1064F4D75B24B8FA355B23A560AF263361BB94B2339C3A01952C447CAC862AA9DCAB64B09ABAA0AD50232CDB299D1E4B5F7138F448A87ED32BFF4B5B66F35FFA08F13FD98DFCEC7114710282E463245311DA7A56CBEA958D88137A8B507D8601464535978EFE36EE37EF721260DB7112484F244409F0BD64C823ACFB13D06ABA84A9A0C5AB207E19231D6A71CC80F07FDA2A9654F0F609C2C3396D6DFFBBB10EF4C3D4B5ADFC72EACC044E81F252B699F095CFEF8630B284B1F6BD7201367BD5FDF2BB4C20BD07B9CC20B214D86C729
4B9ECA6DD47C1B230D972E7DA026165F1CE743EC96825E4C13DFE2C6437FE673A13CA622047EE7D2F7C5280198D81550A1CBD17F8E8A3C4C2D53A746FA6464AA5194FC2782527B014F017008D89BB2C80B7FA367C74FE01369986B56BCE7DC573A11ED884511F0CB12160CA5E42D488451AA8961BF5A9F71E6A5E89F19BC8EFAC26DDE989A0369667EE74372F6E558887FE2561EA926B441AB8F0FD3DEDD608A671011313372084B059CAD7E4807AC852C0873C57F216349422771C089678BAC3021D054C4427EADE70219E251617B83E68640DD7D03C3F99E47F79EB71C124F59EDEA724496A4552F2E9E1F90DDE550745E85483D823F146982C6D2008FE9AA
GreenhandUpdated:
method 1: 6BAAAC1060B6D0D56AD7D45A1BEECE82391088FF47A8D8179EFBBEB0925C4AC6C9DFC56F672E99F4A6E3C106A866B70513C25AE11B267286C584A136FBC20C4D1E7B10697352DF020BA5D67029A6EF890B2674F02C496CB1F1EBB0D4DBB580EB045DBB0FA0D7D73B418FF63F345658C6C73DA742FE260C9639C94967A928F74F61DACA03310B9986C32D83CAB8C7FC13E80612CCFC0B7E3E35BEA04EAEBDAA55FB8837B4661DC71499B4A0B1D36E1D23D9927CDB55C237D5AB2E5C088F29C6FAFAD9FE64DD4851CEC113560864E9923D485D0C6E092C8EBE82D29C312E5835B38EE9BD6B8B4BCC753EF4EE4D0977B2E781B391839E3EC31C36E5B1AA0CE90227
method 2: 4B9ECA6DD47C1B230D972E7DA026165F1CE743EC96825E4C13DFE2C6437FE673A13CA622047EE7D2F7C5280198D81550A1CBD17F8E8A3C4C2D53A746FA6464AA5194FC2782527B014F017008D89BB2C80B7FA367C74FE01369986B56BCE7DC573A11ED884511F0CB12160CA5E42D488451AA8961BF5A9F71E6A5E89F19BC8EFAC26DDE989A0369667EE74372F6E558887FE2561EA926B441AB8F0FD3DEDD608A671011313372084B059CAD7E4807AC852C0873C57F216349422771C089678BAC3021D054C4427EADE70219E251617B83E68640DD7D03C3F99E47F79EB71C124F59EDEA724496A4552F2E9E1F90DDE550745E85483D823F146982C6D2008FE9AA
Interestingly only the value for method 1 in the updated code differs. Thus, I looked at the intermediary objects in that case
[BC 1.52]
hash: 03AC674216F3E15C761EE1A5E255F067953623C8B388B4459E13F978D7C846F4
algo: 2.16.840.1.101.3.4.2.1
info: 3031300D06096086480165030402010500042003AC674216F3E15C761EE1A5E255F067953623C8B388B4459E13F978D7C846F4
[BC 1.53]
hash: 03AC674216F3E15C761EE1A5E255F067953623C8B388B4459E13F978D7C846F4
algo: 2.16.840.1.101.3.4.2.1
info: 302F300B0609608648016503040201042003AC674216F3E15C761EE1A5E255F067953623C8B388B4459E13F978D7C846F4
Thus, BouncyCastle 1.53 encodes the DigestInfo object differently! And the encoding in 1.52 (and below) is the one expected by the RFC 3447 Section 9.2.
Looking at the ASN.1 dumps one sees that BC 1.52 encodes the AlgorithmIdentifier as
2 13: SEQUENCE {
<06 09>
4 9: OBJECT IDENTIFIER sha-256 (2 16 840 1 101 3 4 2 1)
: (NIST Algorithm)
<05 00>
15 0: NULL
: }
while BC 1.53 creates
2 11: SEQUENCE {
<06 09>
4 9: OBJECT IDENTIFIER sha-256 (2 16 840 1 101 3 4 2 1)
: (NIST Algorithm)
: }
So in 1.53 the algorithm parameters are missing altogether. This suggests changing the line
AlgorithmIdentifier sha256Aid = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, null);
to
AlgorithmIdentifier sha256Aid = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, DERNull.INSTANCE);
and suddenly it works with BouncyCastle 1.53, too, the values for method 1 and method 2 coincide! ;)
TL;DR
Don't use null as the SHA-256 parameters when instantiating the AlgorithmIdentifier, use DERNull.INSTANCE instead.
How did I...
In a comment the OP indicated that he'd like to know more about
how do you inspect the intermediate object of BouncyCastle and
how do you produce the ASN.1 dumps.
So...
... inspect the intermediate object
Quite simple. First I split up the line
rsaSignature.update(di.toASN1Primitive().getEncoded());
in the updated code as
byte[] encodedDigestInfo = di.toASN1Primitive().getEncoded();
rsaSignature.update(encodedDigestInfo);
and then added console outputs
System.out.println(" hash: " + bytesToHex(outputDigest));
System.out.println(" algo: " + sha256Aid.getAlgorithm());
System.out.println(" info: " + bytesToHex(encodedDigestInfo));
Finally I executed the code with the different BouncyCastle versions.
... produce the ASN.1 dumps
There is a well-known utility called dumpasn1 by Peter Gutmann which has become the kernel of many command line and GUI tools for creating and displaying ASN.1 dumps. I currently happen to use GUIdumpASN-ng.
In the case at hand I saved the contents of the byte[] encodedDigestInfo to a file (which can be done using e.g. Files.write) and opened these files in GUIdumpASN-ng.
| Bouncy Castle | 33,305,800 | 39 |
I cannot find any code/doc describing how to sign a CSR using BC. As input I have a CSR as a byte array and would like to get the cert in PEM and/or DER format.
I have gotten this far
def signCSR(csrData:Array[Byte], ca:CACertificate, caPassword:String) = {
val csr = new PKCS10CertificationRequestHolder(csrData)
val spi = csr.getSubjectPublicKeyInfo
val ks = new java.security.spec.X509EncodedKeySpec(spi.getDEREncoded())
val kf = java.security.KeyFactory.getInstance("RSA")
val pk = kf.generatePublic(ks)
val (caCert, caPriv) = parsePKCS12(ca.pkcs12data, caPassword)
val fromDate : java.util.Date = new java.util.Date // FixMe
val toDate = fromDate // FixMe
val issuer = PrincipalUtil.getIssuerX509Principal(caCert)
val contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC).build(caPriv)
val serial = BigInt(CertSerialnumber.nextSerialNumber)
val certgen = new JcaX509v3CertificateBuilder(new X500Name(issuer.getName), serial.bigInteger, fromDate, toDate, csr.getSubject, pk)
I have trouble figuring out get from a certificate generator to store this in PEM or DER format.
Or am I going down the wrong path all together?
| Ok ... I was looking to do the same stuff and for the life of me I couldn't figure out how. The APIs all talk about generating the key pairs and then generating the cert but not how to sign a CSR. Somehow, quite by chance - here's what I found.
Since PKCS10 represents the format of the request (of the CSR), you first need to put your CSR into a PKCS10Holder. Then, you pass it to a CertificateBuilder (since CertificateGenerator is deprecated). The way you pass it is to call getSubject on the holder.
Here's the code (Java, please adapt as you need):
public static X509Certificate sign(PKCS10CertificationRequest inputCSR, PrivateKey caPrivate, KeyPair pair)
throws InvalidKeyException, NoSuchAlgorithmException,
NoSuchProviderException, SignatureException, IOException,
OperatorCreationException, CertificateException {
AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder()
.find("SHA1withRSA");
AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder()
.find(sigAlgId);
AsymmetricKeyParameter foo = PrivateKeyFactory.createKey(caPrivate
.getEncoded());
SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(pair
.getPublic().getEncoded());
PKCS10CertificationRequestHolder pk10Holder = new PKCS10CertificationRequestHolder(inputCSR);
//in newer version of BC such as 1.51, this is
//PKCS10CertificationRequest pk10Holder = new PKCS10CertificationRequest(inputCSR);
X509v3CertificateBuilder myCertificateGenerator = new X509v3CertificateBuilder(
new X500Name("CN=issuer"), new BigInteger("1"), new Date(
System.currentTimeMillis()), new Date(
System.currentTimeMillis() + 30 * 365 * 24 * 60 * 60
* 1000), pk10Holder.getSubject(), keyInfo);
ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
.build(foo);
X509CertificateHolder holder = myCertificateGenerator.build(sigGen);
X509CertificateStructure eeX509CertificateStructure = holder.toASN1Structure();
//in newer version of BC such as 1.51, this is
//org.spongycastle.asn1.x509.Certificate eeX509CertificateStructure = holder.toASN1Structure();
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
// Read Certificate
InputStream is1 = new ByteArrayInputStream(eeX509CertificateStructure.getEncoded());
X509Certificate theCert = (X509Certificate) cf.generateCertificate(is1);
is1.close();
return theCert;
//return null;
}
As you can see, I've generated the request outside this method, but passed it in. Then, I have the PKCS10CertificationRequestHolder to accept this as a constructor arg.
Next, in the X509v3CertificateBuilder arguments, you'll see the pk10Holder.getSubject - this is apparently all you need? If something is missing, please let me know too!!! It worked for me. The cert I generated correctly had the DN info I needed.
Wikipedia has a killer section on PKCS - http://en.wikipedia.org/wiki/PKCS
| Bouncy Castle | 7,230,330 | 37 |
I've been looking around for about a week+ to implement a method I have in mind. I have came across (and read) many articles on all of these different methods, but I am still left confused, so I was hoping maybe someone can spread their knowledge of these topics so I can more easily go about creating my sought after method and implementing it in Android.
My "sought after" method:
Must generate RSA Public & Private keys
Public must have PKCS#1 padding
Must be RSA 2048
Return Public Key in Byte array
Apparently you can go about it four ways:
Standard Java
Bouncy Castle
Spongy Castle (Android Friendly?)
JSch
Since I'm very new to security and Java as a whole I was wondering if someone could finally give a good clear cut explanation of all of this.
Below are the ways I have tried to implement my sought after method (mentioned above) in the 4 different programming methods. If I don't know something it's because I can't figure out through the respective documentation. Please feel free to correct me.
1. Standard Java (Not sure if PKCS#1):
public byte[] returnPublicKeyInBytes() throws NoSuchAlgorithmException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair keyPair = kpg.genKeyPair();
byte[] pri = keyPair.getPrivate().getEncoded();
byte[] pub = keyPair.getPublic().getEncoded();
return pub;
}
2. Bouncy Castle (Not yet functional =/ Ideas?):
public byte[] returnPublicKeyInBytes() throws NoSuchAlgorithmException {
RSAKeyPairGenerator r = new RSAKeyPairGenerator();
r.init(new KeyGenerationParameters(new SecureRandom(),4096));
AsymmetricCipherKeyPair keys = r.generateKeyPair();
CipherParameters pri = keys.getPrivate();
CipherParameters pub = keys.getPublic();
byte[] pubbyte = pub.toString().getBytes();
return pubbyte; //NOT WORKING
}
3. SpongyCastle (Havn't started it/Same as Bouncy Castle?):
4. JSch (Very Dis-functional/Work in progress)
public byte[] returnPublicKeyInBytes(JSch jSch) {
try {
KeyPair keyPair = KeyPair.genKeyPair(jSch, KeyPair.RSA);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
keyPair.writePrivateKey(bs);
jSch.addIdentity("Generated", bs.toByteArray(), keyPair.getPublicKeyBlob(), null);
return keyPair.getPublicKeyBlob();
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
I'd like this to really become more of a resource for anyone that has problems with RSA key generation in Android (like I, and many others have had).
I feel that Bouncy Castle has very little information about it's API which makes it extremely difficult for a beginner (like me) to understand it. From my research, people use Bouncy Castle in Java instead of the built-in security provider because Bouncy Castle is much more robust. Using Bouncy Castle in Android is not desired because it "ships with a crippled version of Bouncy Castle" which may be prone to errors. Spongy Castle is simply a repackage of Bouncy Castle.
To this end, I will ask my final question of, which method should be used for Android?
Update
I hope someone can answer this later on. As for what I did to solve my problem was to just use NDK.
| It is complicated, but I'll try to explain as best I can. I think I'll start with Java. My discussion is geared to Java 6, I'm not sure what has changed in Java 7.
Java' built-in cryptography is available through the Java Cryptography Extension (JCE). This extension has two parts to it, the application API and service provider API. The application API is the part you interact with. You use the getInstance() factory methods of various crypto classes. The service provider aspect is more confusing for the average programmer. They don't care about how the crypto is implemented, they just want something that works. But under the hood there are the crypto provider classes that do the actual work. If you look at the arguments to getInstance() you'll see that you can specify the provider if you want. Why would you ever want to? Maybe you have paid $$$ for an optimized commercial implementation of RSA, so you want to use that one. Perhaps one provider has a FIPS certificate or some other certification that you need for your app. Then you would specify that provider. Sun/Oracle ships their Java environment with several providers that together comprise the default provider set for their Java environment. Don't look at them too carefully because they are overlapping and thus confusing due somewhat to historical artifacts. Basically, when using Oracle Java you ask for some crypto like a KeyPairGenerator through KeyPairGenerator.getInstance("RSA"); you're going to get an appropriate class instance from one of these providers.
Next, lets look at bouncycastle. The bouncycastle library consists of two parts. One is their unique crypto library whose API you have experimented with in your #2 above. The second part is a lot of glue code to allow this library to be used as crypt provider for the JCE. This means you as a programmer have a choice as to how you use the bouncycastle crypto library. You can use their API directly as in #2 above. Or, you can use the JCE api but explicitly specify the bouncycastle implementation by something like KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");.
If you prefer to use the unique bouncycastle API directly (they call it their "lightweight API") then you have no need for all the glue code used to make it work as a JCE provider. For this bouncycastle does provide a download of just the lightweight API classes.
And now, at last, we look at Android's implementation. Google didn't license Oracle's Java source code, so they didn't have any of Oracle's JCE providers. They had to provide their own providers. Since bouncycastle had all the code needed, and was open source and liberally licensed, Google/Android chose to use bouncycastle as the basis for their default JCE provider. But, Android has made no effort to make available the unique lightweight API for Android programmers. They expect you to use these classes solely through the JCE. They have modified the bouncycastle code to tune it for Android. They fact that you can find and maybe use some of the lightweight API directly on Android is simply a side-effect of the fact that it's there under the hood. And not everything is there. Some have described this situation as "bouncycastle on Android is crippled".
To actually provide a full featured version of the bouncycastle library on Android some developers produced something called the Spongycastle library. It is nothing more than the bouncycastle library modified so that it can work on Android. The chief modification was to change the package names from org.bouncycastle.* to org.spongycastle.* to prevent namespace conflicts.
So what should you use? That depends on what you want to do, what your portability needs are, what your style preferences are, and what you crypto skill level is. In general, when you are using these libraries you are using crypto at fairly low level. You are concentrating at how to do it (use RSA for key transport, use AES for message encryption, use HMAC-SHA256 for message integrity, etc.) versus what to do (I want to send an encrypted message to a recipient via an email-like mechanism). Obviously, if you can you should stick to higher-level libraries that directly solve your problem. These libraries already understand what PKCS#1 is and how to use it as part of larger and more complete protocols.
| Bouncy Castle | 9,962,825 | 35 |
I am using bcmail-jdk16-1.46.jar and bcprov-jdk16-1.46.jar (Bouncycastle libraries) to sign a string and then verify the signature.
This is my code to sign a string:
package my.package;
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.CMSTypedData;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.util.Store;
import sun.misc.BASE64Encoder;
public class SignMessage {
static final String KEYSTORE_FILE = "keys/certificates.p12";
static final String KEYSTORE_INSTANCE = "PKCS12";
static final String KEYSTORE_PWD = "test";
static final String KEYSTORE_ALIAS = "Key1";
public static void main(String[] args) throws Exception {
String text = "This is a message";
Security.addProvider(new BouncyCastleProvider());
KeyStore ks = KeyStore.getInstance(KEYSTORE_INSTANCE);
ks.load(new FileInputStream(KEYSTORE_FILE), KEYSTORE_PWD.toCharArray());
Key key = ks.getKey(KEYSTORE_ALIAS, KEYSTORE_PWD.toCharArray());
//Sign
PrivateKey privKey = (PrivateKey) key;
Signature signature = Signature.getInstance("SHA1WithRSA", "BC");
signature.initSign(privKey);
signature.update(text.getBytes());
//Build CMS
X509Certificate cert = (X509Certificate) ks.getCertificate(KEYSTORE_ALIAS);
List certList = new ArrayList();
CMSTypedData msg = new CMSProcessableByteArray(signature.sign());
certList.add(cert);
Store certs = new JcaCertStore(certList);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privKey);
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert));
gen.addCertificates(certs);
CMSSignedData sigData = gen.generate(msg, false);
BASE64Encoder encoder = new BASE64Encoder();
String signedContent = encoder.encode((byte[]) sigData.getSignedContent().getContent());
System.out.println("Signed content: " + signedContent + "\n");
String envelopedData = encoder.encode(sigData.getEncoded());
System.out.println("Enveloped data: " + envelopedData);
}
}
Now, the EnvelopedData output will be used in the process to verify the signature:
package my.package;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Iterator;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Store;
import org.bouncycastle.util.encoders.Base64;
public class VerifySignature {
public static void main(String[] args) throws Exception {
String envelopedData = "MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIAwggLQMIIC" +
"OQIEQ479uzANBgkqhkiG9w0BAQUFADCBrjEmMCQGCSqGSIb3DQEJARYXcm9zZXR0YW5ldEBtZW5k" +
"ZWxzb24uZGUxCzAJBgNVBAYTAkRFMQ8wDQYDVQQIEwZCZXJsaW4xDzANBgNVBAcTBkJlcmxpbjEi" +
"MCAGA1UEChMZbWVuZGVsc29uLWUtY29tbWVyY2UgR21iSDEiMCAGA1UECxMZbWVuZGVsc29uLWUt" +
"Y29tbWVyY2UgR21iSDENMAsGA1UEAxMEbWVuZDAeFw0wNTEyMDExMzQyMTlaFw0xOTA4MTAxMzQy" +
"MTlaMIGuMSYwJAYJKoZIhvcNAQkBFhdyb3NldHRhbmV0QG1lbmRlbHNvbi5kZTELMAkGA1UEBhMC" +
"REUxDzANBgNVBAgTBkJlcmxpbjEPMA0GA1UEBxMGQmVybGluMSIwIAYDVQQKExltZW5kZWxzb24t" +
"ZS1jb21tZXJjZSBHbWJIMSIwIAYDVQQLExltZW5kZWxzb24tZS1jb21tZXJjZSBHbWJIMQ0wCwYD" +
"VQQDEwRtZW5kMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+X1g6JvbdwJI6mQMNT41GcycH" +
"UbwCFWKJ4qHDaHffz3n4h+uQJJoQvc8yLTCfnl109GB0yL2Y5YQtTohOS9IwyyMWBhh77WJtCN8r" +
"dOfD2DW17877te+NlpugRvg6eOH6np9Vn3RZODVxxTyyJ8pI8VMnn13YeyMMw7VVaEO5hQIDAQAB" +
"MA0GCSqGSIb3DQEBBQUAA4GBALwOIc/rWMAANdEh/GgO/DSkVMwxM5UBr3TkYbLU/5jg0Lwj3Y++" +
"KhumYSrxnYewSLqK+JXA4Os9NJ+b3eZRZnnYQ9eKeUZgdE/QP9XE04y8WL6ZHLB4sDnmsgVaTU+p" +
"0lFyH0Te9NyPBG0J88109CXKdXCTSN5gq0S1CfYn0staAAAxggG9MIIBuQIBATCBtzCBrjEmMCQG" +
"CSqGSIb3DQEJARYXcm9zZXR0YW5ldEBtZW5kZWxzb24uZGUxCzAJBgNVBAYTAkRFMQ8wDQYDVQQI" +
"EwZCZXJsaW4xDzANBgNVBAcTBkJlcmxpbjEiMCAGA1UEChMZbWVuZGVsc29uLWUtY29tbWVyY2Ug" +
"R21iSDEiMCAGA1UECxMZbWVuZGVsc29uLWUtY29tbWVyY2UgR21iSDENMAsGA1UEAxMEbWVuZAIE" +
"Q479uzAJBgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG9w0BCQUx" +
"DxcNMTMwNTIxMDE1MDUzWjAjBgkqhkiG9w0BCQQxFgQU8mE6gw6iudxLUc9379lWK0lUSWcwDQYJ" +
"KoZIhvcNAQEBBQAEgYB5mVhqJu1iX9nUqfqk7hTYJb1lR/hQiCaxruEuInkuVTglYuyzivZjAR54" +
"zx7Cfm5lkcRyyxQ35ztqoq/V5JzBa+dYkisKcHGptJX3CbmmDIa1s65mEye4eLS4MTBvXCNCUTb9" +
"STYSWvr4VPenN80mbpqSS6JpVxjM0gF3QTAhHwAAAAAAAA==";
Security.addProvider(new BouncyCastleProvider());
CMSSignedData cms = new CMSSignedData(Base64.decode(envelopedData.getBytes()));
Store store = cms.getCertificates();
SignerInformationStore signers = cms.getSignerInfos();
Collection c = signers.getSigners();
Iterator it = c.iterator();
while (it.hasNext()) {
SignerInformation signer = (SignerInformation) it.next();
Collection certCollection = store.getMatches(signer.getSID());
Iterator certIt = certCollection.iterator();
X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {
System.out.println("verified");
}
}
}
}
Everything works fine until signer.verify(..) due to the following Exception:
Exception in thread "main" org.bouncycastle.cms.CMSSignerDigestMismatchException: message-digest attribute value does not match calculated value
at org.bouncycastle.cms.SignerInformation.doVerify(Unknown Source)
at org.bouncycastle.cms.SignerInformation.verify(Unknown Source)
at my.package.VerifySignature.main(VerifySignature.java:64)
Can someone please give me a hint of what could be happening?
PS. If someone wants to test above code you will need the test certificate file that I am using to replicate this, just download it from here:
https://www.dropbox.com/s/zs4jo1a86v8qamw/certificates.p12?dl=0
| The
gen.generate(msg, false)
means the signed data is not encapsulated in the signature. This is fine if you want to create a detached signature, but it does mean that when you go to verify the SignedData you have to use the CMSSignedData constructor that takes a copy of the data as well - in this case the code is using the single argument constructor which has to assume the signed data was encapsulated (so for this case will be empty), with the result that the attempt at verification is failing.
| Bouncy Castle | 16,662,408 | 34 |
How can one programmatically obtain a KeyStore from a PEM file containing both a certificate and a private key? I am attempting to provide a client certificate to a server in an HTTPS connection. I have confirmed that the client certificate works if I use openssl and keytool to obtain a jks file, which I load dynamically. I can even get it to work by dynamically reading in a p12 (PKCS12) file.
I'm looking into using the PEMReader class from BouncyCastle, but I can't get past some errors. I'm running the Java client with the -Djavax.net.debug=all option and Apache web server with the debug LogLevel. I'm not sure what to look for though. The Apache error log indicates:
...
OpenSSL: Write: SSLv3 read client certificate B
OpenSSL: Exit: error in SSLv3 read client certificate B
Re-negotiation handshake failed: Not accepted by client!?
The Java client program indicates:
...
main, WRITE: TLSv1 Handshake, length = 48
main, waiting for close_notify or alert: state 3
main, Exception while waiting for close java.net.SocketException: Software caused connection abort: recv failed
main, handling exception: java.net.SocketException: Software caused connection abort: recv failed
%% Invalidated: [Session-3, TLS_RSA_WITH_AES_128_CBC_SHA]
main, SEND TLSv1 ALERT: fatal, description = unexpected_message
...
The client code :
public void testClientCertPEM() throws Exception {
String requestURL = "https://mydomain/authtest";
String pemPath = "C:/Users/myusername/Desktop/client.pem";
HttpsURLConnection con;
URL url = new URL(requestURL);
con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(getSocketFactoryFromPEM(pemPath));
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(false);
con.connect();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
while((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
con.disconnect();
}
public SSLSocketFactory getSocketFactoryFromPEM(String pemPath) throws Exception {
Security.addProvider(new BouncyCastleProvider());
SSLContext context = SSLContext.getInstance("TLS");
PEMReader reader = new PEMReader(new FileReader(pemPath));
X509Certificate cert = (X509Certificate) reader.readObject();
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(null);
keystore.setCertificateEntry("alias", cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keystore, null);
KeyManager[] km = kmf.getKeyManagers();
context.init(km, null, null);
return context.getSocketFactory();
}
I noticed the server is outputing SSLv3 in the log while the client is TLSv1. If I add the system property -Dhttps.protocols=SSLv3 then the client will use SSLv3 as well, but I get the same error message. I've also tried adding -Dsun.security.ssl.allowUnsafeRenegotiation=true with no change in outcome.
I've googled around and the usual answer for this question is to just use openssl and keytool first. In my case I need to read the PEM directly on the fly. I'm actually porting a C++ program that already does this, and frankly, I'm very surprised how difficult it is to do this in Java. The C++ code:
curlpp::Easy request;
...
request.setOpt(new Options::Url(myurl));
request.setOpt(new Options::SslVerifyPeer(false));
request.setOpt(new Options::SslCertType("PEM"));
request.setOpt(new Options::SslCert(cert));
request.perform();
| I figured it out. The problem is that the X509Certificate by itself isn't sufficient. I needed to put the private key into the dynamically generated keystore as well. It doesn't seem that BouncyCastle PEMReader can handle a PEM file with both cert and private key all in one go, but it can handle each piece separately. I can read the PEM into memory myself and break it into two separate streams and then feed each one to a separate PEMReader. Since I know that the PEM files I'm dealing with will have the cert first and the private key second I can simplify the code at the cost of robustness. I also know that the END CERTIFICATE delimiter will always be surrounded with five hyphens. The implementation that works for me is:
protected static SSLSocketFactory getSocketFactoryPEM(String pemPath) throws Exception {
Security.addProvider(new BouncyCastleProvider());
SSLContext context = SSLContext.getInstance("TLS");
byte[] certAndKey = fileToBytes(new File(pemPath));
String delimiter = "-----END CERTIFICATE-----";
String[] tokens = new String(certAndKey).split(delimiter);
byte[] certBytes = tokens[0].concat(delimiter).getBytes();
byte[] keyBytes = tokens[1].getBytes();
PEMReader reader;
reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(certBytes)));
X509Certificate cert = (X509Certificate)reader.readObject();
reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(keyBytes)));
PrivateKey key = (PrivateKey)reader.readObject();
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(null);
keystore.setCertificateEntry("cert-alias", cert);
keystore.setKeyEntry("key-alias", key, "changeit".toCharArray(), new Certificate[] {cert});
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keystore, "changeit".toCharArray());
KeyManager[] km = kmf.getKeyManagers();
context.init(km, null, null);
return context.getSocketFactory();
}
Update: It seems this can be done without BouncyCastle:
byte[] certAndKey = fileToBytes(new File(pemPath));
byte[] certBytes = parseDERFromPEM(certAndKey, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");
byte[] keyBytes = parseDERFromPEM(certAndKey, "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----");
X509Certificate cert = generateCertificateFromDER(certBytes);
RSAPrivateKey key = generatePrivateKeyFromDER(keyBytes);
...
protected static byte[] parseDERFromPEM(byte[] pem, String beginDelimiter, String endDelimiter) {
String data = new String(pem);
String[] tokens = data.split(beginDelimiter);
tokens = tokens[1].split(endDelimiter);
return DatatypeConverter.parseBase64Binary(tokens[0]);
}
protected static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey)factory.generatePrivate(spec);
}
protected static X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException {
CertificateFactory factory = CertificateFactory.getInstance("X.509");
return (X509Certificate)factory.generateCertificate(new ByteArrayInputStream(certBytes));
}
| Bouncy Castle | 12,501,117 | 30 |
Apparently Spongy Castle is the Android alternative to using a full version of Bouncy Castle.
However, on importing the jar I'm getting all kinds of "cannot be resolved" errors because it relies on packages not included with Android, primarily javax.mail, javax.activation, and javax.awt.datatransfer.
So what's the best way around this? Responses to this question and this indicate those packages shouldn't be used at all, and this popular question doesn't even consider finding a way to get AWT back. So how is Spongy Castle relying on them? People are using Spongy Castle, right?
| If you are using gradle, then you can just specify your dependencies in build.gradle file like this:
dependencies {
....
compile 'com.madgag.spongycastle:core:1.54.0.0'
compile 'com.madgag.spongycastle:prov:1.54.0.0'
compile 'com.madgag.spongycastle:pkix:1.54.0.0'
compile 'com.madgag.spongycastle:pg:1.54.0.0'
}
You can find out the latest version of the library here.
Don't forget to insert it as a security provider in your app.
static {
Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
}
| Bouncy Castle | 6,898,801 | 29 |
I need to encrypt data in C# in order to pass it to Java. The Java code belongs to a 3rd party but I have been given the relevant source, so I decided that as the Java uses the Bouncy Castle libs, I will use the C# port.
Decryption works fine. However, decryption works only when I use the encrypt using the private key, and not with the public key. When using the public key, decryption fails with unknown block type.
Obviously the encryption inside the RsaEncryptWithPrivate uses the public key when encrypting, so I do not get why the two encryption methods are not functionally identical:
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.OpenSsl;
public class EncryptionClass
{
public string RsaEncryptWithPublic(string clearText
, string publicKey)
{
var bytesToEncrypt = Encoding.UTF8.GetBytes(clearText);
var encryptEngine = new Pkcs1Encoding(new RsaEngine());
using (var txtreader = new StringReader(publicKey))
{
var keyParameter = (AsymmetricKeyParameter)new PemReader(txtreader).ReadObject();
encryptEngine.Init(true, keyParameter);
}
var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));
return encrypted;
}
public string RsaEncryptWithPrivate(string clearText
, string privateKey)
{
var bytesToEncrypt = Encoding.UTF8.GetBytes(clearText);
var encryptEngine = new Pkcs1Encoding(new RsaEngine());
using (var txtreader = new StringReader(privateKey))
{
var keyPair = (AsymmetricCipherKeyPair)new PemReader(txtreader).ReadObject();
encryptEngine.Init(true, keyPair.Public);
}
var encrypted= Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));
return encrypted;
}
// Decryption:
public string RsaDecrypt(string base64Input
, string privateKey)
{
var bytesToDecrypt = Convert.FromBase64String(base64Input);
//get a stream from the string
AsymmetricCipherKeyPair keyPair;
var decryptEngine = new Pkcs1Encoding(new RsaEngine());
using ( var txtreader = new StringReader(privateKey) )
{
keyPair = (AsymmetricCipherKeyPair) new PemReader(txtreader).ReadObject();
decryptEngine.Init(false, keyPair.Private);
}
var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));
return decrypted;
}
}
// In my test project
[Test()]
public void EncryptTest()
{
// Set up
var input = "Perceived determine departure explained no forfeited";
var enc = new EncryptionClass();
var publicKey = "-----BEGIN PUBLIC KEY----- // SNIPPED // -----END PUBLIC KEY-----";
var privateKey = "-----BEGIN PRIVATE KEY----- // SNIPPED // -----END PRIVATE KEY-----";
// Encrypt it
var encryptedWithPublic = enc.RsaEncryptWithPublic(input, publicKey);
var encryptedWithPrivate = enc.RsaEncryptWithPrivate(input, privateKey);
// Decrypt
var outputWithPublic = payUEnc.RsaDecrypt(encryptedWithPrivate, privateKey);
// Throws error: "unknown block type"
var outputWithPrivate = payUEnc.RsaDecrypt(encryptedWithPrivate, _privateKey);
// returns the correct decrypted text, "Perceived determine departure explained no forfeited"
// Assertion
Assert.AreEqual(outputWithPrivate, input); // This is true
}
Incidentally the Java decryption exhibits the same issue - when encrypted with the public key only, it fails.
I'm very new to cryptography, so I'm sure I'm doing something very simple wrong in the RsaEncryptWithPublic method.
EDIT:
I've also added a unit test which proves that the public key is equal to the public key that is extracted from the private key:
[Test()]
public void EncryptCompareTest()
{
AsymmetricKeyParameter keyParameterFromPub;
AsymmetricKeyParameter keyParameterFromPriv;
AsymmetricCipherKeyPair keyPair;
using (var txtreader = new StringReader(_publicKey))
{
keyParameterFromPub = (AsymmetricKeyParameter)new PemReader(txtreader).ReadObject();
}
using (var txtreader = new StringReader(_privateKey))
{
keyPair = (AsymmetricCipherKeyPair)new PemReader(txtreader).ReadObject();
keyParameterFromPriv = keyPair.Public;
}
Assert.AreEqual(keyParameterFromPub, keyParameterFromPriv); // returns true;
}
| There are some errors in OP's code. I made few changes. Here is what I got running.
public class TFRSAEncryption
{
public string RsaEncryptWithPublic(string clearText, string publicKey)
{
var bytesToEncrypt = Encoding.UTF8.GetBytes(clearText);
var encryptEngine = new Pkcs1Encoding(new RsaEngine());
using (var txtreader = new StringReader(publicKey))
{
var keyParameter = (AsymmetricKeyParameter)new PemReader(txtreader).ReadObject();
encryptEngine.Init(true, keyParameter);
}
var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));
return encrypted;
}
public string RsaEncryptWithPrivate(string clearText, string privateKey)
{
var bytesToEncrypt = Encoding.UTF8.GetBytes(clearText);
var encryptEngine = new Pkcs1Encoding(new RsaEngine());
using (var txtreader = new StringReader(privateKey))
{
var keyPair = (AsymmetricCipherKeyPair)new PemReader(txtreader).ReadObject();
encryptEngine.Init(true, keyPair.Private);
}
var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));
return encrypted;
}
// Decryption:
public string RsaDecryptWithPrivate(string base64Input, string privateKey)
{
var bytesToDecrypt = Convert.FromBase64String(base64Input);
AsymmetricCipherKeyPair keyPair;
var decryptEngine = new Pkcs1Encoding(new RsaEngine());
using (var txtreader = new StringReader(privateKey))
{
keyPair = (AsymmetricCipherKeyPair)new PemReader(txtreader).ReadObject();
decryptEngine.Init(false, keyPair.Private);
}
var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));
return decrypted;
}
public string RsaDecryptWithPublic(string base64Input, string publicKey)
{
var bytesToDecrypt = Convert.FromBase64String(base64Input);
var decryptEngine = new Pkcs1Encoding(new RsaEngine());
using (var txtreader = new StringReader(publicKey))
{
var keyParameter = (AsymmetricKeyParameter)new PemReader(txtreader).ReadObject();
decryptEngine.Init(false, keyParameter);
}
var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));
return decrypted;
}
}
class Program
{
static void Main(string[] args)
{
// Set up
var input = "Perceived determine departure explained no forfeited";
var enc = new TFRSAEncryption();
var publicKey = "-----BEGIN PUBLIC KEY----- // Base64 string omitted // -----END PUBLIC KEY-----";
var privateKey = "-----BEGIN PRIVATE KEY----- // Base64 string omitted// -----END PRIVATE KEY-----";
// Encrypt it
var encryptedWithPublic = enc.RsaEncryptWithPublic(input, publicKey);
var encryptedWithPrivate = enc.RsaEncryptWithPrivate(input, privateKey);
// Decrypt
var output1 = enc.RsaDecryptWithPrivate(encryptedWithPublic, privateKey);
var output2 = enc.RsaDecryptWithPublic(encryptedWithPrivate, publicKey);
Console.WriteLine(output1 == output2 && output2 == input);
Console.Read();
}
}
| Bouncy Castle | 28,086,321 | 29 |
So after CodingHorror's fun with encryption and the thrashing comments, we are reconsidering doing our own encryption.
In this case, we need to pass some information that identifies a user to a 3rd party service which will then call back to a service on our website with the information plus a hash.
The 2nd service looks up info on that user and then passes it back to the 3rd party service.
We want to encrypt this user information going into the 3rd party service and decrypt it after it comes out. So it is not a long lived encryption.
On the coding horror article, Coda Hale recommended BouncyCastle and a high level abstraction in the library to do the encryption specific to a particular need.
My problem is that the BouncyCastle namespaces are huge and the documentation is non-existant. Can anyone point me to this high level abstraction library? (Or another option besides BouncyCastle?)
| High level abstraction? I suppose the highest level abstractions in the Bouncy Castle library would include:
The BlockCipher interface (for symmetric ciphers)
The BufferedBlockCipher class
The AsymmetricBlockCipher interface
The BufferedAsymmetricBlockCipher class
The CipherParameters interface (for initializing the block ciphers and asymmetric block ciphers)
I am mostly familiar with the Java version of the library. Perhaps this code snippet will offer you a high enough abstraction for your purposes (example is using AES-256 encryption):
public byte[] encryptAES256(byte[] input, byte[] key) throws InvalidCipherTextException {
assert key.length == 32; // 32 bytes == 256 bits
CipherParameters cipherParameters = new KeyParameter(key);
/*
* A full list of BlockCiphers can be found at http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/BlockCipher.html
*/
BlockCipher blockCipher = new AESEngine();
/*
* Paddings available (http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/paddings/BlockCipherPadding.html):
* - ISO10126d2Padding
* - ISO7816d4Padding
* - PKCS7Padding
* - TBCPadding
* - X923Padding
* - ZeroBytePadding
*/
BlockCipherPadding blockCipherPadding = new ZeroBytePadding();
BufferedBlockCipher bufferedBlockCipher = new PaddedBufferedBlockCipher(blockCipher, blockCipherPadding);
return encrypt(input, bufferedBlockCipher, cipherParameters);
}
public byte[] encrypt(byte[] input, BufferedBlockCipher bufferedBlockCipher, CipherParameters cipherParameters) throws InvalidCipherTextException {
boolean forEncryption = true;
return process(input, bufferedBlockCipher, cipherParameters, forEncryption);
}
public byte[] decrypt(byte[] input, BufferedBlockCipher bufferedBlockCipher, CipherParameters cipherParameters) throws InvalidCipherTextException {
boolean forEncryption = false;
return process(input, bufferedBlockCipher, cipherParameters, forEncryption);
}
public byte[] process(byte[] input, BufferedBlockCipher bufferedBlockCipher, CipherParameters cipherParameters, boolean forEncryption) throws InvalidCipherTextException {
bufferedBlockCipher.init(forEncryption, cipherParameters);
int inputOffset = 0;
int inputLength = input.length;
int maximumOutputLength = bufferedBlockCipher.getOutputSize(inputLength);
byte[] output = new byte[maximumOutputLength];
int outputOffset = 0;
int outputLength = 0;
int bytesProcessed;
bytesProcessed = bufferedBlockCipher.processBytes(
input, inputOffset, inputLength,
output, outputOffset
);
outputOffset += bytesProcessed;
outputLength += bytesProcessed;
bytesProcessed = bufferedBlockCipher.doFinal(output, outputOffset);
outputOffset += bytesProcessed;
outputLength += bytesProcessed;
if (outputLength == output.length) {
return output;
} else {
byte[] truncatedOutput = new byte[outputLength];
System.arraycopy(
output, 0,
truncatedOutput, 0,
outputLength
);
return truncatedOutput;
}
}
Edit: Whoops, I just read the article you linked to. It sounds like he is talking about even higher level abstractions than I thought (e.g., "send a confidential message"). I am afraid I don't quite understand what he is getting at.
| Bouncy Castle | 885,485 | 28 |
I'm trying to use bouncycastle to encrypt a file using a public key.
I've registered the provider programatically:
Security.addProvider(new BouncyCastleProvider());
I created the public key object successfully.
when i get to encrypting the file using a PGPEncryptedDataGenerator and the key I get a ClassNotFound exception.
It seems the provider can't find this class at runtime, though I know for sure I have its jar...
I'm running my app on tomcat.
Using maven to handle dependencies - the bouncy castle jars I put are bcpg, bcprov, bcmail, bctsp.
I tried using both the 1.4 and the 1.6 versions without success.
I used the "dependency hierarchy" in maven plugin for eclipse and exclusions in the pom to make sure that there are no multiple versions of bouncycastle in my project.
This is the stack trace:
org.bouncycastle.openpgp.PGPException: exception encrypting session key
at org.bouncycastle.openpgp.PGPEncryptedDataGenerator.open(Unknown Source)
at org.bouncycastle.openpgp.PGPEncryptedDataGenerator.open(Unknown Source)
.....(web application stack trace and uninteresting stuff).....
Caused by: java.security.NoSuchAlgorithmException: No such algorithm: ElGamal/ECB/PKCS1Padding
at javax.crypto.Cipher.getInstance(DashoA13*..)
at org.bouncycastle.openpgp.PGPEncryptedDataGenerator$PubMethod.addSessionInfo(Unknown Source)
... 42 more
Caused by: java.security.NoSuchAlgorithmException: class configured for Cipher(provider: BC)cannot be found.
at java.security.Provider$Service.getImplClass(Provider.java:1268)
at java.security.Provider$Service.newInstance(Provider.java:1220)
... 44 more
Caused by: java.lang.ClassNotFoundException: org.bouncycastle.jce.provider.JCEElGamalCipher$NoPadding
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
at java.security.Provider$Service.getImplClass(Provider.java:1262)
| You have a BouncyCastle Security provider installation problem, you need to either
Add BouncyCastle to the JRE/JDK $JAVA_HOME/jre/lib/security/java.security file as a provider (be sure that you add it to the JRE you use when running, eg. if you have multiple JRE's/JDK's installed)
eg.
security.provider.2=org.bouncycastle.jce.provider.BouncyCastleProvider
(and renumber the security providers below it - don't put it as the highest priority provider).
or you can add BouncyCastle programmatically, as you were trying to do above, but in this case the security policy $JAVA_HOME/jre/lib/security/java.policy should be "unlimited" (you can probably download an unlimited policy file from the Java homepage).
| Bouncy Castle | 6,908,696 | 28 |
UPDATED 2019: Bouncycastle now support PBKDF2-HMAC-SHA256 since bouncycastle 1.60
Is there any reliable implementation of PBKDF2-HMAC-SHA256 for JAVA?
I used to encrypt using bouncycastle but it does not provide PBKDF2WithHmacSHA256'.
I do not want to write crypto module by myself.
Could you recommend any alternative library or algorithm (if i can stick with bouncycastle)
(here are the algorithms that bouncycastle supports)
http://www.bouncycastle.org/specifications.html
| Using BouncyCastle classes directly:
PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
gen.init("password".getBytes("UTF-8"), "salt".getBytes(), 4096);
byte[] dk = ((KeyParameter) gen.generateDerivedParameters(256)).getKey();
| Bouncy Castle | 22,580,853 | 27 |
I use BouncyCastle for encryption in my application. When I run it standalone, everything works fine. However, if I put it in the webapp and deploy on JBoss server, I get a following error:
javax.servlet.ServletException: error constructing MAC: java.security.NoSuchProviderException: JCE cannot authenticate the provider BC
(...)
root cause
java.lang.Exception: error constructing MAC: java.security.NoSuchProviderException: JCE cannot authenticate the provider BC
(...)
root cause
java.io.IOException: error constructing MAC: java.security.NoSuchProviderException: JCE cannot authenticate the provider BC
org.bouncycastle.jce.provider.JDKPKCS12KeyStore.engineLoad(Unknown Source)
java.security.KeyStore.load(Unknown Source)
Here is a part of the code that causes this error:
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null)
{
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
// Read the Private Key
KeyStore ks = KeyStore.getInstance("PKCS12", BouncyCastleProvider.PROVIDER_NAME);
ks.load(new FileInputStream(certificatePath), privateKeyPassword.toCharArray());
And maven dependency:
<dependency>
<groupId>bouncycastle</groupId>
<artifactId>bcmail-jdk16</artifactId>
<version>140</version>
</dependency>
Do you know how could I deploy it?
| For JBoss AS7 bouncy castle needs to be deployed as a server module. This replaces the server/default/lib mechanism of earlier versions (as mentioned in Gergely Bacso's answer).
JBoss AS7 uses jdk1.6+. When using JBoss AS7 with jdk1.6 we need to make sure we are using bcprov-jdk16.
Create a Jboss module (a folder $JBOSS_HOME/modules/org/bouncycastle/main).
Put the bouncy castle jars that you want to be globally available in it, along with a module.xml file that looks like this:
<module xmlns="urn:jboss:module:1.1" name="org.bouncycastle">
<resources>
<resource-root path="bcprov-jdk16-1.46.jar"/>
</resources>
<dependencies>
<module name="javax.api" slot="main" export="true"/>
</dependencies>
</module>
Once you have setup the module you need to make it available to your deployments. There are two ways:
1. Globally via standalone.xml
In $JBOSS_HOME/standalone/configuration/standalone.xml replace
<subsystem xmlns="urn:jboss:domain:ee:1.0"/>
with
<subsystem xmlns="urn:jboss:domain:ee:1.0">
<global-modules>
<module name="org.bouncycastle" slot="main"/>
</global-modules>
</subsystem>
The jar libraries will now be available across all applications (and this will "emulate" adding to the classpath as was possible in jboss 4,5,6 etc)
2. For a specific deployment (preferred)
Add a module dependency entry to the ear's META-INF/jboss-deployment-structure.xml file, under the section, eg:
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.1">
<deployment>
<dependencies>
<module name="org.bouncycastle" slot="main" export="true" />
</dependencies>
</deployment>
</jboss-deployment-structure>
| Bouncy Castle | 9,534,512 | 26 |
Update: Partial solution available on Git
EDIT: A compiled version of this is available at https://github.com/makerofthings7/Bitcoin-MessageSignerVerifier
Please note that the message to be verified must have Bitcoin Signed Message:\n as a prefix. Source1 Source2
There is something wrong in the C# implementation that I can probably correct from this Python implementation
It seems to have a problem with actually coming up with the correct Base 58 address.
I have the following message, signature, and Base58 address below. I intend to extract the key from the signature, hash that key, and compare the Base58 hashes.
My problem is: How do I extract the key from the signature? (Edit I found the c++ code at the bottom of this post, need it in Bouncy Castle / or C#)
Message
StackOverflow test 123
Signature
IB7XjSi9TdBbB3dVUK4+Uzqf2Pqk71XkZ5PUsVUN+2gnb3TaZWJwWW2jt0OjhHc4B++yYYRy1Lg2kl+WaiF+Xsc=
Base58 Bitcoin address "hash"
1Kb76YK9a4mhrif766m321AMocNvzeQxqV
Since the Base58 Bitcoin address is just a hash, I can't use it for validation of a Bitcoin message. However, it is possible to extract the public key from a signature.
Edit: I'm emphasizing that I'm deriving the Public key from the signature itself, and not from the Base58 public key hash. If I want to (and I actually do want to) I should be able to convert these public key bits into the Base58 hash. I don't need assistance in doing this, I just need help in extracting the public key bits and verifying the signature.
Question
In the Signature above, what format is this signature in? PKCS10? (Answer: no, it's proprietary as described here)
how do I extract the public key in Bouncy Castle?
What is the correct way to verify the signature? (assume that I already know how to convert the Public Key bits into a hash that equals the Bitcoin hash above)
Prior research
This link describes how to use ECDSA curves, and the following code will allow me to convert a public key into a BC object, but I'm unsure on how to get the point Q from the signature.
In the sample below Q is the hard coded value
Org.BouncyCastle.Asn1.X9.X9ECParameters ecp = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
ECDomainParameters params = new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H);
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(
ecp .curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q
params);
PublicKey pubKey = f.generatePublic(pubKeySpec);
var signer = SignerUtilities.GetSigner("ECDSA"); // possibly similar to SHA-1withECDSA
signer.Init(false, pubKey);
signer.BlockUpdate(plainTextAsBytes, 0, plainTextAsBytes.Length);
return signer.VerifySignature(signature);
Additional research:
THIS is the Bitcoin source that verifies a message.
After decoding the Base64 of the signature, the RecoverCompact(hash of message, signature) is called. I'm not a C++ programmer so I'm assuming I need to figure out how key.Recover works. That or key.GetPubKey
This is the C++ code that I think I need in C#, ideally in bouncy castle... but I'll take anything that works.
// reconstruct public key from a compact signature
// This is only slightly more CPU intensive than just verifying it.
// If this function succeeds, the recovered public key is guaranteed to be valid
// (the signature is a valid signature of the given data for that key)
bool Recover(const uint256 &hash, const unsigned char *p64, int rec)
{
if (rec<0 || rec>=3)
return false;
ECDSA_SIG *sig = ECDSA_SIG_new();
BN_bin2bn(&p64[0], 32, sig->r);
BN_bin2bn(&p64[32], 32, sig->s);
bool ret = ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), rec, 0) == 1;
ECDSA_SIG_free(sig);
return ret;
}
... the code for ECDSA_SIG_recover_key_GFp is here
Custom signature format in Bitcoin
This answer says there are 4 possible public keys that can produce a signature, and this is encoded in the newer signatures.
| After referencing BitcoinJ, it appears some of these code samples are missing proper preparation of the message, double-SHA256 hashing, and possible compressed encoding of the recovered public point that is input to the address calculation.
The following code should only need BouncyCastle (probably you'll need recent version from github, not sure). It borrows a few things from BitcoinJ, and does just does enough to get small examples working, see inline comments for message size restrictions.
It only calculates up to the RIPEMD-160 hash, and I used http://gobittest.appspot.com/Address to check the final address that results (unfortunately that website doesn't seem to support entering a compressed encoding for the public key).
public static void CheckSignedMessage(string message, string sig64)
{
byte[] sigBytes = Convert.FromBase64String(sig64);
byte[] msgBytes = FormatMessageForSigning(message);
int first = (sigBytes[0] - 27);
bool comp = (first & 4) != 0;
int rec = first & 3;
BigInteger[] sig = ParseSig(sigBytes, 1);
byte[] msgHash = DigestUtilities.CalculateDigest("SHA-256", DigestUtilities.CalculateDigest("SHA-256", msgBytes));
ECPoint Q = Recover(msgHash, sig, rec, true);
byte[] qEnc = Q.GetEncoded(comp);
Console.WriteLine("Q: " + Hex.ToHexString(qEnc));
byte[] qHash = DigestUtilities.CalculateDigest("RIPEMD-160", DigestUtilities.CalculateDigest("SHA-256", qEnc));
Console.WriteLine("RIPEMD-160(SHA-256(Q)): " + Hex.ToHexString(qHash));
Console.WriteLine("Signature verified correctly: " + VerifySignature(Q, msgHash, sig));
}
public static BigInteger[] ParseSig(byte[] sigBytes, int sigOff)
{
BigInteger r = new BigInteger(1, sigBytes, sigOff, 32);
BigInteger s = new BigInteger(1, sigBytes, sigOff + 32, 32);
return new BigInteger[] { r, s };
}
public static ECPoint Recover(byte[] hash, BigInteger[] sig, int recid, bool check)
{
X9ECParameters x9 = SecNamedCurves.GetByName("secp256k1");
BigInteger r = sig[0], s = sig[1];
FpCurve curve = x9.Curve as FpCurve;
BigInteger order = x9.N;
BigInteger x = r;
if ((recid & 2) != 0)
{
x = x.Add(order);
}
if (x.CompareTo(curve.Q) >= 0) throw new Exception("X too large");
byte[] xEnc = X9IntegerConverter.IntegerToBytes(x, X9IntegerConverter.GetByteLength(curve));
byte[] compEncoding = new byte[xEnc.Length + 1];
compEncoding[0] = (byte)(0x02 + (recid & 1));
xEnc.CopyTo(compEncoding, 1);
ECPoint R = x9.Curve.DecodePoint(compEncoding);
if (check)
{
//EC_POINT_mul(group, O, NULL, R, order, ctx))
ECPoint O = R.Multiply(order);
if (!O.IsInfinity) throw new Exception("Check failed");
}
BigInteger e = CalculateE(order, hash);
BigInteger rInv = r.ModInverse(order);
BigInteger srInv = s.Multiply(rInv).Mod(order);
BigInteger erInv = e.Multiply(rInv).Mod(order);
return ECAlgorithms.SumOfTwoMultiplies(R, srInv, x9.G.Negate(), erInv);
}
public static bool VerifySignature(ECPoint Q, byte[] hash, BigInteger[] sig)
{
X9ECParameters x9 = SecNamedCurves.GetByName("secp256k1");
ECDomainParameters ec = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
ECPublicKeyParameters publicKey = new ECPublicKeyParameters(Q, ec);
return VerifySignature(publicKey, hash, sig);
}
public static bool VerifySignature(ECPublicKeyParameters publicKey, byte[] hash, BigInteger[] sig)
{
ECDsaSigner signer = new ECDsaSigner();
signer.Init(false, publicKey);
return signer.VerifySignature(hash, sig[0], sig[1]);
}
private static BigInteger CalculateE(
BigInteger n,
byte[] message)
{
int messageBitLength = message.Length * 8;
BigInteger trunc = new BigInteger(1, message);
if (n.BitLength < messageBitLength)
{
trunc = trunc.ShiftRight(messageBitLength - n.BitLength);
}
return trunc;
}
public static byte[] FormatMessageForSigning(String message)
{
MemoryStream bos = new MemoryStream();
bos.WriteByte((byte)BITCOIN_SIGNED_MESSAGE_HEADER_BYTES.Length);
bos.Write(BITCOIN_SIGNED_MESSAGE_HEADER_BYTES, 0, BITCOIN_SIGNED_MESSAGE_HEADER_BYTES.Length);
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
//VarInt size = new VarInt(messageBytes.length);
//bos.write(size.encode());
// HACK only works for short messages (< 253 bytes)
bos.WriteByte((byte)messageBytes.Length);
bos.Write(messageBytes, 0, messageBytes.Length);
return bos.ToArray();
}
Sample output for the initial data in the question:
Q: 0283437893b491218348bf5ff149325e47eb628ce36f73a1a927ae6cb6021c7ac4
RIPEMD-160(SHA-256(Q)): cbe57ebe20ad59518d14926f8ab47fecc984af49
Signature verified correctly: True
If we plug the RIPEMD-160 value into the address checker, it returns
1Kb76YK9a4mhrif766m321AMocNvzeQxqV
as given in the question.
| Bouncy Castle | 19,665,491 | 26 |
Surprisingly enough there's very little information on the Web about using Bouncy Castle's lightweight API. After looking around for a while I was able to put together a basic example:
RSAKeyPairGenerator generator = new RSAKeyPairGenerator();
generator.init(new RSAKeyGenerationParameters
(
new BigInteger("10001", 16),//publicExponent
SecureRandom.getInstance("SHA1PRNG"),//prng
1024,//strength
80//certainty
));
AsymmetricCipherKeyPair keyPair = generator.generateKeyPair();
I have a basic understanding of RSA and the math that happens behind the scenes, so I understand what publicExponent and strength are. I presume publicExponent refers to a coprime of phi(pq) and from what I gather it can be small (like 3) as long as appropriate padding is used. However, I have no idea what certainty refers to (some place mentioned that it might refer to a percentage but I want to be sure). The use of SecureRandom is self-explanatory. The documentation of RSAKeyGenerationParameters is completely worthless (no surprise there). My only guess is that it has something to do with the accuracy of the generated keys, but again I want to be sure. So my question is what are appropriate values for certainty and publicExponent?
P.S.
Please don't reply with "it depends on the context - how secure you want the information to be". It's pretty safe to assume highest degree of security (i.e. 4096-bit RSA key or greater) unless otherwise specified... I would also appreciate links to sources that give good example of the use of Bouncy Castle's Lightweight API (I'm not at all interested in the JCA implementation or any examples pertaining to it).
| You are using correct values for both.
The publicExponent should be a Fermat Number. 0x10001 (F4) is current recommended value. 3 (F1) is known to be safe also.
The RSA key generation requires prime numbers. However, it's impossible to generate absolute prime numbers. Like any other crypto libraries, BC uses probable prime numbers. The certainty indicate how certain you want the number to be prime. Anything above 80 will slow down key generation considerably.
Please note that RSA algorithm still works in the unlikely event that the prime number is not true prime because BC checks for relative primeness.
| Bouncy Castle | 3,087,049 | 25 |
I am new to the security side of Java and stumbled across this library called BouncyCastle. But the examples that they provide and the ones out on the internet ask to use
return new PKCS10CertificationRequest("SHA256withRSA", new X500Principal(
"CN=Requested Test Certificate"), pair.getPublic(), null, pair.getPrivate()
But when I use PKCS10CertificationRequest, it looks like it is deprecated. So I started looking at another method where I use CertificationRequest class. But I am really confused, the constructor does not take the same parameters instead it takes CertificationRequestInfo class which I am not sure how to fill up.
CertificationRequest request = new CertificationRequest(...);
It would be awesome if someone could help me figure out how to make a CSR so that I can send it to the server for getting it signed.
| With the recent versions of BouncyCastle it is recommended to create the CSR using the org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder class.
You can use this code snipppet:
KeyPair pair = generateKeyPair();
PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
new X500Principal("CN=Requested Test Certificate"), pair.getPublic());
JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
ContentSigner signer = csBuilder.build(pair.getPrivate());
PKCS10CertificationRequest csr = p10Builder.build(signer);
| Bouncy Castle | 20,532,912 | 25 |
I'm trying to use iText Java.
When you run the example "how to sign" the following error occurs:
Caused by: java.lang.ClassNotFoundException: org.bouncycastle.tsp.TimeStampTokenInfo
According "Getting Started with iText - How to sign a PDF using iText", I have to use the BouncyCastle.
I downloaded the file: bcprov-jdk15on-147.jar from BouncyCastle download page.
And added to the project: Java Build Path/Libraries/Add External JARs...
I added the following line:
Security.addProvider(new BouncyCastleProvider());
When you run the example the same error occurs.
So I downloaded another file: bcpkix-jdk15on-147.jar entitled "PKIX/CMS/EAC/PKCS/OCSP/TSP/OPENSSL"
And added to the project: Java Build Path/Libraries/Add External JARs...
Now I have two Jars.
When you run the example the following error occurs:
Caused by: java.lang.ClassNotFoundException: org.bouncycastle.asn1.DEREncodable
I tried downloading the file "bcprov-ext-jdk15on-147.jar" but did not solve the problem.
I am using iText 5.2.1 and eclipse on Windows 7 64 bits.
| iText marks bouncycastle dependencies as optional. If you require them, you need to add the dependencies in your own pom file.
To find out which dependency to include in your project, open the itextpdf pom.xml file of the version you are using (for example 5.3.2, here) and search for the 2 bouncycastle dependencies.
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.47</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcmail-jdk15on</artifactId>
<version>1.47</version>
<optional>true</optional>
</dependency>
Copy them into your pom file and remove the optional option.
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.3.2</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.47</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcmail-jdk15on</artifactId>
<version>1.47</version>
</dependency>
| Bouncy Castle | 10,391,271 | 23 |
I've seen a number of posts, followed a number of tutorials but none seems to work. Sometimes, they make reference to some classes which are not found. Can I be pointed to a place where I can get a simple tutorial showing how to encrypt and decrypt a file.
I'm very new to Pgp and any assistance is welcomed.
| I know this question is years old but it is still #1 or #2 in Google for searches related to PGP Decryption using Bouncy Castle. Since it seems hard to find a complete, succinct example I wanted to share my working solution here for decrypting a PGP file. This is simply a modified version of the Bouncy Castle example included with their source files.
using System;
using System.IO;
using Org.BouncyCastle.Bcpg.OpenPgp;
using Org.BouncyCastle.Utilities.IO;
namespace PGPDecrypt
{
class Program
{
static void Main(string[] args)
{
DecryptFile(
@"path_to_encrypted_file.pgp",
@"path_to_secret_key.asc",
"your_password_here".ToCharArray(),
"output.txt"
);
}
private static void DecryptFile(
string inputFileName,
string keyFileName,
char[] passwd,
string defaultFileName)
{
using (Stream input = File.OpenRead(inputFileName),
keyIn = File.OpenRead(keyFileName))
{
DecryptFile(input, keyIn, passwd, defaultFileName);
}
}
private static void DecryptFile(
Stream inputStream,
Stream keyIn,
char[] passwd,
string defaultFileName)
{
inputStream = PgpUtilities.GetDecoderStream(inputStream);
try
{
PgpObjectFactory pgpF = new PgpObjectFactory(inputStream);
PgpEncryptedDataList enc;
PgpObject o = pgpF.NextPgpObject();
//
// the first object might be a PGP marker packet.
//
if (o is PgpEncryptedDataList)
{
enc = (PgpEncryptedDataList)o;
}
else
{
enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
}
//
// find the secret key
//
PgpPrivateKey sKey = null;
PgpPublicKeyEncryptedData pbe = null;
PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(
PgpUtilities.GetDecoderStream(keyIn));
foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
{
sKey = FindSecretKey(pgpSec, pked.KeyId, passwd);
if (sKey != null)
{
pbe = pked;
break;
}
}
if (sKey == null)
{
throw new ArgumentException("secret key for message not found.");
}
Stream clear = pbe.GetDataStream(sKey);
PgpObjectFactory plainFact = new PgpObjectFactory(clear);
PgpObject message = plainFact.NextPgpObject();
if (message is PgpCompressedData)
{
PgpCompressedData cData = (PgpCompressedData)message;
PgpObjectFactory pgpFact = new PgpObjectFactory(cData.GetDataStream());
message = pgpFact.NextPgpObject();
}
if (message is PgpLiteralData)
{
PgpLiteralData ld = (PgpLiteralData)message;
string outFileName = ld.FileName;
if (outFileName.Length == 0)
{
outFileName = defaultFileName;
}
Stream fOut = File.Create(outFileName);
Stream unc = ld.GetInputStream();
Streams.PipeAll(unc, fOut);
fOut.Close();
}
else if (message is PgpOnePassSignatureList)
{
throw new PgpException("encrypted message contains a signed message - not literal data.");
}
else
{
throw new PgpException("message is not a simple encrypted file - type unknown.");
}
if (pbe.IsIntegrityProtected())
{
if (!pbe.Verify())
{
Console.Error.WriteLine("message failed integrity check");
}
else
{
Console.Error.WriteLine("message integrity check passed");
}
}
else
{
Console.Error.WriteLine("no message integrity check");
}
}
catch (PgpException e)
{
Console.Error.WriteLine(e);
Exception underlyingException = e.InnerException;
if (underlyingException != null)
{
Console.Error.WriteLine(underlyingException.Message);
Console.Error.WriteLine(underlyingException.StackTrace);
}
}
}
private static PgpPrivateKey FindSecretKey(PgpSecretKeyRingBundle pgpSec, long keyID, char[] pass)
{
PgpSecretKey pgpSecKey = pgpSec.GetSecretKey(keyID);
if (pgpSecKey == null)
{
return null;
}
return pgpSecKey.ExtractPrivateKey(pass);
}
}
}
| Bouncy Castle | 6,987,699 | 22 |
I'm creating a certificate distribution system to keep track of clients and stuff.
What happens is:
Client send CSR to Server
Server checks and signs certificate
Server sends Signed certificate to Client
Client puts Signed certificate plus Private key in Windows store.
So on the client this happens:
//Pseudo Server Object:
Server s = new Server();
//Requested Certificate Name and things
X509Name name = new X509Name("CN=Client Cert, C=NL");
//Key generation 2048bits
RsaKeyPairGenerator rkpg = new RsaKeyPairGenerator();
rkpg.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
AsymmetricCipherKeyPair ackp = rkpg.GenerateKeyPair();
//PKCS #10 Certificate Signing Request
Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest("SHA1WITHRSA", name, ackp.Public, null, ackp.Private);
//Make it a nice PEM thingie
StringBuilder sb = new StringBuilder();
PemWriter pemwrit = new PemWriter(new StringWriter(b));
pemwrit.WriteObject(csr);
pemwrit.Writer.Flush();
s.SendRequest(sb.ToSting());
Ok So I'll skip serverside Just trust me the server signs the cert and send it back to the client. Thats where I'll pick up the action.
PemReader pr = new PemReader(new StringReader(b.ToString()));
X509Certificate cert = (X509Certificate)pr.ReadObject();
//So lets asume I saved the AsymmetricCipherKeyPair (ackp) from before
//I have now the certificate and my private key;
//first I make it a "Microsoft" x509cert.
//This however does not have a PrivateKey thats in the AsymmetricCipherKeyPair (ackp)
System.Security.Cryptography.X509Certificates.X509Certificate2 netcert = DotNetUtilities.ToX509Certificate(cert);
//So here comes the RSACryptoServerProvider:
System.Security.Cryptography.RSACryptoServiceProvider rcsp = new System.Security.Cryptography.RSACryptoServiceProvider();
//And the privateKeyParameters
System.Security.Cryptography.RSAParameters parms = new System.Security.Cryptography.RSAParameters();
//now I have to translate ackp.PrivateKey to parms;
RsaPrivateCrtKeyParameters BCKeyParms = ((RsaPrivateCrtKeyParameters)ackp1.Private);
//D is the private exponent
parms.Modulus = BCKeyParms.Modulus.ToByteArray();
parms.P = BCKeyParms.P.ToByteArray();
parms.Q = BCKeyParms.Q.ToByteArray();
parms.DP = BCKeyParms.DP.ToByteArray();
parms.DQ = BCKeyParms.DQ.ToByteArray();
parms.InverseQ = BCKeyParms.QInv.ToByteArray();
parms.D = BCKeyParms.Exponent.ToByteArray();
parms.Exponent = BCKeyParms.PublicExponent.ToByteArray();
//Now I should be able to import the RSAParameters into the RSACryptoServiceProvider
rcsp.ImportParameters(parms);
//<em><b>not really</b></em> This breaks says "Bad Data" and not much more. I'll Post the
//stacktrace at the end
//I open up the windows cert store because thats where I want to save it.
//Add it and save it this works fine without the privkey.
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.MaxAllowed);
store.Add(netcert);
store.Close();
Now you're probably thinking there must be something going wrong at the server side. Well thats what I thought too but When I made a pfx file from this cert and imported it by hand it worked fine ....
Somehow there's a diference bewteen a .NET RSA privatekey and a BouncyCastle RSA privatekey and I can't put my finger on it.
You will probably suggest to import the pfx and then get the private key from it via the X509Store. I tried. :S And failed. As soon as I try to ExportParameters(true) the true stands for including privateparameters. It says "Key not valid for use in specified state.". See for complete exception at the end.
I hope some of you have slain this pig before or might be able to help me.
***Exceptions:***
System.Security.Cryptography.CryptographicException was unhandled
Message="Key not valid for use in specified state.\r\n"
Source="mscorlib"
StackTrace:
at System.Security.Cryptography.CryptographicException.ThrowCryptogaphicException(Int32 hr)
at System.Security.Cryptography.Utils._ExportKey(SafeKeyHandle hKey, Int32 blobType, Object cspObject)
at System.Security.Cryptography.RSACryptoServiceProvider.ExportParameters(Boolean includePrivateParameters)
InnerException:
***And the other one:***
System.Security.Cryptography.CryptographicException was unhandled
Message="Bad Data.\r\n"
Source="mscorlib"
StackTrace:
at System.Security.Cryptography.CryptographicException.ThrowCryptogaphicException(Int32 hr)
at System.Security.Cryptography.Utils._ImportKey(SafeProvHandle hCSP, Int32 keyNumber, CspProviderFlags flags, Object cspObject, SafeKeyHandle& hKey)
at System.Security.Cryptography.RSACryptoServiceProvider.ImportParameters(RSAParameters parameters)
InnerException:
| The answer (from username) points to the right direction: padding.
Bouncy-castle's latest version from git has the following code:
public static RSAParameters ToRSAParameters(RsaPrivateCrtKeyParameters privKey)
{
RSAParameters rp = new RSAParameters();
rp.Modulus = privKey.Modulus.ToByteArrayUnsigned();
rp.Exponent = privKey.PublicExponent.ToByteArrayUnsigned();
rp.P = privKey.P.ToByteArrayUnsigned();
rp.Q = privKey.Q.ToByteArrayUnsigned();
rp.D = ConvertRSAParametersField(privKey.Exponent, rp.Modulus.Length);
rp.DP = ConvertRSAParametersField(privKey.DP, rp.P.Length);
rp.DQ = ConvertRSAParametersField(privKey.DQ, rp.Q.Length);
rp.InverseQ = ConvertRSAParametersField(privKey.QInv, rp.Q.Length);
return rp;
}
private static byte[] ConvertRSAParametersField(BigInteger n, int size)
{
byte[] bs = n.ToByteArrayUnsigned();
if (bs.Length == size)
return bs;
if (bs.Length > size)
throw new ArgumentException("Specified size too small", "size");
byte[] padded = new byte[size];
Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);
return padded;
}
nb: This code in not in the nuget version (2011) of bouncy castle, or in most code samples were RSA parameters are simply copied.
This code is different from the code you can see anywhere else which basically copy/paste the key parameters, and does not perform the extra padding step.
| Bouncy Castle | 949,727 | 20 |
I'm having problems inserting a new CA certificate with privatekey in the Root certificate store of the localmachine.
This is what happens:
//This doesn't help either.
new StorePermission (PermissionState.Unrestricted) { Flags = StorePermissionFlags.AddToStore }.Assert();
var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
privkey.PersistKeyInCsp = true;
//This shouldn't be necessary doesn't make a difference what so ever.
RSACryptoServiceProvider.UseMachineKeyStore = true;
cert.PrivateKey = privkey;
store.Open (OpenFlags.MaxAllowed);
store.Add (cert);
store.Close ();
The certificate gets inserted and it all looks dandy: (see!)
Note: is says it has a privatekey.
So you'd say one would be able to find it with FindPrivateKey
C:\Users\Administrator\Desktop>FindPrivateKey.exe Root LocalMachine -t "54 11 b1 f4 31 99 19 d3 5a f0 5f 01 95 fc aa 6f 71 12 13 eb"
FindPrivateKey failed for the following reason:
Unable to obtain private key file name
Use /? option for help
It's cute .... BUT IT'S WRONG!! (2 stupid dogs reference)
And the Certificate export dialog gives me this very fine message:
This code is run while impersonating an administrator using this snippet: click here
I'd just love to know WHY?
(tested on Windows Server 2008 R2 & Windows 7)
I'll be damned!
It works when I compile it to v3.5!!!!
What to do?
| I had exactly the same problem and the solution turned out to be really simple.
All I had to do is to pass
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
to X509Certificate2's ctor.
Now you are using the DotNetUtilities to convert the bouncycastle certificate to the .net one, but the helper method creates the .net cert with the DefaultKeySet (instead of MachineKeySet + PersistKeySet
).
And arrange the private key like this:
var cspParams = new CspParameters
{
KeyContainerName = Guid.NewGuid().ToString(),
KeyNumber = (int)KeyNumber.Exchange,
Flags = CspProviderFlags.UseMachineKeyStore
};
var rsaProvider = new RSACryptoServiceProvider(cspParams);
I hope this helps.
| Bouncy Castle | 3,625,624 | 20 |
I am using the "BouncyCastle.Crypto.dll" for encrypt/decrypt a string in my app. I am using the
following code from this blog:
I have a class BCEngine, exactly the same as the one given in the link mentioned above.
public class BCEngine
{
private readonly Encoding _encoding;
private readonly IBlockCipher _blockCipher;
private PaddedBufferedBlockCipher _cipher;
private IBlockCipherPadding _padding;
public BCEngine(IBlockCipher blockCipher, Encoding encoding)
{
_blockCipher = blockCipher;
_encoding = encoding;
}
public void SetPadding(IBlockCipherPadding padding)
{
if (padding != null)
_padding = padding;
}
public string Encrypt(string plain, string key)
{
byte[] result = BouncyCastleCrypto(true, _encoding.GetBytes(plain), key);
return Convert.ToBase64String(result);
}
public string Decrypt(string cipher, string key)
{
byte[] result = BouncyCastleCrypto(false, Convert.FromBase64String(cipher), key);
return _encoding.GetString(result);
}
/// <summary>
///
/// </summary>
/// <param name="forEncrypt"></param>
/// <param name="input"></param>
/// <param name="key"></param>
/// <returns></returns>
/// <exception cref="CryptoException"></exception>
private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key)
{
try
{
_cipher = _padding == null ? new PaddedBufferedBlockCipher(_blockCipher) : new PaddedBufferedBlockCipher(_blockCipher, _padding);
byte[] keyByte = _encoding.GetBytes(key);
_cipher.Init(forEncrypt, new KeyParameter(keyByte));
return _cipher.DoFinal(input);
}
catch (Org.BouncyCastle.Crypto.CryptoException ex)
{
throw new CryptoException(ex.Message);
}
}
}
I am using an asp.net form in which i have written code as given below:
public partial class EncryptionForm : System.Web.UI.Page
{
Encoding _encoding;
IBlockCipherPadding _padding;
string key = "DFGFRT";
string textToBeEncrypted = "Original text. Please encrypt me.";
string txtEncryptedText = string.empty;
string txtDecryptedText = string.empty;
protected void Page_Load(object sender, EventArgs e)
{
_encoding = Encoding.ASCII;
Pkcs7Padding pkcs = new Pkcs7Padding();
_padding = pkcs;
}
protected void btnEncrypt_Click(object sender, EventArgs e)
{
txtEncryptedText = AESEncryption(textToBeEncrypted, key, true);
}
protected void btnDecrypt_Click(object sender, EventArgs e)
{
txtDecryptedText = AESDecryption(txtEncryptedText.Text, key, true);
}
public string AESEncryption(string plain, string key, bool fips)
{
BCEngine bcEngine = new BCEngine(new AesEngine(), _encoding);
bcEngine.SetPadding(_padding);
return bcEngine.Encrypt(plain, key);
}
public string AESDecryption(string cipher, string key, bool fips)
{
BCEngine bcEngine = new BCEngine(new AesEngine(), _encoding);
bcEngine.SetPadding(_padding);
return bcEngine.Decrypt(cipher, key);
}
}
Not sure, but due to some reason, I get an exception when I call the btnEncrypt_Click
"Key length not 128/192/256 bits."
Can anybody please guide? I am a complete newbie to this.
Thanks in Advance.
| Your string key = "DFGFRT"; is not 128/192/256 bits.
DFGFRT is 6 characters, which is 6 (or 12?) bytes = 8*12 = 96 bits (at most).
To get a 128 bit key you need a 16 byte string, so I'd go on the safe side and use a 16 character string so it will be a 128 bit key if using single byte characters and 256 if using wide characters.
| Bouncy Castle | 5,910,454 | 20 |
Can you help me to find a simple tutorial of how sign a string using ECDSA algorithm in java. But without using any third-party libraries like bouncycastle. Just JDK 7. I found it difficult to search a simple example, I'm new to cryptography.
import java.io.*;
import java.security.*;
public class GenSig {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
/*
* Generate a DSA signature
*/
try {
/*
* Generate a key pair
*/
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
/*
* Create a Signature object and initialize it with the private key
*/
Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");
dsa.initSign(priv);
String str = "This is string to sign";
byte[] strByte = str.getBytes();
dsa.update(strByte);
/*
* Now that all the data to be signed has been read in, generate a
* signature for it
*/
byte[] realSig = dsa.sign();
System.out.println("Signature: " + new String(realSig));
} catch (Exception e) {
System.err.println("Caught exception " + e.toString());
}
}
}
How to modify it for ECDSA?
| Here is small example based on your example.
NOTE: this is the original code for this answer, please see the next code snippet for an updated version.
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
public class ECDSAExample {
public static void main(String[] args) throws Exception {
/*
* Generate an ECDSA signature
*/
/*
* Generate a key pair
*/
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
keyGen.initialize(256, random);
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
/*
* Create a Signature object and initialize it with the private key
*/
Signature dsa = Signature.getInstance("SHA1withECDSA");
dsa.initSign(priv);
String str = "This is string to sign";
byte[] strByte = str.getBytes("UTF-8");
dsa.update(strByte);
/*
* Now that all the data to be signed has been read in, generate a
* signature for it
*/
byte[] realSig = dsa.sign();
System.out.println("Signature: " + new BigInteger(1, realSig).toString(16));
}
}
UPDATE: Here is slightly improved example removing deprecated algorithms. It also explicitly requests the NIST P-256 curve using the SECG notation "secp256r1" as specified in RFC 8422.
import java.math.BigInteger;
import java.security.*;
import java.security.spec.ECGenParameterSpec;
public class ECDSAExample {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
/*
* Generate an ECDSA signature
*/
/*
* Generate a key pair
*/
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
keyGen.initialize(new ECGenParameterSpec("secp256r1"), new SecureRandom());
KeyPair pair = keyGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
/*
* Create a Signature object and initialize it with the private key
*/
Signature ecdsa = Signature.getInstance("SHA256withECDSA");
ecdsa.initSign(priv);
String str = "This is string to sign";
byte[] strByte = str.getBytes("UTF-8");
ecdsa.update(strByte);
/*
* Now that all the data to be signed has been read in, generate a
* signature for it
*/
byte[] realSig = ecdsa.sign();
System.out.println("Signature: " + new BigInteger(1, realSig).toString(16));
}
}
| Bouncy Castle | 11,339,788 | 20 |
In my build process, I want to include a timestamp from an RFC-3161-compliant TSA. At run time, the code will verify this timestamp, preferably without the assistance of a third-party library. (This is a .NET application, so I have standard hash and asymmetric cryptography functionality readily at my disposal.)
RFC 3161, with its reliance on ASN.1 and X.690 and whatnot, is not simple to implement, so for now at least, I'm using Bouncy Castle to generate the TimeStampReq (request) and parse the TimeStampResp (response). I just can't quite figure out how to validate the response.
So far, I've figured out how to extract the signature itself, the public cert, the time the timestamp was created, and the message imprint digest and nonce that I sent (for build-time validation). What I can't figure out is how to put this data together to generate the data that was hashed and signed.
Here's a rough idea of what I'm doing and what I'm trying to do. This is test code, so I've taken some shortcuts. I'll have to clean a couple of things up and do them the right way once I get something that works.
Timestamp generation at build time:
// a lot of fully-qualified type names here to make sure it's clear what I'm using
static void WriteTimestampToBuild(){
var dataToTimestamp = Encoding.UTF8.GetBytes("The rain in Spain falls mainly on the plain");
var hashToTimestamp = new System.Security.Cryptography.SHA1Cng().ComputeHash(dataToTimestamp);
var nonce = GetRandomNonce();
var tsr = GetTimestamp(hashToTimestamp, nonce, "http://some.rfc3161-compliant.server");
var tst = tsr.TimeStampToken;
var tsi = tst.TimeStampInfo;
ValidateNonceAndHash(tsi, hashToTimestamp, nonce);
var cms = tst.ToCmsSignedData();
var signer =
cms.GetSignerInfos().GetSigners()
.Cast<Org.BouncyCastle.Cms.SignerInformation>().First();
// TODO: handle multiple signers?
var signature = signer.GetSignature();
var cert =
tst.GetCertificates("Collection").GetMatches(signer.SignerID)
.Cast<Org.BouncyCastle.X509.X509Certificate>().First();
// TODO: handle multiple certs (for one or multiple signers)?
ValidateCert(cert);
var timeString = tsi.TstInfo.GenTime.TimeString;
var time = tsi.GenTime; // not sure which is more useful
// TODO: Do I care about tsi.TstInfo.Accuracy or tsi.GenTimeAccuracy?
var serialNumber = tsi.SerialNumber.ToByteArray(); // do I care?
WriteToBuild(cert.GetEncoded(), signature, timeString/*or time*/, serialNumber);
// TODO: Do I need to store any more values?
}
static Org.BouncyCastle.Math.BigInteger GetRandomNonce(){
var rng = System.Security.Cryptography.RandomNumberGenerator.Create();
var bytes = new byte[10]; // TODO: make it a random length within a range
rng.GetBytes(bytes);
return new Org.BouncyCastle.Math.BigInteger(bytes);
}
static Org.BouncyCastle.Tsp.TimeStampResponse GetTimestamp(byte[] hash, Org.BouncyCastle.Math.BigInteger nonce, string url){
var reqgen = new Org.BouncyCastle.Tsp.TimeStampRequestGenerator();
reqgen.SetCertReq(true);
var tsrequest = reqgen.Generate(Org.BouncyCastle.Tsp.TspAlgorithms.Sha1, hash, nonce);
var data = tsrequest.GetEncoded();
var webreq = WebRequest.CreateHttp(url);
webreq.Method = "POST";
webreq.ContentType = "application/timestamp-query";
webreq.ContentLength = data.Length;
using(var reqStream = webreq.GetRequestStream())
reqStream.Write(data, 0, data.Length);
using(var respStream = webreq.GetResponse().GetResponseStream())
return new Org.BouncyCastle.Tsp.TimeStampResponse(respStream);
}
static void ValidateNonceAndHash(Org.BouncyCastle.Tsp.TimeStampTokenInfo tsi, byte[] hashToTimestamp, Org.BouncyCastle.Math.BigInteger nonce){
if(tsi.Nonce != nonce)
throw new Exception("Nonce doesn't match. Man-in-the-middle attack?");
var messageImprintDigest = tsi.GetMessageImprintDigest();
var hashMismatch =
messageImprintDigest.Length != hashToTimestamp.Length ||
Enumerable.Range(0, messageImprintDigest.Length).Any(i=>
messageImprintDigest[i] != hashToTimestamp[i]
);
if(hashMismatch)
throw new Exception("Message imprint doesn't match. Man-in-the-middle attack?");
}
static void ValidateCert(Org.BouncyCastle.X509.X509Certificate cert){
// not shown, but basic X509Chain validation; throw exception on failure
// TODO: Validate certificate subject and policy
}
static void WriteToBuild(byte[] cert, byte[] signature, string time/*or DateTime time*/, byte[] serialNumber){
// not shown
}
Timestamp verification at run time (client site):
// a lot of fully-qualified type names here to make sure it's clear what I'm using
static void VerifyTimestamp(){
var timestampedData = Encoding.UTF8.GetBytes("The rain in Spain falls mainly on the plain");
var timestampedHash = new System.Security.Cryptography.SHA1Cng().ComputeHash(timestampedData);
byte[] certContents;
byte[] signature;
string time; // or DateTime time
byte[] serialNumber;
GetDataStoredDuringBuild(out certContents, out signature, out time, out serialNumber);
var cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certContents);
ValidateCert(cert);
var signedData = MagicallyCombineThisStuff(timestampedHash, time, serialNumber);
// TODO: What other stuff do I need to magically combine?
VerifySignature(signedData, signature, cert);
// not shown: Use time from timestamp to validate cert for other signed data
}
static void GetDataStoredDuringBuild(out byte[] certContents, out byte[] signature, out string/*or DateTime*/ time, out byte[] serialNumber){
// not shown
}
static void ValidateCert(System.Security.Cryptography.X509Certificates.X509Certificate2 cert){
// not shown, but basic X509Chain validation; throw exception on failure
}
static byte[] MagicallyCombineThisStuff(byte[] timestampedhash, string/*or DateTime*/ time, byte[] serialNumber){
// HELP!
}
static void VerifySignature(byte[] signedData, byte[] signature, System.Security.Cryptography.X509Certificates.X509Certificate2 cert){
var key = (RSACryptoServiceProvider)cert.PublicKey.Key;
// TODO: Handle DSA keys, too
var okay = key.VerifyData(signedData, CryptoConfig.MapNameToOID("SHA1"), signature);
// TODO: Make sure to use the same hash algorithm as the TSA
if(!okay)
throw new Exception("Timestamp doesn't match! Don't trust this!");
}
As you might guess, where I think I'm stuck is the MagicallyCombineThisStuff function.
| I finally figured it out myself. It should come as no surprise, but the answer is nauseatingly complex and indirect.
The missing pieces to the puzzle were in RFC 5652. I didn't really understand the TimeStampResp structure until I read (well, skimmed through) that document.
Let me describe in brief the TimeStampReq and TimeStampResp structures. The interesting fields of the request are:
a "message imprint", which is the hash of the data to be timestamped
the OID of the hash algorithm used to create the message imprint
an optional "nonce", which is a client-chosen identifier used to verify that the response is generated specifically for this request. This is effectively just a salt, used to avoid replay attacks and to detect errors.
The meat of the response is a CMS SignedData structure. Among the fields in this structure are:
the certificate(s) used to sign the response
an EncapsulatedContentInfo member containing a TSTInfo structure. This structure, importantly, contains:
the message imprint that was sent in the request
the nonce that was sent in the request
the time certified by the TSA
a set of SignerInfo structures, with typically just one structure in the set. For each SignerInfo, the interesting fields within the structure are:
a sequence of "signed attributes". The DER-encoded BLOB of this sequence is what is actually signed. Among these attributes are:
the time certified by the TSA (again)
a hash of the DER-encoded BLOB of the TSTInfo structure
an issuer and serial number or subject key identifier that identifies the signer's certificate from the set of certificates found in the SignedData structure
the signature itself
The basic process of validating the timestamp is as follows:
Read the data that was timestamped, and recompute the message imprint using the same hashing algorithm used in the timestamp request.
Read the nonce used in the timestamp request, which must be stored along with the timestamp for this purpose.
Read and parse the TimeStampResp structure.
Verify that the TSTInfo structure contains the correct message imprint and nonce.
From the TimeStampResp, read the certificate(s).
For each SignerInfo:
Find the certificate for that signer (there should be exactly one).
Verify the certificate.
Using that certificate, verify the signer's signature.
Verify that the signed attributes contain the correct hash of the TSTInfo structure
If everything is okay, then we know that all signed attributes are valid, since they're signed, and since those attributes contain a hash of the TSTInfo structure, then we know that's okay, too. We have therefore validated that the timestamped data is unchanged since the time given by the TSA.
Because the signed data is a DER-encoded BLOB (which contains a hash of the different DER-encoded BLOB containing the information the verifier actually cares about), there's no getting around having some sort of library on the client (verifier) that understands X.690 encoding and ASN.1 types. Therefore, I conceded to including Bouncy Castle in the client as well as in the build process, since there's no way I have time to implement those standards myself.
My code to add and verify timestamps is similar to the following:
Timestamp generation at build time:
// a lot of fully-qualified type names here to make sure it's clear what I'm using
static void WriteTimestampToBuild(){
var dataToTimestamp = ... // see OP
var hashToTimestamp = ... // see OP
var nonce = ... // see OP
var tsq = GetTimestampRequest(hashToTimestamp, nonce);
var tsr = GetTimestampResponse(tsq, "http://some.rfc3161-compliant.server");
ValidateTimestamp(tsq, tsr);
WriteToBuild("tsq-hashalg", Encoding.UTF8.GetBytes("SHA1"));
WriteToBuild("nonce", nonce.ToByteArray());
WriteToBuild("timestamp", tsr.GetEncoded());
}
static Org.BouncyCastle.Tsp.TimeStampRequest GetTimestampRequest(byte[] hash, Org.BouncyCastle.Math.BigInteger nonce){
var reqgen = new TimeStampRequestGenerator();
reqgen.SetCertReq(true);
return reqgen.Generate(TspAlgorithms.Sha1/*assumption*/, hash, nonce);
}
static void GetTimestampResponse(Org.BouncyCastle.Tsp.TimeStampRequest tsq, string url){
// similar to OP
}
static void ValidateTimestamp(Org.BouncyCastle.Tsp.TimeStampRequest tsq, Org.BouncyCastle.Tsp.TimeStampResponse tsr){
// same as client code, see below
}
static void WriteToBuild(string key, byte[] value){
// not shown
}
Timestamp verification at run time (client site):
/* Just like in the OP, I've used fully-qualified names here to avoid confusion.
* In my real code, I'm not doing that, for readability's sake.
*/
static DateTime GetTimestamp(){
var timestampedData = ReadFromBuild("timestamped-data");
var hashAlg = Encoding.UTF8.GetString(ReadFromBuild("tsq-hashalg"));
var timestampedHash = System.Security.Cryptography.HashAlgorithm.Create(hashAlg).ComputeHash(timestampedData);
var nonce = new Org.BouncyCastle.Math.BigInteger(ReadFromBuild("nonce"));
var tsq = new Org.BouncyCastle.Tsp.TimeStampRequestGenerator().Generate(System.Security.Cryptography.CryptoConfig.MapNameToOID(hashAlg), timestampedHash, nonce);
var tsr = new Org.BouncyCastle.Tsp.TimeStampResponse(ReadFromBuild("timestamp"));
ValidateTimestamp(tsq, tsr);
// if we got here, the timestamp is okay, so we can trust the time it alleges
return tsr.TimeStampToken.TimeStampInfo.GenTime;
}
static void ValidateTimestamp(Org.BouncyCastle.Tsp.TimeStampRequest tsq, Org.BouncyCastle.Tsp.TimeStampResponse tsr){
/* This compares the nonce and message imprint and whatnot in the TSTInfo.
* It throws an exception if they don't match. This doesn't validate the
* certs or signatures, though. We still have to do that in order to trust
* this data.
*/
tsr.Validate(tsq);
var tst = tsr.TimeStampToken;
var timestamp = tst.TimeStampInfo.GenTime;
var signers = tst.ToCmsSignedData().GetSignerInfos().GetSigners().Cast<Org.BouncyCastle.Cms.SignerInformation>();
var certs = tst.GetCertificates("Collection");
foreach(var signer in signers){
var signerCerts = certs.GetMatches(signer.SignerID).Cast<Org.BouncyCastle.X509.X509Certificate>().ToList();
if(signerCerts.Count != 1)
throw new Exception("Expected exactly one certificate for each signer in the timestamp");
if(!signerCerts[0].IsValid(timestamp)){
/* IsValid only checks whether the given time is within the certificate's
* validity period. It doesn't verify that it's a valid certificate or
* that it hasn't been revoked. It would probably be better to do that
* kind of thing, just like I'm doing for the signing certificate itself.
* What's more, I'm not sure it's a good idea to trust the timestamp given
* by the TSA to verify the validity of the TSA's certificate. If the
* TSA's certificate is compromised, then an unauthorized third party could
* generate a TimeStampResp with any timestamp they wanted. But this is a
* chicken-and-egg scenario that my brain is now too tired to keep thinking
* about.
*/
throw new Exception("The timestamp authority's certificate is expired or not yet valid.");
}
if(!signer.Verify(signerCerts[0])){ // might throw an exception, might not ... depends on what's wrong
/* I'm pretty sure that signer.Verify verifies the signature and that the
* signed attributes contains a hash of the TSTInfo. It also does some
* stuff that I didn't identify in my list above.
* Some verification errors cause it to throw an exception, some just
* cause it to return false. If it throws an exception, that's great,
* because that's what I'm counting on. If it returns false, let's
* throw an exception of our own.
*/
throw new Exception("Invalid signature");
}
}
}
static byte[] ReadFromBuild(string key){
// not shown
}
| Bouncy Castle | 19,528,456 | 20 |